diff --git a/.gitattributes b/.gitattributes index e4069148544207463a437f44946bb4b536a777a5..fce6f0f665da989f20d5a2c86b2ceaa2179bebeb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -331,3 +331,4 @@ python_embeded/Lib/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs python_embeded/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text python_embeded/Lib/site-packages/numpy/random/lib/npyrandom.lib filter=lfs diff=lfs merge=lfs -text python_embeded/Lib/site-packages/onnxruntime/capi/onnxruntime.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/Lib/site-packages/numpy/core/lib/npymath.lib filter=lfs diff=lfs merge=lfs -text diff --git a/python_embeded/Lib/site-packages/kornia-0.8.1.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/kornia-0.8.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia-0.8.1.dist-info/licenses/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b44c388c507dfd0b312557186297cf26db19dd96 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/__init__.py @@ -0,0 +1,20 @@ +# 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. +# + +from kornia.augmentation._2d.geometric import * +from kornia.augmentation._2d.intensity import * +from kornia.augmentation._2d.mix import * diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/base.py new file mode 100644 index 0000000000000000000000000000000000000000..18360b5a4d52ab72cddd95f10f4b2dc11474c9ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/base.py @@ -0,0 +1,151 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from torch import float16, float32, float64 + +from kornia.augmentation.base import _AugmentationBase +from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype +from kornia.core import Tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints +from kornia.utils import eye_like, is_autocast_enabled + + +class AugmentationBase2D(_AugmentationBase): + r"""AugmentationBase2D base class for customized augmentation implementations. + + AugmentationBase2D aims at offering a generic base class for a greater level of customization. + If the subclass contains routined matrix-based transformations, `RigidAffineAugmentationBase2D` + might be a better fit. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch + form ``False``. + + """ + + def validate_tensor(self, input: Tensor) -> None: + """Check if the input tensor is formatted as expected.""" + _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64]) + if len(input.shape) != 4: + raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.") + + def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor: + """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W).""" + _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64]) + + if shape is None: + return _transform_input(input) + else: + return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel) + + +class RigidAffineAugmentationBase2D(AugmentationBase2D): + r"""AugmentationBase2D base class for rigid/affine augmentation implementations. + + RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices + for different data types like masks, boxes, and keypoints. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch + form ``False``. + + """ + + _transform_matrix: Optional[Tensor] + + @property + def transform_matrix(self) -> Optional[Tensor]: + return self._transform_matrix + + def identity_matrix(self, input: Tensor) -> Tensor: + """Return 3x3 identity matrix.""" + return eye_like(3, input) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + raise NotImplementedError + + def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + """Generate transformation matrices with the given input and param settings.""" + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + + in_tensor = self.transform_tensor(input) + if not to_apply.any(): + trans_matrix = self.identity_matrix(in_tensor) + elif to_apply.all(): + trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags) + else: + trans_matrix_A = self.identity_matrix(in_tensor) + trans_matrix_B = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags) + + if is_autocast_enabled(): + trans_matrix_A = trans_matrix_A.type(input.dtype) + trans_matrix_B = trans_matrix_B.type(input.dtype) + + trans_matrix = trans_matrix_A.index_put((to_apply,), trans_matrix_B) + + return trans_matrix + + def inverse_inputs( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def inverse_masks( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def inverse_boxes( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + raise NotImplementedError + + def inverse_keypoints( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + raise NotImplementedError + + def inverse_classes( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def apply_func( + self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None + ) -> Tensor: + if flags is None: + flags = self.flags + + trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags) + output = self.transform_inputs(in_tensor, params, flags, trans_matrix) + self._transform_matrix = trans_matrix + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef714e3e8ac5141d73b709c61944f4d9691f35e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/__init__.py @@ -0,0 +1,32 @@ +# 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. +# + +from kornia.augmentation._2d.geometric.affine import RandomAffine +from kornia.augmentation._2d.geometric.center_crop import CenterCrop +from kornia.augmentation._2d.geometric.crop import RandomCrop +from kornia.augmentation._2d.geometric.elastic_transform import RandomElasticTransform +from kornia.augmentation._2d.geometric.fisheye import RandomFisheye +from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlip +from kornia.augmentation._2d.geometric.pad import PadTo +from kornia.augmentation._2d.geometric.perspective import RandomPerspective +from kornia.augmentation._2d.geometric.resize import LongestMaxSize, Resize, SmallestMaxSize +from kornia.augmentation._2d.geometric.resized_crop import RandomResizedCrop +from kornia.augmentation._2d.geometric.rotation import RandomRotation, RandomRotation90 +from kornia.augmentation._2d.geometric.shear import RandomShear +from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline +from kornia.augmentation._2d.geometric.translate import RandomTranslate +from kornia.augmentation._2d.geometric.vertical_flip import RandomVerticalFlip diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/affine.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/affine.py new file mode 100644 index 0000000000000000000000000000000000000000..5a78c77c7a6470c8c6b8bcd1c89442d61e3d1987 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/affine.py @@ -0,0 +1,156 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample, SamplePadding +from kornia.core import Tensor, as_tensor +from kornia.geometry.conversions import deg2rad +from kornia.geometry.transform import get_affine_matrix2d, warp_affine + + +class RandomAffine(GeometricAugmentationBase2D): + r"""Apply a random 2D affine transformation to a tensor image. + + .. image:: _static/img/RandomAffine.png + + The transformation is computed so that the image center is kept invariant. + + Args: + degrees: Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). Set to 0 to deactivate rotations. + translate: tuple of maximum absolute fraction for horizontal + and vertical translations. For example translate=(a, b), then horizontal shift + is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is + randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. + scale: scaling factor interval. + If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b. + If (a, b, c, d), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d. + Will keep original scale by default. + shear: Range of degrees to select from. + If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied. + If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied. + If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) + will be applied. Will not apply shear by default. + resample: resample mode from "nearest" (0) or "bilinear" (1). + padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.warp_affine`. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3) + >>> aug = RandomAffine((-15., 20.), p=1.) + >>> out = aug(input) + >>> out, aug.transform_matrix + (tensor([[[[0.3961, 0.7310, 0.1574], + [0.1781, 0.3074, 0.5648], + [0.4804, 0.8379, 0.4234]]]]), tensor([[[ 0.9923, -0.1241, 0.1319], + [ 0.1241, 0.9923, -0.1164], + [ 0.0000, 0.0000, 1.0000]]])) + >>> aug.inverse(out) + tensor([[[[0.3890, 0.6573, 0.1865], + [0.2063, 0.3074, 0.5459], + [0.3892, 0.7896, 0.4224]]]]) + >>> input + tensor([[[[0.4963, 0.7682, 0.0885], + [0.1320, 0.3074, 0.6341], + [0.4901, 0.8964, 0.4556]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomAffine((-15., 20.), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + degrees: Union[Tensor, float, Tuple[float, float]], + translate: Optional[Union[Tensor, Tuple[float, float]]] = None, + scale: Optional[Union[Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None, + shear: Optional[Union[Tensor, float, Tuple[float, float]]] = None, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator: rg.AffineGenerator = rg.AffineGenerator(degrees, translate, scale, shear) + self.flags = { + "resample": Resample.get(resample), + "padding_mode": SamplePadding.get(padding_mode), + "align_corners": align_corners, + } + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return get_affine_matrix2d( + as_tensor(params["translations"], device=input.device, dtype=input.dtype), + as_tensor(params["center"], device=input.device, dtype=input.dtype), + as_tensor(params["scale"], device=input.device, dtype=input.dtype), + as_tensor(params["angle"], device=input.device, dtype=input.dtype), + deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)), + deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)), + ) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, _, height, width = input.shape + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return warp_affine( + input, + transform[:, :2, :], + (height, width), + flags["resample"].name.lower(), + align_corners=flags["align_corners"], + padding_mode=flags["padding_mode"].name.lower(), + ) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/base.py new file mode 100644 index 0000000000000000000000000000000000000000..807c46eca61e3bd5544c53d41e05116bc5b6b3cc --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/base.py @@ -0,0 +1,305 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor, as_tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints +from kornia.utils.helpers import _torch_inverse_cast + + +class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D): + r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + """ + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + """By default, the exact transformation as ``apply_transform`` will be used.""" + raise NotImplementedError + + def compute_inverse_transformation(self, transform: Tensor) -> Tensor: + """Compute the inverse transform of given transformation matrices.""" + return _torch_inverse_cast(transform) + + def get_transformation_matrix( + self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Obtain transformation matrices. + + Return the current transformation matrix if existed. Generate a new one, otherwise. + """ + flags = self.flags if flags is None else flags + if params is not None: + transform = self.generate_transformation_matrix(input, params, flags) + elif self.transform_matrix is None: + params = self.forward_parameters(input.shape) + transform = self.generate_transformation_matrix(input, params, flags) + else: + transform = self.transform_matrix + return as_tensor(transform, device=input.device, dtype=input.dtype) + + def apply_non_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process masks corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process masks corresponding to the inputs that are transformed. + + Note: + Convert "resample" arguments to "nearest" by default. + + """ + resample_method: Optional[Resample] + if "resample" in flags: + resample_method = flags["resample"] + flags["resample"] = Resample.get("nearest") + output = self.apply_transform(input, params, flags, transform) + if resample_method is not None: + flags["resample"] = resample_method + return output + + def apply_non_transform_box( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + """Process boxes corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_box( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + """Process boxes corresponding to the inputs that are transformed.""" + if transform is None: + if self.transform_matrix is None: + raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.") + transform = self.transform_matrix + input = self.apply_non_transform_box(input, params, flags, transform) + return input.transform_boxes_(transform) + + def apply_non_transform_keypoint( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + """Process keypoints corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_keypoint( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + """Process keypoints corresponding to the inputs that are transformed.""" + if transform is None: + if self.transform_matrix is None: + raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.") + transform = self.transform_matrix + input = self.apply_non_transform_keypoint(input, params, flags, transform) + return input.transform_keypoints_(transform) + + def apply_non_transform_class( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process class tags corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_class( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process class tags corresponding to the inputs that are transformed.""" + return input + + def inverse_inputs( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + in_tensor = self.transform_tensor(input) + output = in_tensor.clone() + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + size: Optional[Tuple[int, int]] = None + if "forward_input_shape" in params: + # Majorly for cropping functions + _size = params["forward_input_shape"].tolist() + size = (_size[-2], _size[-1]) + + # if no augmentation needed + if not to_apply.any(): + output = in_tensor + # if all data needs to be augmented + elif to_apply.all(): + output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size) + else: + output[to_apply] = self.inverse_transform( + in_tensor[to_apply], + transform=transform[to_apply] if transform is not None else transform, + size=size, + flags=flags, + ) + return output + + def inverse_masks( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + resample_method: Optional[Resample] = None + if "resample" in flags: + resample_method = flags["resample"] + flags["resample"] = Resample.get("nearest") + output = self.inverse_inputs(input, params, flags, transform, **kwargs) + if resample_method is not None: + flags["resample"] = resample_method + return output + + def inverse_boxes( + self, + input: Boxes, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Boxes: + output = input.clone() + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + + if transform is None: + raise RuntimeError("`transform` has to be a tensor. Got None.") + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + # if no augmentation needed + if not to_apply.any(): + output = input + # if all data needs to be augmented + elif to_apply.all(): + output = input.transform_boxes_(transform) + else: + output[to_apply] = input[to_apply].transform_boxes_(transform[to_apply]) + + return output + + def inverse_keypoints( + self, + input: Keypoints, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Keypoints: + """Inverse the transformation on keypoints. + + Args: + input: input keypoints tensor or object. + params: the corresponding parameters for an operation. + flags: static parameters. + transform: the inverse transformation matrix + kwargs: additional arguments + + """ + output = input.clone() + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + + if transform is None: + raise RuntimeError("`transform` has to be a tensor. Got None.") + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + # if no augmentation needed + if not to_apply.any(): + output = input + # if all data needs to be augmented + elif to_apply.all(): + output = input.transform_keypoints_(transform) + else: + output[to_apply] = input[to_apply].transform_keypoints_(transform[to_apply]) + + return output + + def inverse_classes( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + return input + + def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor: + """Perform inverse operations. + + Args: + input: the input tensor. + params: the corresponding parameters for an operation. + If None, a new parameter suite will be generated. + **kwargs: key-value pairs to override the parameters and flags. + + """ + input_shape = input.shape + in_tensor = self.transform_tensor(input) + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, self.flags, **kwargs + ) + + if params is None: + params = self._params + transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags) + + transform = self.compute_inverse_transformation(transform) + output = self.inverse_inputs(in_tensor, params, flags, transform) + + if self.keepdim: + return self.transform_output_tensor(output, input_shape) + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/center_crop.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/center_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..cd80a46c6faa411994078e7160161e67198a6702 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/center_crop.py @@ -0,0 +1,154 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform + + +class CenterCrop(GeometricAugmentationBase2D): + r"""Crop a given image tensor at the center. + + .. image:: _static/img/CenterCrop.png + + Args: + size: Desired output size (out_h, out_w) of the crop. + If integer, out_h = out_w = size. + If Tuple[int, int], out_h = size[0], out_w = size[1]. + align_corners: interpolation flag. + resample: The interpolation mode. + p: probability of applying the transformation for the whole batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based + on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation + to extract and resize at once. Use `slice` for efficiency, or `resample` for proper + differentiability. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, out_h, out_w)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> inputs = torch.randn(1, 1, 4, 4) + >>> inputs + tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339], + [ 0.8487, 0.6920, -0.3160, -2.1152], + [ 0.3223, -1.2633, 0.3500, 0.3081], + [ 0.1198, 1.2377, 1.1168, -0.2473]]]]) + >>> aug = CenterCrop(2, p=1., cropping_mode="resample") + >>> out = aug(inputs) + >>> out + tensor([[[[ 0.6920, -0.3160], + [-1.2633, 0.3500]]]]) + >>> aug.inverse(out, padding_mode="border") + tensor([[[[ 0.6920, 0.6920, -0.3160, -0.3160], + [ 0.6920, 0.6920, -0.3160, -0.3160], + [-1.2633, -1.2633, 0.3500, 0.3500], + [-1.2633, -1.2633, 0.3500, 0.3500]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = CenterCrop(2, p=1., cropping_mode="resample") + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + size: Union[int, Tuple[int, int]], + align_corners: bool = True, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + p: float = 1.0, + keepdim: bool = False, + cropping_mode: str = "slice", + ) -> None: + # same_on_batch is always True for CenterCrop + # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely. + super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim) + if isinstance(size, tuple): + self.size = (size[0], size[1]) + elif isinstance(size, int): + self.size = (size, size) + else: + raise Exception(f"Invalid size type. Expected (int, tuple(int, int). Got: {type(size)}.") + + self.flags = { + "resample": Resample.get(resample), + "cropping_mode": cropping_mode, + "align_corners": align_corners, + "size": self.size, + "padding_mode": "zeros", + } + + def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + if flags["cropping_mode"] in ("resample", "slice"): + transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input)) + transform = transform.expand(input.shape[0], -1, -1) + return transform + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return crop_by_transform_mat( + input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"] + ) + if flags["cropping_mode"] == "slice": # uses advanced slicing to crop + return crop_by_indices(input, params["src"], flags["size"]) + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + if size is None: + size = self.size + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return crop_by_transform_mat( + input, + transform[:, :2, :], + size, + flags["resample"].name.lower(), + flags["padding_mode"], + flags["align_corners"], + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/crop.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/crop.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2e63fd90cbaac8d48fb6156ca768c6dec2d6ec --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/crop.py @@ -0,0 +1,321 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor, pad, tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints +from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform + + +class RandomCrop(GeometricAugmentationBase2D): + r"""Crop random patches of a tensor image on a given size. + + .. image:: _static/img/RandomCrop.png + + Args: + size: Desired output size (out_h, out_w) of the crop. + Must be Tuple[int, int], then out_h = size[0], out_w = size[1]. + padding: Optional padding on each border + of the image. Default is None, i.e no padding. If a sequence of length + 4 is provided, it is used to pad left, top, right, bottom borders + respectively. If a sequence of length 2 is provided, it is used to + pad left/right, top/bottom borders, respectively. + pad_if_needed: It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill: Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + padding_mode: Type of padding. Should be: constant, reflect, replicate. + resample: the interpolation mode. + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation for the whole batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based + on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation + to extract and resize at once. Use `slice` for efficiency, or `resample` for proper + differentiability. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, out_h, out_w)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> _ = torch.manual_seed(0) + >>> inputs = torch.arange(1*1*3*3.).view(1, 1, 3, 3) + >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample") + >>> out = aug(inputs) + >>> out + tensor([[[[3., 4.], + [6., 7.]]]]) + >>> aug.inverse(out, padding_mode="replicate") + tensor([[[[3., 4., 4.], + [3., 4., 4.], + [6., 7., 7.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample") + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + size: Tuple[int, int], + padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None, + pad_if_needed: Optional[bool] = False, + fill: int = 0, + padding_mode: str = "constant", + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = True, + p: float = 1.0, + keepdim: bool = False, + cropping_mode: str = "slice", + ) -> None: + # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely. + super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim) + self._param_generator = rg.CropGenerator(size) + self.flags = { + "size": size, + "padding": padding, + "pad_if_needed": pad_if_needed, + "fill": fill, + "padding_mode": padding_mode, + "resample": Resample.get(resample), + "align_corners": align_corners, + "cropping_mode": cropping_mode, + } + + def compute_padding(self, shape: Tuple[int, ...], flags: Optional[Dict[str, Any]] = None) -> List[int]: + flags = self.flags if flags is None else flags + if len(shape) != 4: + raise AssertionError(f"Expected BCHW. Got {shape}.") + padding = [0, 0, 0, 0] # left, right, top, bottom + if flags["padding"] is not None: + if isinstance(flags["padding"], int): + padding = [flags["padding"]] * 4 + elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 2: + padding = [flags["padding"][0], flags["padding"][0], flags["padding"][1], flags["padding"][1]] + elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 4: + padding = [flags["padding"][0], flags["padding"][2], flags["padding"][1], flags["padding"][3]] + else: + raise RuntimeError(f"Expect `padding` to be a scalar, or length 2/4 list. Got {flags['padding']}.") + + if flags["pad_if_needed"]: + needed_padding: Tuple[int, int] = (flags["size"][0] - shape[-2], flags["size"][1] - shape[-1]) # HW + # If crop width is larger than input width pad equally left and right + if needed_padding[1] > 0: + # Only use the extra padding if actually needed after possible fixed padding + padding[0] = max(needed_padding[1], padding[0]) + padding[1] = max(needed_padding[1], padding[1]) + # If crop height is larger than input height pad equally top and bottom + if needed_padding[0] > 0: + # Only use the extra padding if actually needed after possible fixed padding + padding[2] = max(needed_padding[0], padding[2]) + padding[3] = max(needed_padding[0], padding[3]) + return padding + + def precrop_padding( + self, input: Tensor, padding: Optional[List[int]] = None, flags: Optional[Dict[str, Any]] = None + ) -> Tensor: + flags = self.flags if flags is None else flags + if padding is None: + padding = self.compute_padding(input.shape) + + if any(padding): + input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"]) + + return input + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + if flags["cropping_mode"] in ("resample", "slice"): + transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input)) + return transform + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def apply_transform_keypoint( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + """Process keypoints corresponding to the inputs that are no transformation applied.""" + # For pad the keypoints properly. + padding_size = params["padding_size"].to(device=input.device) + input = input.pad(padding_size) + return super().apply_transform_keypoint(input=input, params=params, flags=flags, transform=transform) + + def apply_transform_box( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + """Process keypoints corresponding to the inputs that are no transformation applied.""" + # For pad the boxes properly. + padding_size = params["padding_size"] + input = input.pad(padding_size) + return super().apply_transform_box(input=input, params=params, flags=flags, transform=transform) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + padding_size: Optional[List[int]] = None + if "padding_size" in params and isinstance(params["padding_size"], Tensor): + padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist() + input = self.precrop_padding(input, padding_size, flags) + + flags = self.flags if flags is None else flags + if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + # Fit the arg to F.pad + if flags["padding_mode"] == "constant": + padding_mode = "zeros" + elif flags["padding_mode"] == "replicate": + padding_mode = "border" + elif flags["padding_mode"] == "reflect": + padding_mode = "reflection" + else: + padding_mode = flags["padding_mode"] + + return crop_by_transform_mat( + input, + transform, + flags["size"], + mode=flags["resample"].name.lower(), + padding_mode=padding_mode, + align_corners=flags["align_corners"], + ) + if flags["cropping_mode"] == "slice": # uses advanced slicing to crop + return crop_by_indices(input, params["src"], flags["size"]) + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + if size is None: + raise RuntimeError("`size` has to be a tuple. Got None.") + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + # Fit the arg to F.pad + if flags["padding_mode"] == "constant": + padding_mode = "zeros" + elif flags["padding_mode"] == "replicate": + padding_mode = "border" + elif flags["padding_mode"] == "reflect": + padding_mode = "reflection" + else: + padding_mode = flags["padding_mode"] + return crop_by_transform_mat( + input, + transform[:, :2, :], + size, + flags["resample"].name.lower(), + padding_mode=padding_mode, + align_corners=flags["align_corners"], + ) + + def inverse_inputs( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + out = super().inverse_inputs(input, params, flags, transform, **kwargs) + if not params["batch_prob"].all(): + return out + padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist() + padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]] + return self.precrop_padding(out, padding_size) + + def inverse_boxes( + self, + input: Boxes, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Boxes: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + output = super().inverse_boxes(input, params, flags, transform, **kwargs) + if not params["batch_prob"].all(): + return output + + return output.unpad(params["padding_size"]) + + def inverse_keypoints( + self, + input: Keypoints, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Keypoints: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + output = super().inverse_keypoints(input, params, flags, transform, **kwargs) + if not params["batch_prob"].all(): + return output + + return output.unpad(params["padding_size"].to(device=input.device)) + + # Override parameters for precrop + def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + input_pad = self.compute_padding(batch_shape) + batch_shape_new = torch.Size( + ( + *batch_shape[:2], + batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding + batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding + ) + ) + padding_size = tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1) + _params = super().forward_parameters(batch_shape_new) + _params.update({"padding_size": padding_size}) + return _params diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/elastic_transform.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/elastic_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..faba55bfc53ea3876f72acb625792b18e4432071 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/elastic_transform.py @@ -0,0 +1,133 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from kornia.augmentation._2d.base import AugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.transform import elastic_transform2d + + +class RandomElasticTransform(AugmentationBase2D): + r"""Add random elastic transformation to a tensor image. + + .. image:: _static/img/RandomElasticTransform.png + + Args: + kernel_size: the size of the Gaussian kernel. + sigma: The standard deviation of the Gaussian in the y and x directions, + respectively. Larger sigma results in smaller pixel displacements. + alpha: The scaling factor that controls the intensity of the deformation + in the y and x directions, respectively. + align_corners: Interpolation flag used by `grid_sample`. + resample: Interpolation mode used by `grid_sample`. Either 'nearest' (0) or 'bilinear' (1). + padding_mode: The padding used by ```grid_sample```. Either 'zeros', 'border' or 'refection'. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + .. note:: + This function internally uses :func:`kornia.geometry.transform.elastic_transform2d`. + + Examples: + >>> import torch + >>> img = torch.ones(1, 1, 2, 2) + >>> out = RandomElasticTransform()(img) + >>> out.shape + torch.Size([1, 1, 2, 2]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomElasticTransform(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (63, 63), + sigma: Tuple[float, float] = (32.0, 32.0), + alpha: Tuple[float, float] = (1.0, 1.0), + align_corners: bool = False, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + padding_mode: str = "zeros", + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + self.flags = { + "kernel_size": kernel_size, + "sigma": sigma, + "alpha": alpha, + "align_corners": align_corners, + "resample": Resample.get(resample), + "padding_mode": padding_mode, + } + + def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]: + B, _, H, W = shape + if self.same_on_batch: + noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W) + else: + noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype) + return {"noise": noise * 2 - 1} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return elastic_transform2d( + input, + params["noise"].to(input), + flags["kernel_size"], + flags["sigma"], + flags["alpha"], + flags["align_corners"], + flags["resample"].name.lower(), + flags["padding_mode"], + ) + + def apply_non_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return input + + def apply_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process masks corresponding to the inputs that are transformed.""" + return self.apply_transform(input, params=params, flags=flags, transform=transform) + + def apply_transform_box( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + """Process masks corresponding to the inputs that are transformed.""" + # We assume that boxes may not be affected too much by the deformation. + return input + + def apply_transform_class( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + """Process class tags corresponding to the inputs that are transformed.""" + return input diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/fisheye.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/fisheye.py new file mode 100644 index 0000000000000000000000000000000000000000..017392e37ab1b70c9c353d142fe087223e53a8ba --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/fisheye.py @@ -0,0 +1,101 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.base import AugmentationBase2D +from kornia.core import Tensor +from kornia.geometry.transform import remap +from kornia.utils import create_meshgrid + + +class RandomFisheye(AugmentationBase2D): + r"""Add random camera radial distortion. + + .. image:: _static/img/RandomFisheye.png + + Args: + center_x: Ranges to sample respect to x-coordinate center with shape (2,). + center_y: Ranges to sample respect to y-coordinate center with shape (2,). + gamma: Ranges to sample for the gamma values respect to optical center with shape (2,). + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Examples: + >>> import torch + >>> img = torch.ones(1, 1, 2, 2) + >>> center_x = torch.tensor([-.3, .3]) + >>> center_y = torch.tensor([-.3, .3]) + >>> gamma = torch.tensor([.9, 1.]) + >>> out = RandomFisheye(center_x, center_y, gamma)(img) + >>> out.shape + torch.Size([1, 1, 2, 2]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomFisheye(center_x, center_y, gamma, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + center_x: Tensor, + center_y: Tensor, + gamma: Tensor, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self._check_tensor(center_x) + self._check_tensor(center_y) + self._check_tensor(gamma) + self._param_generator = rg.PlainUniformGenerator( + (center_x[:, None], "center_x", None, None), + (center_y[:, None], "center_y", None, None), + (gamma[:, None], "gamma", None, None), + ) + + def _check_tensor(self, data: Tensor) -> None: + if not isinstance(data, Tensor): + raise TypeError(f"Invalid input type. Expected Tensor - got: {type(data)}") + + if len(data.shape) != 1 and data.shape[0] != 2: + raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.") + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + # create the initial sampling fields + B, _, H, W = input.shape + grid = create_meshgrid(H, W, normalized_coordinates=True) + field_x = grid[..., 0].to(input) # 1xHxW + field_y = grid[..., 1].to(input) # 1xHxW + # vectorize the random parameters + center_x = params["center_x"].view(B, 1, 1).to(input) + center_y = params["center_y"].view(B, 1, 1).to(input) + gamma = params["gamma"].view(B, 1, 1).to(input) + # compute and apply the distances respect to the camera optical center + distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5 + field_x = field_x + field_x * distance**gamma # BxHxw + field_y = field_y + field_y * distance**gamma # BxHxW + return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/horizontal_flip.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/horizontal_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..8174cb46e0852e339bee8836de2e52c8b0b36ed6 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/horizontal_flip.py @@ -0,0 +1,99 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from torch import Tensor + +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.core import as_tensor, tensor +from kornia.geometry.transform import hflip + + +class RandomHorizontalFlip(GeometricAugmentationBase2D): + r"""Apply a random horizontal flip to a tensor image or a batch of tensor images with a given probability. + + .. image:: _static/img/RandomHorizontalFlip.png + + Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`. + If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second, + the corresponding transformation matrix that has been applied to them. In this case the module + will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the + previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module. + + Args: + p: probability of the image being flipped. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.hflip`. + + Examples: + >>> import torch + >>> input = torch.tensor([[[[0., 0., 0.], + ... [0., 0., 0.], + ... [0., 1., 1.]]]]) + >>> seq = RandomHorizontalFlip(p=1.0) + >>> seq(input), seq.transform_matrix + (tensor([[[[0., 0., 0.], + [0., 0., 0.], + [1., 1., 0.]]]]), tensor([[[-1., 0., 2.], + [ 0., 1., 0.], + [ 0., 0., 1.]]])) + >>> seq.inverse(seq(input)).equal(input) + True + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> seq = RandomHorizontalFlip(p=1.0) + >>> (seq(input) == seq(input, params=seq._params)).all() + tensor(True) + + """ + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + w: int = int(params["forward_input_shape"][-1]) + flip_mat: Tensor = tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype) + + return flip_mat.expand(input.shape[0], 3, 3) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return hflip(input) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/pad.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/pad.py new file mode 100644 index 0000000000000000000000000000000000000000..0172e464830bfd6536cfd6355b91d471d7e813d1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/pad.py @@ -0,0 +1,96 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +import torch +from torch import Tensor + +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D + + +class PadTo(GeometricAugmentationBase2D): + r"""Pad the given sample to a specific size. Always occurs (p=1.0). + + .. image:: _static/img/PadTo.png + + Args: + size: a tuple of ints in the format (height, width) that give the spatial + dimensions to pad inputs to. + pad_mode: the type of padding to perform on the image (valid values + are those accepted by torch.nn.functional.pad) + pad_value: fill value for 'constant' padding applied to the image + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`torch.nn.functional.pad`. + + Examples: + >>> import torch + >>> img = torch.tensor([[[[0., 0., 0.], + ... [0., 0., 0.], + ... [0., 0., 0.]]]]) + >>> pad = PadTo((4, 5), pad_value=1.) + >>> out = pad(img) + >>> out + tensor([[[[0., 0., 0., 1., 1.], + [0., 0., 0., 1., 1.], + [0., 0., 0., 1., 1.], + [1., 1., 1., 1., 1.]]]]) + >>> pad.inverse(out) + tensor([[[[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]]]) + + """ + + def __init__( + self, size: Tuple[int, int], pad_mode: str = "constant", pad_value: float = 0, keepdim: bool = False + ) -> None: + super().__init__(p=1.0, same_on_batch=True, p_batch=1.0, keepdim=keepdim) + self.flags = {"size": size, "pad_mode": pad_mode, "pad_value": pad_value} + + # TODO: It is incorrect to return identity + # TODO: Having a resampled version with ``warp_affine`` + def compute_transformation(self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return self.identity_matrix(image) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, _, height, width = input.shape + height_pad: int = flags["size"][0] - height + width_pad: int = flags["size"][1] - width + return torch.nn.functional.pad( + input, [0, width_pad, 0, height_pad], mode=flags["pad_mode"], value=flags["pad_value"] + ) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if size is None: + raise RuntimeError("`size` has to be a tuple. Got None.") + return input[..., : size[0], : size[1]] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/perspective.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/perspective.py new file mode 100644 index 0000000000000000000000000000000000000000..07afbc34b39795a7191b2bba62ded58a7a2ef50c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/perspective.py @@ -0,0 +1,119 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor, as_tensor +from kornia.geometry.transform import get_perspective_transform, warp_perspective + + +class RandomPerspective(GeometricAugmentationBase2D): + r"""Apply a random perspective transformation to an image tensor with a given probability. + + .. image:: _static/img/RandomPerspective.png + + Args: + distortion_scale: the degree of distortion, ranged from 0 to 1. + resample: the interpolation method to use. + same_on_batch: apply the same transformation across the batch. Default: False. + align_corners: interpolation flag. + p: probability of the image being perspectively transformed. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + sampling_method: ``'basic'`` | ``'area_preserving'``. Default: ``'basic'`` + If ``'basic'``, samples by translating the image corners randomly inwards. + If ``'area_preserving'``, samples by randomly translating the image corners in any direction. + Preserves area on average. See https://arxiv.org/abs/2104.03308 for further details. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.warp_pespective`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs= torch.tensor([[[[1., 0., 0.], + ... [0., 1., 0.], + ... [0., 0., 1.]]]]) + >>> aug = RandomPerspective(0.5, p=0.5) + >>> out = aug(inputs) + >>> out + tensor([[[[0.0000, 0.2289, 0.0000], + [0.0000, 0.4800, 0.0000], + [0.0000, 0.0000, 0.0000]]]]) + >>> aug.inverse(out) + tensor([[[[0.0500, 0.0961, 0.0000], + [0.2011, 0.3144, 0.0000], + [0.0031, 0.0130, 0.0053]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomPerspective(0.5, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + distortion_scale: Union[Tensor, float] = 0.5, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + p: float = 0.5, + keepdim: bool = False, + sampling_method: str = "basic", + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator = rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method) + + self.flags: Dict[str, Any] = {"align_corners": align_corners, "resample": Resample.get(resample)} + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input)) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, _, height, width = input.shape + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return warp_perspective( + input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"] + ) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resize.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resize.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb4b22b915c19ed8f2a0de4b45822cf831660cf --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resize.py @@ -0,0 +1,151 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize +from kornia.utils import eye_like + + +class Resize(GeometricAugmentationBase2D): + """Resize to size. + + Args: + size: Size (h, w) in pixels of the resized region or just one side. + side: Which side to resize, if size is only of type int. + resample: Resampling mode. + align_corners: interpolation flag. + antialias: if True, then image will be filtered with Gaussian before downscaling. No effect for upscaling. + p: probability of the augmentation been applied. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + """ + + def __init__( + self, + size: Union[int, Tuple[int, int]], + side: str = "short", + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + align_corners: bool = True, + antialias: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim) + self._param_generator = rg.ResizeGenerator(resize_to=size, side=side) + self.flags = { + "size": size, + "side": side, + "resample": Resample.get(resample), + "align_corners": align_corners, + "antialias": antialias, + } + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + if params["output_size"] == input.shape[-2:]: + return eye_like(3, input) + + transform: Tensor = torch.as_tensor( + get_perspective_transform(params["src"], params["dst"]), dtype=input.dtype, device=input.device + ) + transform = transform.expand(input.shape[0], -1, -1) + return transform + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + B, C, _, _ = input.shape + out_size = tuple(params["output_size"][0].tolist()) + out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype) + + for i in range(B): + x1 = int(params["src"][i, 0, 0]) + x2 = int(params["src"][i, 1, 0]) + 1 + y1 = int(params["src"][i, 0, 1]) + y2 = int(params["src"][i, 3, 1]) + 1 + out[i] = resize( + input[i : i + 1, :, y1:y2, x1:x2], + out_size, + interpolation=flags["resample"].name.lower(), + align_corners=( + flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None + ), + antialias=flags["antialias"], + ) + return out + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(size, tuple): + raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}") + + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return crop_by_transform_mat( + input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"] + ) + + +class LongestMaxSize(Resize): + """Rescale an image so that maximum side is equal to max_size, keeping the aspect ratio of the initial image. + + Args: + max_size: maximum size of the image after the transformation. + + """ + + def __init__( + self, + max_size: int, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + align_corners: bool = True, + p: float = 1.0, + ) -> None: + # TODO: Support max_size list input to randomly select from + super().__init__(size=max_size, side="long", resample=resample, align_corners=align_corners, p=p) + + +class SmallestMaxSize(Resize): + """Rescale an image so that minimum side is equal to max_size, keeping the aspect ratio of the initial image. + + Args: + max_size: maximum size of the image after the transformation. + + """ + + def __init__( + self, + max_size: int, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + align_corners: bool = True, + p: float = 1.0, + ) -> None: + # TODO: Support max_size list input to randomly select from + super().__init__(size=max_size, side="short", resample=resample, align_corners=align_corners, p=p) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resized_crop.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resized_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..f5001cdd58e33494afabfb1a116a52cfebcf410c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resized_crop.py @@ -0,0 +1,160 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform + + +class RandomResizedCrop(GeometricAugmentationBase2D): + r"""Crop random patches in an image tensor and resizes to a given size. + + .. image:: _static/img/RandomResizedCrop.png + + Args: + size: Desired output size (out_h, out_w) of each edge. + Must be Tuple[int, int], then out_h = size[0], out_w = size[1]. + scale: range of size of the origin size cropped. + ratio: range of aspect ratio of the origin aspect ratio cropped. + resample: the interpolation mode. + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of the augmentation been applied. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based + on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation + to extract and resize at once. Use `slice` for efficiency, or `resample` for proper + differentiability. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, out_h, out_w)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Example: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.tensor([[[0., 1., 2.], + ... [3., 4., 5.], + ... [6., 7., 8.]]]) + >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample") + >>> out = aug(inputs) + >>> out + tensor([[[[1.0000, 1.5000, 2.0000], + [4.0000, 4.5000, 5.0000], + [7.0000, 7.5000, 8.0000]]]]) + >>> aug.inverse(out, padding_mode="border") + tensor([[[[1., 1., 2.], + [4., 4., 5.], + [7., 7., 8.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample") + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + size: Tuple[int, int], + scale: Union[Tensor, Tuple[float, float]] = (0.08, 1.0), + ratio: Union[Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0), + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = True, + p: float = 1.0, + keepdim: bool = False, + cropping_mode: str = "slice", + ) -> None: + # Since PyTorch does not support ragged tensor. So cropping function happens all the time. + super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim) + self._param_generator = rg.ResizedCropGenerator(size, scale, ratio) + self.flags = { + "size": size, + "resample": Resample.get(resample), + "align_corners": align_corners, + "cropping_mode": cropping_mode, + "padding_mode": "zeros", + } + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + if flags["cropping_mode"] in ("resample", "slice"): + transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input)) + transform = transform.expand(input.shape[0], -1, -1) + return transform + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return crop_by_transform_mat( + input, + transform, + flags["size"], + mode=flags["resample"].name.lower(), + padding_mode="zeros", + align_corners=flags["align_corners"], + ) + if flags["cropping_mode"] == "slice": # uses advanced slicing to crop + return crop_by_indices( + input, + params["src"], + flags["size"], + interpolation=flags["resample"].name.lower(), + align_corners=flags["align_corners"], + ) + raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.") + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if flags["cropping_mode"] != "resample": + raise NotImplementedError( + f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}." + ) + if not isinstance(size, tuple): + raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}") + + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return crop_by_transform_mat( + input, + transform[:, :2, :], + size, + flags["resample"].name.lower(), + flags["padding_mode"], + flags["align_corners"], + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/rotation.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb4e7cdac542eb42fbb38fea1ec2530d189780b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/rotation.py @@ -0,0 +1,232 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample +from kornia.core import Tensor, as_tensor +from kornia.geometry.transform import affine +from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center +from kornia.utils.misc import eye_like + + +class RandomRotation(GeometricAugmentationBase2D): + r"""Apply a random rotation to a tensor image or a batch of tensor images given an amount of degrees. + + .. image:: _static/img/RandomRotation.png + + Args: + degrees: range of degrees to select from. If degrees is a number the + range of degrees to select from will be (-degrees, +degrees). + resample: Default: the interpolation mode. + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.affine`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> input = torch.tensor([[1., 0., 0., 2.], + ... [0., 0., 0., 0.], + ... [0., 1., 2., 0.], + ... [0., 0., 1., 2.]]) + >>> aug = RandomRotation(degrees=45.0, p=1.) + >>> out = aug(input) + >>> out + tensor([[[[0.9824, 0.0088, 0.0000, 1.9649], + [0.0000, 0.0029, 0.0000, 0.0176], + [0.0029, 1.0000, 1.9883, 0.0000], + [0.0000, 0.0088, 1.0117, 1.9649]]]]) + >>> aug.transform_matrix + tensor([[[ 1.0000, -0.0059, 0.0088], + [ 0.0059, 1.0000, -0.0088], + [ 0.0000, 0.0000, 1.0000]]]) + >>> inv = aug.inverse(out) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomRotation(degrees=45.0, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + # Note: Extra params, center=None, fill=0 in TorchVision + + def __init__( + self, + degrees: Union[Tensor, float, Tuple[float, float], List[float]], + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = True, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator = rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0))) + + self.flags = {"resample": Resample.get(resample), "align_corners": align_corners} + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + # TODO: Update to use `get_rotation_matrix2d` + angles: Tensor = params["degrees"].to(input) + + center: Tensor = _compute_tensor_center(input) + rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1)) + + # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix + trans_mat: Tensor = eye_like(3, input, shared_memory=False) + trans_mat[:, 0] = rotation_mat[:, 0] + trans_mat[:, 1] = rotation_mat[:, 1] + + return trans_mat + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"]) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) + + +class RandomRotation90(GeometricAugmentationBase2D): + r"""Apply a random 90 * n degree rotation to a tensor image or a batch of tensor images. + + Args: + times: the range of n times 90 degree rotation needs to be applied. + resample: Default: the interpolation mode. + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively + slow as it operates based on affine transformations. + + Examples: + >>> rng = torch.manual_seed(1) + >>> torch.set_printoptions(sci_mode=False) + >>> input = torch.tensor([[1., 0., 0., 2.], + ... [0., 0., 0., 0.], + ... [0., 1., 2., 0.], + ... [0., 0., 1., 2.]]) + >>> aug = RandomRotation90(times=(1, 1), p=1.) + >>> out = aug(input) + >>> out + tensor([[[[ 2.0000, 0.0000, 0.0000, 2.0000], + [ 0.0000, 0.0000, 2.0000, 1.0000], + [ 0.0000, 0.0000, 1.0000, 0.0000], + [ 1.0000, 0.0000, 0.0000, 0.0000]]]]) + >>> aug.transform_matrix + tensor([[[ -0.0000, 1.0000, 0.0000], + [ -1.0000, -0.0000, 3.0000], + [ 0.0000, 0.0000, 1.0000]]]) + >>> inv = aug.inverse(out) + >>> torch.set_printoptions(profile='default') + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomRotation90(times=(-1, 1), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + times: tuple[int, int], + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = True, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator = rg.PlainUniformGenerator((times, "times", 0.0, (-3, 3))) + + self.flags = {"resample": Resample.get(resample), "align_corners": align_corners} + + def compute_transformation(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any]) -> Tensor: + # TODO: Update to use `get_rotation_matrix2d` + angles: Tensor = 90.0 * params["times"].round().to(input) + + center: Tensor = _compute_tensor_center(input) + rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1)) + + # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix + trans_mat: Tensor = eye_like(3, input, shared_memory=False) + trans_mat[:, 0] = rotation_mat[:, 0] + trans_mat[:, 1] = rotation_mat[:, 1] + + return trans_mat + + def apply_transform( + self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"]) + + def inverse_transform( + self, + input: Tensor, + flags: dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/shear.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/shear.py new file mode 100644 index 0000000000000000000000000000000000000000..39e992b9fc8921426f20e03674c02324a28f49b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/shear.py @@ -0,0 +1,133 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample, SamplePadding +from kornia.core import Tensor, as_tensor +from kornia.geometry.conversions import deg2rad +from kornia.geometry.transform import get_shear_matrix2d, warp_affine + + +class RandomShear(GeometricAugmentationBase2D): + r"""Apply a random 2D shear transformation to a tensor image. + + The transformation is computed so that the image center is kept invariant. + + Args: + shear: Range of degrees to select from. + If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied. + If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied. + If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) + will be applied. Will not apply shear by default. + resample: resample mode from "nearest" (0) or "bilinear" (1). + padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.warp_affine`. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3) + >>> aug = RandomShear((-5., 2., 5., 10.), p=1.) + >>> out = aug(input) + >>> out, aug.transform_matrix + (tensor([[[[0.4403, 0.7614, 0.1516], + [0.1753, 0.3074, 0.6127], + [0.4438, 0.8924, 0.4061]]]]), tensor([[[ 1.0000, 0.0100, -0.0100], + [-0.1183, 0.9988, 0.1194], + [ 0.0000, 0.0000, 1.0000]]])) + >>> aug.inverse(out) + tensor([[[[0.4045, 0.7577, 0.1393], + [0.2071, 0.3074, 0.5582], + [0.3958, 0.8868, 0.4265]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomShear((-15., 20.), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]], + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator: rg.ShearGenerator = rg.ShearGenerator(shear) + self.flags = { + "resample": Resample.get(resample), + "padding_mode": SamplePadding.get(padding_mode), + "align_corners": align_corners, + } + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return get_shear_matrix2d( + as_tensor(params["center"], device=input.device, dtype=input.dtype), + deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)), + deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)), + ) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, _, height, width = input.shape + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return warp_affine( + input, + transform[:, :2, :], + (height, width), + flags["resample"].name.lower(), + align_corners=flags["align_corners"], + padding_mode=flags["padding_mode"].name.lower(), + ) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/thin_plate_spline.py new file mode 100644 index 0000000000000000000000000000000000000000..19ff5f33c99ab15dbb52182503d3f07f65719b33 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/thin_plate_spline.py @@ -0,0 +1,88 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from kornia.augmentation._2d.base import AugmentationBase2D +from kornia.constants import SamplePadding +from kornia.core import Tensor, tensor +from kornia.geometry.transform import get_tps_transform, warp_image_tps + + +# NOTE: This NEEDS to be updated. It is out of the random generator controller. +class RandomThinPlateSpline(AugmentationBase2D): + r"""Add random noise to the Thin Plate Spline algorithm. + + .. image:: _static/img/RandomThinPlateSpline.png + + Args: + scale: the scale factor to apply to the destination points. + align_corners: Interpolation flag used by ``grid_sample``. + mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + .. note:: + This function internally uses :func:`kornia.geometry.transform.warp_image_tps`. + + Examples: + >>> img = torch.ones(1, 1, 2, 2) + >>> out = RandomThinPlateSpline()(img) + >>> out.shape + torch.Size([1, 1, 2, 2]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomThinPlateSpline(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + scale: float = 0.2, + align_corners: bool = False, + padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = { + "align_corners": align_corners, + "padding_mode": SamplePadding.get(padding_mode), + } + self.dist = torch.distributions.Uniform(-scale, scale) + + def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]: + B, _, _, _ = shape + src = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2 + dst = src + self.dist.rsample(src.shape) + return {"src": src, "dst": dst} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + src = params["src"].to(input) + dst = params["dst"].to(input) + # NOTE: warp_image_tps need to use inverse parameters + kernel, affine = get_tps_transform(dst, src) + return warp_image_tps(input, src, kernel, affine, flags["align_corners"], flags["padding_mode"].name.lower()) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/translate.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/translate.py new file mode 100644 index 0000000000000000000000000000000000000000..4afa1a39d4581b4686a8fe662805b4784d0b81a7 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/translate.py @@ -0,0 +1,129 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.constants import Resample, SamplePadding +from kornia.core import Tensor, as_tensor, stack +from kornia.geometry.transform import get_translation_matrix2d, warp_affine + + +class RandomTranslate(GeometricAugmentationBase2D): + r"""Apply a random 2D affine transformation to a tensor image. + + Args: + translate_x: tuple of maximum absolute fraction for horizontal translations. + For example translate_x=(a, b), then horizontal shift + is randomly sampled in the range img_width * a < dx < img_width * b + translate_y: tuple of maximum absolute fraction for vertical translations. + For example translate_y=(a, b), then vertical shift + is randomly sampled in the range img_height * a < dy < img_height * b. + resample: resample mode from "nearest" (0) or "bilinear" (1). + padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.warp_affine`. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3) + >>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.) + >>> out = aug(input) + >>> out, aug.transform_matrix + (tensor([[[[0.3403, 0.6439, 0.2920], + [0.1377, 0.3383, 0.5569], + [0.3226, 0.6909, 0.4844]]]]), tensor([[[ 1.0000, 0.0000, 0.1588], + [ 0.0000, 1.0000, -0.0907], + [ 0.0000, 0.0000, 1.0000]]])) + >>> aug.inverse(out) + tensor([[[[0.3565, 0.4839, 0.1922], + [0.2164, 0.4134, 0.3968], + [0.3797, 0.6075, 0.3765]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None, + translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator: rg.TranslateGenerator = rg.TranslateGenerator(translate_x, translate_y) + self.flags = { + "resample": Resample.get(resample), + "padding_mode": SamplePadding.get(padding_mode), + "align_corners": align_corners, + } + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + translations = stack([params["translate_x"], params["translate_y"]], dim=-1) + return get_translation_matrix2d(as_tensor(translations, device=input.device, dtype=input.dtype)) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, _, height, width = input.shape + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + + return warp_affine( + input, + transform[:, :2, :], + (height, width), + flags["resample"].name.lower(), + align_corners=flags["align_corners"], + padding_mode=flags["padding_mode"].name.lower(), + ) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/vertical_flip.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/vertical_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..facf0852f56a159133328c5fdb18d9ecb5dc8564 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/vertical_flip.py @@ -0,0 +1,91 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.core import Tensor, as_tensor, tensor +from kornia.geometry.transform import vflip + + +class RandomVerticalFlip(GeometricAugmentationBase2D): + r"""Apply a random vertical flip to a tensor image or a batch of tensor images with a given probability. + + .. image:: _static/img/RandomVerticalFlip.png + + Args: + p: probability of the image being flipped. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.geometry.transform.vflip`. + + Examples: + >>> import torch + >>> input = torch.tensor([[[[0., 0., 0.], + ... [0., 0., 0.], + ... [0., 1., 1.]]]]) + >>> seq = RandomVerticalFlip(p=1.0) + >>> seq(input), seq.transform_matrix + (tensor([[[[0., 1., 1.], + [0., 0., 0.], + [0., 0., 0.]]]]), tensor([[[ 1., 0., 0.], + [ 0., -1., 2.], + [ 0., 0., 1.]]])) + >>> seq.inverse(seq(input)).equal(input) + True + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> seq = RandomVerticalFlip(p=1.0) + >>> (seq(input) == seq(input, params=seq._params)).all() + tensor(True) + + """ + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + h: int = int(params["forward_input_shape"][-2]) + flip_mat: Tensor = tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype) + + return flip_mat.expand(input.shape[0], 3, 3) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return vflip(input) + + def inverse_transform( + self, + input: Tensor, + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + size: Optional[Tuple[int, int]] = None, + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.") + return self.apply_transform( + input, + params=self._params, + transform=as_tensor(transform, device=input.device, dtype=input.dtype), + flags=flags, + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/auto_contrast.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/auto_contrast.py new file mode 100644 index 0000000000000000000000000000000000000000..a57788dfc0d7011f9ee8d62c7b7b2ef876e6311e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/auto_contrast.py @@ -0,0 +1,58 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor +from kornia.enhance import normalize_min_max + + +class RandomAutoContrast(IntensityAugmentationBase2D): + r"""Apply a random auto-contrast of a tensor image. + + Args: + p: probability of applying the transformation. + clip_output: if true clip output + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.normalize_min_max` + + """ + + def __init__( + self, clip_output: bool = True, same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + self.clip_output = clip_output + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + out = normalize_min_max(input) + + if self.clip_output: + return out.clamp(0.0, 1.0) + + return out diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6ff2c1cf948a0c45030021618c897802544f70 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/base.py @@ -0,0 +1,88 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from torch import Tensor + +from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + + +class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D): + r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + """ + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return self.identity_matrix(input) + + def apply_non_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + # For the images where batch_prob == False. + return input + + def apply_non_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return input + + def apply_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return input + + def apply_non_transform_boxes( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + return input + + def apply_transform_boxes( + self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes: + return input + + def apply_non_transform_keypoint( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + return input + + def apply_transform_keypoint( + self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints: + return input + + def apply_non_transform_class( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return input + + def apply_transform_class( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return input diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/box_blur.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/box_blur.py new file mode 100644 index 0000000000000000000000000000000000000000..436561259570d1bcbb918557ca1329df451536db --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/box_blur.py @@ -0,0 +1,72 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.filters import box_blur + + +class RandomBoxBlur(IntensityAugmentationBase2D): + """Add random blur with a box filter to an image tensor. + + .. image:: _static/img/RandomBoxBlur.png + + Args: + kernel_size: the blurring kernel size. + border_type: the padding mode to be applied before convolving. + The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``. + normalized: if True, L1 norm of the kernel is set to 1. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + .. note:: + This function internally uses :func:`kornia.filters.box_blur`. + + Examples: + >>> img = torch.ones(1, 1, 24, 24) + >>> out = RandomBoxBlur((7, 7))(img) + >>> out.shape + torch.Size([1, 1, 24, 24]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomBoxBlur((7, 7), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (3, 3), + border_type: str = "reflect", + normalized: bool = True, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = {"kernel_size": kernel_size, "border_type": border_type, "normalized": normalized} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return box_blur(input, flags["kernel_size"], flags["border_type"], flags["normalized"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/brightness.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/brightness.py new file mode 100644 index 0000000000000000000000000000000000000000..e100d500ba84d59f21ddc69f490d91ce11572988 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/brightness.py @@ -0,0 +1,93 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.utils import _range_bound +from kornia.core import Tensor +from kornia.enhance.adjust import adjust_brightness + + +class RandomBrightness(IntensityAugmentationBase2D): + r"""Apply a random transformation to the brightness of a tensor image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + + .. image:: _static/img/RandomBrightness.png + + Args: + brightness: the brightness factor to apply + clip_output: if true clip output + silence_instantiation_warning: if True, silence the warning at instantiation. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_brightness` + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.rand(1, 3, 3, 3) + >>> aug = RandomBrightness(brightness = (0.5,2.),p=1.) + >>> aug(inputs) + tensor([[[[0.0505, 0.3225, 0.0000], + [0.0000, 0.0000, 0.1883], + [0.0443, 0.4507, 0.0099]], + + [[0.1866, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000], + [0.0728, 0.2519, 0.3543]], + + [[0.0000, 0.0000, 0.2359], + [0.4694, 0.0000, 0.4284], + [0.0000, 0.1072, 0.5070]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomBrightness((0.8,1.2), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + brightness: Tuple[float, float] = (1.0, 1.0), + clip_output: bool = True, + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.brightness: Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0)) + self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None)) + + self.clip_output = clip_output + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + brightness_factor = params["brightness_factor"].to(input) + return adjust_brightness(input, brightness_factor - 1, self.clip_output) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_dropout.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..5a37c9eaf9cbbfa6bd3f663509e8c8c527f6d7ed --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_dropout.py @@ -0,0 +1,116 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.random_generator._2d import ChannelDropoutGenerator +from kornia.core import Tensor, tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE + + +class RandomChannelDropout(IntensityAugmentationBase2D): + r"""Apply random channel dropout to a batch of images. + + .. image:: _static/img/RandomChannelDropout.png + + Args: + num_drop_channels: Number of channels to drop randomly. Default is 1. + fill_value: Value to fill the dropped channels with. Default is 0.0. + same_on_batch: Apply the same transformation across the batch. Defaults to False. + p: Probability of applying the transformation. Defaults to 0.5. + keepdim: Whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. Defaults to False. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(C, H, W)` or :math:`(B, C, H, W)` + + .. note:: + If `num_drop_channels` is set to 1, it means that for each image in the batch, + we will randomly choose one channel to drop. + If `num_drop_channels` is set to 2, it means that for each image in the batch, + we will randomly choose two channels to drop. + If num_drop_channels is set to 3, it means that for each image in the batch, + we will randomly choose three channels to drop (all image). + + Examples: + >>> rng = torch.manual_seed(1) + >>> img = torch.ones(1, 3, 3, 3) + >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0) + >>> aug(img) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + num_drop_channels: int = 1, + fill_value: float = 0.0, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + KORNIA_CHECK_TYPE(fill_value, float, f"`fill_value` must be a float. Got: {type(fill_value)}") + KORNIA_CHECK( + 0.0 <= fill_value <= 1.0, + f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}", + ) + self.fill_value = tensor(fill_value) + + KORNIA_CHECK_TYPE(num_drop_channels, int, f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}") + KORNIA_CHECK( + num_drop_channels >= 1, + f"Invalid value in `num_drop_channels`. Must be an int greater than 1. Got: {num_drop_channels}", + ) + self.num_drop_channels = num_drop_channels + # Generator of random parameters. + self._param_generator = ChannelDropoutGenerator(self.num_drop_channels) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"]) + KORNIA_CHECK( + self.num_drop_channels <= input.shape[1], + "Invalid value in `num_drop_channels`. Cannot be greater than the number of channels of `input`.", + ) + + out = input.clone() + out[params["batch_idx"], params["channel_idx"], ...] = self.fill_value.to( + device=input.device, dtype=input.dtype + ) + + return out diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_shuffle.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_shuffle.py new file mode 100644 index 0000000000000000000000000000000000000000..fef1d405673180d47e1926d2763b7c20405bb17a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_shuffle.py @@ -0,0 +1,69 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +import torch + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor + + +class RandomChannelShuffle(IntensityAugmentationBase2D): + r"""Shuffle the channels of a batch of multi-dimensional images. + + .. image:: _static/img/RandomChannelShuffle.png + + Args: + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + Examples: + >>> rng = torch.manual_seed(0) + >>> img = torch.arange(1*2*2*2.).view(1,2,2,2) + >>> RandomChannelShuffle()(img) + tensor([[[[4., 5.], + [6., 7.]], + + [[0., 1.], + [2., 3.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomChannelShuffle(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]: + B, C, _, _ = shape + channels = torch.rand(B, C).argsort(dim=1) + return {"channels": channels} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + out = torch.empty_like(input) + for i in range(out.shape[0]): + out[i] = input[i, params["channels"][i]] + return out diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/clahe.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/clahe.py new file mode 100644 index 0000000000000000000000000000000000000000..9142b1b26938dd42ba9c2ac8b8232d323e50ec33 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/clahe.py @@ -0,0 +1,83 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any, Optional + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor +from kornia.enhance import equalize_clahe + + +class RandomClahe(IntensityAugmentationBase2D): + r"""Apply CLAHE equalization on the input tensor randomly. + + .. image:: _static/img/equalize_clahe.png + + Args: + clip_limit: threshold value for contrast limiting. If 0 clipping is disabled. + grid_size: number of tiles to be cropped in each direction (GH, GW). + slow_and_differentiable: flag to select implementation + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + .. note:: + This function internally uses :func:`kornia.enhance.equalize_clahe`. + + Examples: + >>> img = torch.rand(1, 10, 20) + >>> aug = RandomClahe() + >>> res = aug(img) + >>> res.shape + torch.Size([1, 1, 10, 20]) + + >>> img = torch.rand(2, 3, 10, 20) + >>> aug = RandomClahe() + >>> res = aug(img) + >>> res.shape + torch.Size([2, 3, 10, 20]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomClahe(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + clip_limit: tuple[float, float] = (40.0, 40.0), + grid_size: tuple[int, int] = (8, 8), + slow_and_differentiable: bool = False, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.clip_limit = clip_limit + self._param_generator = rg.PlainUniformGenerator((self.clip_limit, "clip_limit_factor", None, None)) + self.flags = {"grid_size": grid_size, "slow_and_differentiable": slow_and_differentiable} + + def apply_transform( + self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + clip_limit = float(params["clip_limit_factor"][0]) + return equalize_clahe(input, clip_limit, flags["grid_size"], flags["slow_and_differentiable"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jiggle.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jiggle.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfd8acd13627c034cc3f0010a72aa6dfd541073 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jiggle.py @@ -0,0 +1,113 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.constants import pi +from kornia.core import Tensor +from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation + + +class ColorJiggle(IntensityAugmentationBase2D): + r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image. + + .. image:: _static/img/ColorJiggle.png + + Args: + p: probability of applying the transformation. + brightness: The brightness factor to apply. + contrast: The contrast factor to apply. + saturation: The saturation factor to apply. + hue: The hue factor to apply. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_brightness`, + :func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`, + :func:`kornia.enhance.adjust_hue`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.ones(1, 3, 3, 3) + >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.) + >>> aug(inputs) + tensor([[[[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]], + + [[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]], + + [[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.hue = hue + self._param_generator = rg.ColorJiggleGenerator(brightness, contrast, saturation, hue) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + transforms = [ + lambda img: adjust_brightness(img, params["brightness_factor"] - 1) + if (params["brightness_factor"] - 1 != 0).any() + else img, + lambda img: adjust_contrast(img, params["contrast_factor"]) + if (params["contrast_factor"] != 1).any() + else img, + lambda img: adjust_saturation(img, params["saturation_factor"]) + if (params["saturation_factor"] != 1).any() + else img, + lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi) if (params["hue_factor"] != 0).any() else img, + ] + + jittered = input + for idx in params["order"].tolist(): + t = transforms[idx] + jittered = t(jittered) + + return jittered diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jitter.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..274da9a04be296f6864805f7a3b8f88abb4ed209 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jitter.py @@ -0,0 +1,192 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.constants import pi +from kornia.core import Tensor +from kornia.enhance import ( + adjust_brightness_accumulative, + adjust_contrast_with_mean_subtraction, + adjust_hue, + adjust_saturation_with_gray_subtraction, +) + + +class ColorJitter(IntensityAugmentationBase2D): + r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. However, it does not + follow the color theory and is not be actively maintained. Prefer using + :func:`kornia.augmentation.ColorJiggle` + + .. image:: _static/img/ColorJitter.png + + Args: + brightness: The brightness factor to apply. + contrast: The contrast factor to apply. + saturation: The saturation factor to apply. + hue: The hue factor to apply. + silence_instantiation_warning: if True, silence the warning at instantiation. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`, + :func:`kornia.enhance.adjust_contrast_with_mean_subtraction`, + :func:`kornia.enhance.adjust_saturation_with_gray_subtraction`, + :func:`kornia.enhance.adjust_hue`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.ones(1, 3, 3, 3) + >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.) + >>> aug(inputs) + tensor([[[[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]], + + [[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]], + + [[0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993], + [0.9993, 0.9993, 0.9993]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0, + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.hue = hue + self._param_generator = rg.ColorJitterGenerator(brightness, contrast, saturation, hue) + + # native functions + self._brightness_fn = adjust_brightness_accumulative + self._contrast_fn = adjust_contrast_with_mean_subtraction + self._saturation_fn = adjust_saturation_with_gray_subtraction + self._hue_fn = adjust_hue + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + transforms = [ + lambda img: ( + self._brightness_fn(img, params["brightness_factor"]) + if (params["brightness_factor"] != 0).any() + else img + ), + lambda img: ( + self._contrast_fn(img, params["contrast_factor"]) if (params["contrast_factor"] != 1).any() else img + ), + lambda img: ( + self._saturation_fn(img, params["saturation_factor"]) + if (params["saturation_factor"] != 1).any() + else img + ), + lambda img: ( + self._hue_fn(img, params["hue_factor"] * 2 * pi) if (params["hue_factor"] != 0).any() else img + ), + ] + + jittered = input + for idx in params["order"]: + t = transforms[idx] + jittered = t(jittered) + + return jittered + + def compile( + self, + *, + fullgraph: bool = False, + dynamic: bool = False, + backend: str = "inductor", + mode: Optional[str] = None, + options: Optional[Dict[Any, Any]] = None, + disable: bool = False, + ) -> "ColorJitter": + self.brightness_fn = torch.compile( + self._brightness_fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + self.contrast_fn = torch.compile( + self._contrast_fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + self.saturation_fn = torch.compile( + self._saturation_fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + self.hue_fn = torch.compile( + self._hue_fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + return self diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/contrast.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/contrast.py new file mode 100644 index 0000000000000000000000000000000000000000..dab5a21b6404a745ee02a8b11db426947c542c0e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/contrast.py @@ -0,0 +1,92 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.utils import _range_bound +from kornia.core import Tensor +from kornia.enhance.adjust import adjust_contrast + + +class RandomContrast(IntensityAugmentationBase2D): + r"""Apply a random transformation to the contrast of a tensor image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + + .. image:: _static/img/RandomContrast.png + + Args: + contrast: the contrast factor to apply. + clip_output: if true clip output. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_contrast` + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.rand(1, 3, 3, 3) + >>> aug = RandomContrast(contrast = (0.5, 2.), p = 1.) + >>> aug(inputs) + tensor([[[[0.2750, 0.4258, 0.0490], + [0.0732, 0.1704, 0.3514], + [0.2716, 0.4969, 0.2525]], + + [[0.3505, 0.1934, 0.2227], + [0.0124, 0.0936, 0.1629], + [0.2874, 0.3867, 0.4434]], + + [[0.0893, 0.1564, 0.3778], + [0.5072, 0.2201, 0.4845], + [0.2325, 0.3064, 0.5281]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomContrast((0.8,1.2), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + contrast: Tuple[float, float] = (1.0, 1.0), + clip_output: bool = True, + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.contrast: Tensor = _range_bound(contrast, "contrast", center=1.0) + self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None)) + + self.clip_output = clip_output + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + contrast_factor = params["contrast_factor"].to(input) + return adjust_contrast(input, contrast_factor, self.clip_output) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/denormalize.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/denormalize.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc03d3a011d986dc5bb605fbee7988d2dbad8db --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/denormalize.py @@ -0,0 +1,83 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.enhance import denormalize + + +class Denormalize(IntensityAugmentationBase2D): + r"""Denormalize tensor images with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] * std[channel]) + mean[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + mean: Mean for each channel. + std: Standard deviations for each channel. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Return: + Denormalised tensor with same size as input :math:`(*, C, H, W)`. + + .. note:: + This function internally uses :func:`kornia.enhance.denormalize`. + + Examples: + >>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4)) + >>> x = torch.rand(1, 4, 3, 3) + >>> out = norm(x) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + """ + + def __init__( + self, + mean: Union[Tensor, Tuple[float], List[float], float], + std: Union[Tensor, Tuple[float], List[float], float], + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=True, keepdim=keepdim) + if isinstance(mean, float): + mean = torch.tensor([mean]) + + if isinstance(std, float): + std = torch.tensor([std]) + + if isinstance(mean, (tuple, list)): + mean = torch.tensor(mean) + + if isinstance(std, (tuple, list)): + std = torch.tensor(std) + + self.flags = {"mean": mean, "std": std} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return denormalize(input, flags["mean"], flags["std"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/dissolving.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/dissolving.py new file mode 100644 index 0000000000000000000000000000000000000000..4448fbafdf7b30f4d38c93f3d3eebc6389238a86 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/dissolving.py @@ -0,0 +1,75 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor +from kornia.filters import StableDiffusionDissolving + + +class RandomDissolving(IntensityAugmentationBase2D): + r"""Perform dissolving transformation using StableDiffusion models. + + Based on :cite:`shi2024dissolving`, the dissolving transformation is essentially applying one-step + reverse diffusion. Our implementation currently supports HuggingFace implementations of SD 1.4, 1.5 + and 2.1. SD 1.X tends to remove more details than SD2.1. + + .. list-table:: Title + :widths: 32 32 32 + :header-rows: 1 + + * - SD 1.4 + - SD 1.5 + - SD 2.1 + * - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.4.png + - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png + - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-2.1.png + + Args: + p: probability of applying the transformation. + version: the version of the stable diffusion model. + step_range: the step range of the diffusion model steps. Higher the step, stronger + the dissolving effects. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + **kwargs: additional arguments for `.from_pretrained` for HF StableDiffusionPipeline. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`. + - Output: :math:`(B, C, H, W)` + + """ + + def __init__( + self, + step_range: Tuple[float, float] = (100, 500), + version: str = "2.1", + p: float = 0.5, + keepdim: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(p=p, same_on_batch=True, keepdim=keepdim) + self.step_range = step_range + self._dslv = StableDiffusionDissolving(version, **kwargs) + self._param_generator = rg.PlainUniformGenerator((self.step_range, "step_range_factor", None, None)) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return self._dslv(input, params["step_range_factor"][0].long().item()) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/equalize.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/equalize.py new file mode 100644 index 0000000000000000000000000000000000000000..5c22af4322c8bce950072222860e1ffb579f7b89 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/equalize.py @@ -0,0 +1,69 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.enhance import equalize + + +class RandomEqualize(IntensityAugmentationBase2D): + r"""Equalize given tensor image or a batch of tensor images randomly. + + .. image:: _static/img/RandomEqualize.png + + Args: + p: Probability to equalize an image. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.equalize`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 5, 5) + >>> equalize = RandomEqualize(p=1.) + >>> equalize(input) + tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], + [0.6341, 0.4901, 0.8964, 0.4556, 0.6323], + [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], + [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], + [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomEqualize(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return equalize(input) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/erasing.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/erasing.py new file mode 100644 index 0000000000000000000000000000000000000000..7e54efad14fba061df5e42ebf929465c3f84f6e5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/erasing.py @@ -0,0 +1,113 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor, where +from kornia.geometry.bbox import bbox_generator, bbox_to_mask + + +class RandomErasing(IntensityAugmentationBase2D): + r"""Erase a random rectangle of a tensor image according to a probability p value. + + .. image:: _static/img/RandomErasing.png + + The operator removes image parts and fills them with zero values at a selected rectangle + for each of the images in the batch. + + The rectangle will have an area equal to the original image area multiplied by a value uniformly + sampled between the range [scale[0], scale[1]) and an aspect ratio sampled + between [ratio[0], ratio[1]) + + Args: + scale: range of proportion of erased area against input image. + ratio: range of aspect ratio of erased area. + value: the value to fill the erased area. + same_on_batch: apply the same transformation across the batch. + p: probability that the random erasing operation will be performed. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.ones(1, 1, 3, 3) + >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=0.5) + >>> aug(inputs) + tensor([[[[1., 0., 0.], + [1., 0., 0.], + [1., 0., 0.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33), + ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3), + value: float = 0.0, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.scale = scale + self.ratio = ratio + self.value = value + self._param_generator = rg.RectangleEraseGenerator(scale, ratio, value) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, c, h, w = input.size() + values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input) + + bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"]) + mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W + mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W + transformed = where(mask == 1.0, values, input) + return transformed + + def apply_transform_mask( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + _, c, h, w = input.size() + + values = params["values"][..., None, None, None].repeat(1, *input.shape[1:]).to(input) + # Erase the corresponding areas on masks. + values = values.zero_() + + bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"]) + mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W + mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W + transformed = where(mask == 1.0, values, input) + return transformed diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gamma.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd0d474592ef5943c52c14ba1660395de2614d1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gamma.py @@ -0,0 +1,90 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor +from kornia.enhance.adjust import adjust_gamma + + +class RandomGamma(IntensityAugmentationBase2D): + r"""Apply a random transformation to the gamma of a tensor image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + + .. image:: _static/img/RandomGamma.png + + Args: + p: probability of applying the transformation. + gamma: the gamma factor to apply. + gain: the gain factor to apply. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_gamma` + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.rand(1, 3, 3, 3) + >>> aug = RandomGamma((0.5,2.),(1.5,1.5),p=1.) + >>> aug(inputs) + tensor([[[[1.0000, 1.0000, 0.3912], + [0.4883, 0.7801, 1.0000], + [1.0000, 1.0000, 0.9702]], + + [[1.0000, 0.8368, 0.9048], + [0.1824, 0.5597, 0.7609], + [1.0000, 1.0000, 1.0000]], + + [[0.5452, 0.7441, 1.0000], + [1.0000, 0.8990, 1.0000], + [0.9267, 1.0000, 1.0000]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomGamma((0.8,1.2), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + gamma: Tuple[float, float] = (1.0, 1.0), + gain: Tuple[float, float] = (1.0, 1.0), + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator = rg.PlainUniformGenerator( + (gamma, "gamma_factor", None, None), (gain, "gain_factor", None, None) + ) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + gamma_factor = params["gamma_factor"].to(input) + gain_factor = params["gain_factor"].to(input) + return adjust_gamma(input, gamma_factor, gain_factor) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_blur.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_blur.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc6eafae467cda40fae21531f0087982eb98009 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_blur.py @@ -0,0 +1,130 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import torch +from torch import Tensor + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.constants import BorderType +from kornia.filters import gaussian_blur2d + + +class RandomGaussianBlur(IntensityAugmentationBase2D): + r"""Apply gaussian blur given tensor image or a batch of tensor images randomly. + + The standard deviation is sampled for each instance. + + .. image:: _static/img/RandomGaussianBlur.png + + Args: + kernel_size: the size of the kernel. + sigma: the range for the standard deviation of the kernel. + border_type: the padding mode to be applied before convolving. + The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``. + separable: run as composition of two 1d-convolutions. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + silence_instantiation_warning: if True, silence the warning at instantiation. + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.filters.gaussian_blur2d`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 5, 5) + >>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.) + >>> blur(input) + tensor([[[[0.5941, 0.5833, 0.5022, 0.4384, 0.3934], + [0.5310, 0.4964, 0.4113, 0.3637, 0.3472], + [0.4991, 0.4997, 0.4312, 0.3620, 0.3081], + [0.6082, 0.5667, 0.4954, 0.3825, 0.3508], + [0.7042, 0.6849, 0.6275, 0.4753, 0.4105]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + kernel_size: Union[Tuple[int, int], int], + sigma: Union[Tuple[float, float], Tensor], + border_type: str = "reflect", + separable: bool = True, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + self.flags = { + "kernel_size": kernel_size, + "separable": separable, + "border_type": BorderType.get(border_type), + } + self._param_generator = rg.RandomGaussianBlurGenerator(sigma) + + self._gaussian_blur2d_fn = gaussian_blur2d + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + sigma = params["sigma"].unsqueeze(-1).expand(-1, 2) + return self._gaussian_blur2d_fn( + input, + kernel_size=self.flags["kernel_size"], + sigma=sigma, + border_type=self.flags["border_type"].name.lower(), + separable=self.flags["separable"], + ) + + def compile( + self, + *, + fullgraph: bool = False, + dynamic: bool = False, + backend: str = "inductor", + mode: Optional[str] = None, + options: Optional[Dict[Any, Any]] = None, + disable: bool = False, + ) -> "RandomGaussianBlur": + self._gaussian_blur2d_fn = torch.compile( + self._gaussian_blur2d_fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + return self diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_illumination.py new file mode 100644 index 0000000000000000000000000000000000000000..eb781e2d596420defb2472c7c24b1e439d4a9ee3 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_illumination.py @@ -0,0 +1,204 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerator +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK + + +class RandomGaussianIllumination(IntensityAugmentationBase2D): + r"""Applies random 2D Gaussian illumination patterns to a batch of images. + + .. image:: _static/img/RandomGaussianIllumination.png + + Args: + gain: Range for the gain factor (intensity) applied to the generated illumination. + center: The center coordinates of the Gaussian distribution are expressed as a + percentage of the spatial dimensions :math:(H, W). + sigma: The sigma values (standard deviation) of the Gaussian distribution are expressed as a + percentage of the spatial dimensions :math:(H, W). + sign: Range for the sign of the Gaussian distribution. If only one sign is needed, + insert only as a tuple or float. + p: Probability of applying the transformation. + same_on_batch: If True, apply the same transformation across the entire batch. Default is False. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + The generated random numbers are not reproducible across different devices and dtypes. By default, + the parameters will be generated on CPU. This can be changed by calling + ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``. + + Examples: + >>> rng = torch.manual_seed(1) + >>> input = torch.ones(1, 3, 3, 3) * 0.5 + >>> aug = RandomGaussianIllumination(gain=0.5, p=1.) + >>> aug(input) + tensor([[[[0.7266, 1.0000, 0.7266], + [0.6621, 0.9121, 0.6621], + [0.5000, 0.6911, 0.5000]], + + [[0.7266, 1.0000, 0.7266], + [0.6621, 0.9121, 0.6621], + [0.5000, 0.6911, 0.5000]], + + [[0.7266, 1.0000, 0.7266], + [0.6621, 0.9121, 0.6621], + [0.5000, 0.6911, 0.5000]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomGaussianIllumination(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.15), + center: Optional[Union[float, Tuple[float, float]]] = (0.1, 0.9), + sigma: Optional[Union[float, Tuple[float, float]]] = (0.2, 1.0), + sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0), + p: float = 0.5, + same_on_batch: bool = False, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + # Validation and initialization of amount parameter. + if isinstance(gain, (tuple, float)): + if isinstance(gain, float): + gain = (gain, gain) + elif len(gain) == 1: + gain = (gain[0], gain[0]) + elif len(gain) > 2 or len(gain) <= 0: + raise ValueError( + "The length of gain must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("gain must be a tuple or a float") + KORNIA_CHECK( + all(0 <= el <= 1 for el in gain), + "gain values must be between 0 and 1. Recommended values less than 0.2.", + ) + + if isinstance(center, (tuple, float)): + if isinstance(center, float): + center = (center, center) + elif len(center) == 1: + center = (center[0], center[0]) + elif len(center) > 2 or len(center) <= 0: + raise ValueError( + "The length of center must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("center must be a tuple or a float") + KORNIA_CHECK( + all(0 <= el <= 1 for el in center), + "center of gaussian value must be between 0 and 1.", + ) + + if isinstance(sigma, (tuple, float)): + if isinstance(sigma, float): + sigma = (sigma, sigma) + elif len(sigma) == 1: + sigma = (sigma[0], sigma[0]) + elif len(sigma) > 2 or len(sigma) <= 0: + raise ValueError( + "The length of sigma must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("sigma must be a tuple or a float") + KORNIA_CHECK( + all(0 <= el <= 1 for el in sigma), + "sigma of gaussian value must be between 0 and 1.", + ) + + if isinstance(sign, (tuple, float)): + if isinstance(sign, float): + sign = (sign, sign) + elif len(sign) == 1: + sign = (sign[0], sign[0]) + elif len(sign) > 2 or len(sign) <= 0: + raise ValueError( + "The length of sign must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("sign must be a tuple or a float") + KORNIA_CHECK( + all(-1 <= el <= 1 for el in sign), + "sign of gaussian value must be between -1 and 1.", + ) + + # Generator of random parameters and masks. + self._param_generator = GaussianIlluminationGenerator(gain, center, sigma, sign) + + def _apply_transform( + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + return input.add_(params["gradient"]).clamp_(0, 1) + + self._fn = _apply_transform + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + r"""Apply random gaussian gradient illumination to the input image.""" + return self._fn(input=input, params=params, flags=flags, transform=transform) + + def compile( + self, + *, + fullgraph: bool = False, + dynamic: bool = False, + backend: str = "inductor", + mode: Optional[str] = None, + options: Optional[Dict[Any, Any]] = None, + disable: bool = False, + ) -> "RandomGaussianIllumination": + self._fn = torch.compile( + self._fn, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + + return self diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_noise.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..e1355afc9d50b836b9386e707ded0e6b36bc2cc1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_noise.py @@ -0,0 +1,80 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +import torch + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor + + +def _randn_like(input: Tensor, mean: float, std: float) -> Tensor: + x = torch.randn_like(input) # Generating on GPU is fastest with `torch.randn_like(...)` + if std != 1.0: # `if` is cheaper than multiplication + x *= std + if mean != 0.0: # `if` is cheaper than addition + x += mean + return x + + +class RandomGaussianNoise(IntensityAugmentationBase2D): + r"""Add gaussian noise to a batch of multi-dimensional images. + + .. image:: _static/img/RandomGaussianNoise.png + + Args: + mean: The mean of the gaussian distribution. + std: The standard deviation of the gaussian distribution. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Examples: + >>> rng = torch.manual_seed(0) + >>> img = torch.ones(1, 1, 2, 2) + >>> RandomGaussianNoise(mean=0., std=1., p=1.)(img) + tensor([[[[ 2.5410, 0.7066], + [-1.1788, 1.5684]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomGaussianNoise(mean=0., std=1., p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, mean: float = 0.0, std: float = 1.0, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = {"mean": mean, "std": std} + + def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]: + return {} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if "gaussian_noise" in params: + gaussian_noise = params["gaussian_noise"] + else: + gaussian_noise = _randn_like(input, mean=flags["mean"], std=flags["std"]) + self._params["gaussian_noise"] = gaussian_noise + return input + gaussian_noise diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/grayscale.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/grayscale.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce2b30c769ec9aef106f8ad005f3155faafaced --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/grayscale.py @@ -0,0 +1,84 @@ +# 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. +# + +from typing import Any, Dict, Optional + +import torch +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.color import rgb_to_grayscale + + +class RandomGrayscale(IntensityAugmentationBase2D): + r"""Apply random transformation to Grayscale according to a probability p value. + + .. image:: _static/img/RandomGrayscale.png + + Args: + rgb_weights: Weights that will be applied on each channel (RGB). + The sum of the weights should add up to one. + p: probability of the image to be transformed to grayscale. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.color.rgb_to_grayscale`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.randn((1, 3, 3, 3)) + >>> aug = RandomGrayscale(p=1.0) + >>> aug(inputs) + tensor([[[[-1.1344, -0.1330, 0.1517], + [-0.0791, 0.6711, -0.1413], + [-0.1717, -0.9023, 0.0819]], + + [[-1.1344, -0.1330, 0.1517], + [-0.0791, 0.6711, -0.1413], + [-0.1717, -0.9023, 0.0819]], + + [[-1.1344, -0.1330, 0.1517], + [-0.0791, 0.6711, -0.1413], + [-0.1717, -0.9023, 0.0819]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomGrayscale(p=1.0) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, rgb_weights: Optional[Tensor] = None, same_on_batch: bool = False, p: float = 0.1, keepdim: bool = False + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.rgb_weights = rgb_weights + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + # Make sure it returns (*, 3, H, W) + grayscale = torch.ones_like(input) + grayscale[:] = rgb_to_grayscale(input, rgb_weights=self.rgb_weights) + return grayscale diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/hue.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/hue.py new file mode 100644 index 0000000000000000000000000000000000000000..2b049cb587c362ec4410e30a39b36c11dfade700 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/hue.py @@ -0,0 +1,85 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.utils import _range_bound +from kornia.constants import pi +from kornia.core import Tensor +from kornia.enhance.adjust import adjust_hue + + +class RandomHue(IntensityAugmentationBase2D): + r"""Apply a random transformation to the hue of a tensor image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + + .. image:: _static/img/RandomHue.png + + Args: + hue: the saturation factor to apply. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.adjust_hue` + + Examples: + >>> rng = torch.manual_seed(0) + >>> inputs = torch.rand(1, 3, 3, 3) + >>> aug = RandomHue(hue = (-0.5,0.5),p=1.) + >>> aug(inputs) + tensor([[[[0.3993, 0.2823, 0.6816], + [0.6117, 0.2090, 0.4081], + [0.4693, 0.5529, 0.9527]], + + [[0.1610, 0.5962, 0.4971], + [0.9152, 0.3971, 0.8742], + [0.4194, 0.6771, 0.7162]], + + [[0.6323, 0.7682, 0.0885], + [0.0223, 0.1689, 0.2939], + [0.5185, 0.8964, 0.4556]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomHue((-0.2,0.2), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, hue: Tuple[float, float] = (0.0, 0.0), same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.hue: Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5)) + self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None)) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + hue_factor = params["hue_factor"].to(input) + return adjust_hue(input, hue_factor * 2 * pi) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/invert.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/invert.py new file mode 100644 index 0000000000000000000000000000000000000000..26d23d5d6676a325c91a0621f0accb2298b58629 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/invert.py @@ -0,0 +1,74 @@ +# 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. +# + +from typing import Any, Dict, Optional, Union + +import torch +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.enhance import invert + + +class RandomInvert(IntensityAugmentationBase2D): + r"""Invert the tensor images values randomly. + + .. image:: _static/img/RandomInvert.png + + Args: + max_val: The expected maximum value in the input tensor. The shape has to + according to the input tensor shape, or at least has to work with broadcasting. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + .. note:: + This function internally uses :func:`kornia.enhance.invert`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> img = torch.rand(1, 1, 5, 5) + >>> inv = RandomInvert() + >>> inv(img) + tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], + [0.6341, 0.4901, 0.8964, 0.4556, 0.6323], + [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], + [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], + [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomInvert(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + max_val: Union[float, Tensor] = 1.0, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = {"max_val": max_val} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return invert(input, torch.as_tensor(flags["max_val"], device=input.device, dtype=input.dtype)) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/jpeg.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/jpeg.py new file mode 100644 index 0000000000000000000000000000000000000000..035162e46a6e58c2bf5af7e2b0636043f46b8238 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/jpeg.py @@ -0,0 +1,75 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor +from kornia.enhance import jpeg_codec_differentiable + + +class RandomJPEG(IntensityAugmentationBase2D): + r"""Applies random (differentiable) JPEG coding to a tensor image. + + .. image:: _static/img/RandomJPEG.png + + Args: + jpeg_quality: The range of compression rates to be applied. + p: probability of applying the transformation. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + This function internally uses :func:`kornia.enhance.jpeg_codec_differentiable`. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> images = 0.1904 * torch.ones(2, 3, 32, 32) + >>> aug = RandomJPEG(jpeg_quality=(1.0, 50.0), p=1.) + >>> images_jpeg = aug(images) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> images = 0.1904 * torch.ones(2, 3, 32, 32) + >>> aug = RandomJPEG(jpeg_quality=20.0, p=1.) # Samples a JPEG quality from the range [30.0, 70.0] + >>> (aug(images) == aug(images, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0, + same_on_batch: bool = False, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.jpeg_quality = jpeg_quality + self._param_generator = rg.JPEGGenerator(jpeg_quality) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + jpeg_output: Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"]) + return jpeg_output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/linear_illumination.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/linear_illumination.py new file mode 100644 index 0000000000000000000000000000000000000000..1bcf5a6be43f0cb3d2d037643b3bdd4df3967035 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/linear_illumination.py @@ -0,0 +1,237 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGenerator +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK + + +class RandomLinearIllumination(IntensityAugmentationBase2D): + r"""Applies random 2D Linear illumination patterns to a batch of images. + + .. image:: _static/img/RandomLinearIllumination.png + + Args: + gain: Range for the gain factor (intensity) applied to the generated illumination. + sign: Range for the sign of the distribution. If only one sign is needed, + insert only as a tuple or float. + p: Probability of applying the transformation. + same_on_batch: If True, apply the same transformation across the entire batch. Default is False. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + The generated random numbers are not reproducible across different devices and dtypes. By default, + the parameters will be generated on CPU. This can be changed by calling + ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``. + + Examples: + >>> rng = torch.manual_seed(1) + >>> input = torch.ones(1, 3, 3, 3) * 0.5 + >>> aug = RandomLinearIllumination(gain=0.25, p=1.) + >>> aug(input) + tensor([[[[0.2500, 0.2500, 0.2500], + [0.3750, 0.3750, 0.3750], + [0.5000, 0.5000, 0.5000]], + + [[0.2500, 0.2500, 0.2500], + [0.3750, 0.3750, 0.3750], + [0.5000, 0.5000, 0.5000]], + + [[0.2500, 0.2500, 0.2500], + [0.3750, 0.3750, 0.3750], + [0.5000, 0.5000, 0.5000]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomLinearIllumination(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.2), + sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0), + p: float = 0.5, + same_on_batch: bool = False, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + # Validation and initialization of amount parameter. + if isinstance(gain, (tuple, float)): + if isinstance(gain, float): + gain = (gain, gain) + elif len(gain) == 1: + gain = (gain[0], gain[0]) + elif len(gain) > 2 or len(gain) <= 0: + raise ValueError( + "The length of gain must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("gain must be a tuple or a float") + KORNIA_CHECK( + all(0 <= el <= 1 for el in gain), + "gain values must be between 0 and 1. Recommended values less than 0.2.", + ) + + if isinstance(sign, (tuple, float)): + if isinstance(sign, float): + sign = (sign, sign) + elif len(sign) == 1: + sign = (sign[0], sign[0]) + elif len(sign) > 2 or len(sign) <= 0: + raise ValueError( + "The length of sign must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("sign must be a tuple or a float") + KORNIA_CHECK( + all(-1 <= el <= 1 for el in sign), + "sign of linear value must be between -1 and 1.", + ) + + # Generator of random parameters and masks. + self._param_generator = LinearIlluminationGenerator(gain, sign) + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + r"""Apply random gaussian gradient illumination to the input image.""" + return input.add(params["gradient"].to(input)).clamp(0, 1) + + +class RandomLinearCornerIllumination(IntensityAugmentationBase2D): + r"""Applies random 2D Linear from corner illumination patterns to a batch of images. + + .. image:: _static/img/RandomLinearCornerIllumination.png + + Args: + gain: Range for the gain factor (intensity) applied to the generated illumination. + sign: Range for the sign of the distribution. If only one sign is needed, + insert only as a tuple or float. + p: Probability of applying the transformation. + same_on_batch: If True, apply the same transformation across the entire batch. Default is False. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + The generated random numbers are not reproducible across different devices and dtypes. By default, + the parameters will be generated on CPU. This can be changed by calling + ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``. + + Examples: + >>> rng = torch.manual_seed(1) + >>> input = torch.ones(1, 3, 3, 3) * 0.5 + >>> aug = RandomLinearCornerIllumination(gain=0.25, p=1.) + >>> aug(input) + tensor([[[[0.3750, 0.4375, 0.5000], + [0.3125, 0.3750, 0.4375], + [0.2500, 0.3125, 0.3750]], + + [[0.3750, 0.4375, 0.5000], + [0.3125, 0.3750, 0.4375], + [0.2500, 0.3125, 0.3750]], + + [[0.3750, 0.4375, 0.5000], + [0.3125, 0.3750, 0.4375], + [0.2500, 0.3125, 0.3750]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32) + >>> aug = RandomLinearCornerIllumination(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.2), + sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0), + p: float = 0.5, + same_on_batch: bool = False, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + + # Validation and initialization of amount parameter. + if isinstance(gain, (tuple, float)): + if isinstance(gain, float): + gain = (gain, gain) + elif len(gain) == 1: + gain = (gain[0], gain[0]) + elif len(gain) > 2 or len(gain) <= 0: + raise ValueError( + "The length of gain must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("gain must be a tuple or a float") + KORNIA_CHECK( + all(0 <= el <= 1 for el in gain), + "gain values must be between 0 and 1. Recommended values less than 0.2.", + ) + + if isinstance(sign, (tuple, float)): + if isinstance(sign, float): + sign = (sign, sign) + elif len(sign) == 1: + sign = (sign[0], sign[0]) + elif len(sign) > 2 or len(sign) <= 0: + raise ValueError( + "The length of sign must be greater than 0 \ + and less than or equal to 2, and it should be a tuple or a float." + ) + else: + raise ValueError("sign must be a tuple or a float") + KORNIA_CHECK( + all(-1 <= el <= 1 for el in sign), + "sign of linear value must be between -1 and 1.", + ) + + # Generator of random parameters and masks. + self._param_generator = LinearCornerIlluminationGenerator(gain, sign) + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + r"""Apply random gaussian gradient illumination to the input image.""" + return input.add(params["gradient"].to(input)).clamp(0, 1) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/median_blur.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/median_blur.py new file mode 100644 index 0000000000000000000000000000000000000000..5795da3c19cca8f171e06ddeba8cecd5681d037d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/median_blur.py @@ -0,0 +1,68 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple + +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.filters import median_blur + + +class RandomMedianBlur(IntensityAugmentationBase2D): + """Add random blur with a median filter to an image tensor. + + .. image:: _static/img/RandomMedianBlur.png + + Args: + kernel_size: the blurring kernel size. + same_on_batch: apply the same transformation across the batch. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + .. note:: + This function internally uses :func:`kornia.filters.median_blur`. + + Examples: + >>> img = torch.ones(1, 1, 4, 4) + >>> out = RandomMedianBlur((3, 3), p = 1)(img) + >>> out.shape + torch.Size([1, 1, 4, 4]) + >>> out + tensor([[[[0., 1., 1., 0.], + [1., 1., 1., 1.], + [1., 1., 1., 1.], + [0., 1., 1., 0.]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomMedianBlur((7, 7), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, kernel_size: Tuple[int, int] = (3, 3), same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = {"kernel_size": kernel_size} + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return median_blur(input, flags["kernel_size"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/motion_blur.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/motion_blur.py new file mode 100644 index 0000000000000000000000000000000000000000..d894652446912b4d4e4c3b9997bd716816b64430 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/motion_blur.py @@ -0,0 +1,125 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union, cast + +import torch + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.constants import BorderType, Resample +from kornia.core import Tensor, tensor +from kornia.filters import motion_blur + + +class RandomMotionBlur(IntensityAugmentationBase2D): + r"""Perform motion blur on 2D images (4D tensor). + + .. image:: _static/img/RandomMotionBlur.png + + Args: + p: probability of applying the transformation. + kernel_size: motion kernel size (odd and positive). + If int, the kernel will have a fixed size. + If Tuple[int, int], it will randomly generate the value from the range batch-wisely. + angle: angle of the motion blur in degrees (anti-clockwise rotation). + If float, it will generate the value from (-angle, angle). + direction: forward/backward direction of the motion blur. + Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle), + while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a + uniformly (but still angled) motion blur. + If float, it will generate the value from (-direction, direction). + If Tuple[int, int], it will randomly generate the value from the range. + border_type: the padding mode to be applied before convolving. + CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. + resample: the interpolation mode. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)` + - Output: :math:`(B, C, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted. + + .. note:: + This function internally uses :func:`kornia.filters.motion_blur`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> input = torch.ones(1, 1, 5, 5) + >>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.) + >>> motion_blur(input) + tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561], + [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], + [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], + [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], + [0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.randn(1, 3, 32, 32) + >>> aug = RandomMotionBlur(3, 35., 0.5, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + kernel_size: Union[int, Tuple[int, int]], + angle: Union[Tensor, float, Tuple[float, float]], + direction: Union[Tensor, float, Tuple[float, float]], + border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name, + resample: Union[str, int, Resample] = Resample.NEAREST.name, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction) + self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)} + + def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + params = super().generate_parameters(batch_shape) + params["idx"] = tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,)) + return params + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + # sample a kernel size + kernel_size_list: List[int] = params["ksize_factor"].tolist() + + # 1. We have to apply the same kernel size to all samples in the batch, thus we take the previously + # selected random index --- `params["idx"][0]` --- to determine the applied kernel size. + # 2. The `VideoSequential` flattens the first two dimensions, effectively creating a larger batch. + # Its method `VideoSequential.__repeat_param_across_channels__` repeats the previously selected index, + # creating a tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit. + idx: int = cast(int, params["idx"][0]) + return motion_blur( + input, + kernel_size=kernel_size_list[idx], + angle=params["angle_factor"], + direction=params["direction_factor"], + border_type=flags["border_type"].name.lower(), + mode=flags["resample"].name.lower(), + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/normalize.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff143ced39fa6d290908b05efa9b514cc48efae --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/normalize.py @@ -0,0 +1,84 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any, Optional + +import torch +from torch import Tensor + +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.enhance import normalize + + +class Normalize(IntensityAugmentationBase2D): + r"""Normalize tensor images with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] - mean[channel]) / std[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + mean: Mean for each channel. + std: Standard deviations for each channel. + p: probability of applying the transformation. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Return: + Normalised tensor with same size as input :math:`(*, C, H, W)`. + + .. note:: + This function internally uses :func:`kornia.enhance.normalize`. + + Examples: + >>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4)) + >>> x = torch.rand(1, 4, 3, 3) + >>> out = norm(x) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + """ + + def __init__( + self, + mean: Tensor | tuple[float, ...] | list[float] | float, + std: Tensor | tuple[float, ...] | list[float] | float, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=True, keepdim=keepdim) + if isinstance(mean, (int, float)): + mean = torch.tensor([mean]) + + if isinstance(std, (int, float)): + std = torch.tensor([std]) + + if isinstance(mean, (tuple, list)): + mean = torch.tensor(mean) + + if isinstance(std, (tuple, list)): + std = torch.tensor(std) + + self.flags = {"mean": mean, "std": std} + + def apply_transform( + self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return normalize(input, flags["mean"], flags["std"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/planckian_jitter.py b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/planckian_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..793099aa49770dfdf855363186a503ab570f95dd --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/planckian_jitter.py @@ -0,0 +1,203 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.core import Tensor, stack, tensor +from kornia.core.check import KORNIA_CHECK_SHAPE + + +def get_planckian_coeffs(mode: str) -> Tensor: + if mode.lower() == "blackbody": + coefs = tensor( + [ + [0.6743, 0.4029, 0.0013], + [0.6281, 0.4241, 0.1665], + [0.5919, 0.4372, 0.2513], + [0.5623, 0.4457, 0.3154], + [0.5376, 0.4515, 0.3672], + [0.5163, 0.4555, 0.4103], + [0.4979, 0.4584, 0.4468], + [0.4816, 0.4604, 0.4782], + [0.4672, 0.4619, 0.5053], + [0.4542, 0.4630, 0.5289], + [0.4426, 0.4638, 0.5497], + [0.4320, 0.4644, 0.5681], + [0.4223, 0.4648, 0.5844], + [0.4135, 0.4651, 0.5990], + [0.4054, 0.4653, 0.6121], + [0.3980, 0.4654, 0.6239], + [0.3911, 0.4655, 0.6346], + [0.3847, 0.4656, 0.6444], + [0.3787, 0.4656, 0.6532], + [0.3732, 0.4656, 0.6613], + [0.3680, 0.4655, 0.6688], + [0.3632, 0.4655, 0.6756], + [0.3586, 0.4655, 0.6820], + [0.3544, 0.4654, 0.6878], + [0.3503, 0.4653, 0.6933], + ] + ) + + elif mode.upper() == "CIED": + coefs = tensor( + [ + [0.5829, 0.4421, 0.2288], + [0.5510, 0.4514, 0.2948], + [0.5246, 0.4576, 0.3488], + [0.5021, 0.4618, 0.3941], + [0.4826, 0.4646, 0.4325], + [0.4654, 0.4667, 0.4654], + [0.4502, 0.4681, 0.4938], + [0.4364, 0.4692, 0.5186], + [0.4240, 0.4700, 0.5403], + [0.4127, 0.4705, 0.5594], + [0.4023, 0.4709, 0.5763], + [0.3928, 0.4713, 0.5914], + [0.3839, 0.4715, 0.6049], + [0.3757, 0.4716, 0.6171], + [0.3681, 0.4717, 0.6281], + [0.3609, 0.4718, 0.6380], + [0.3543, 0.4719, 0.6472], + [0.3480, 0.4719, 0.6555], + [0.3421, 0.4719, 0.6631], + [0.3365, 0.4719, 0.6702], + [0.3313, 0.4719, 0.6766], + [0.3263, 0.4719, 0.6826], + [0.3217, 0.4719, 0.6882], + ] + ) + else: + raise RuntimeError(f"Unexpected mode. Gotcha {mode}") + + return stack((coefs[:, 0] / coefs[:, 1], coefs[:, 2] / coefs[:, 1]), 1) + + +class RandomPlanckianJitter(IntensityAugmentationBase2D): + r"""Apply planckian jitter transformation to input tensor. + + .. image:: _static/img/RandomPlanckianJitter.png + + This is physics based color augmentation, that creates realistic + variations in chromaticity, this can simulate the illumination + changes in the scene. + + See :cite:`zini2022planckian` for more details. + + Args: + mode: 'blackbody' or 'CIED'. + select_from: choose a list of jitters to apply from. `blackbody` range [0-24], `CIED` range [0-22] + same_on_batch: apply the same transformation across the batch. + p: probability that the random erasing operation will be performed. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + .. note:: + Input tensor must be float and normalized into [0, 1]. + + Examples: + To apply planckian jitter based on mode + + >>> rng = torch.manual_seed(0) + >>> input = torch.randn(1, 3, 2, 2) + >>> aug = RandomPlanckianJitter(mode='CIED') + >>> aug(input) + tensor([[[[ 1.0000, -0.2389], + [-1.7740, 0.4628]], + + [[-1.0845, -1.3986], + [ 0.4033, 0.8380]], + + [[-0.9228, -0.5175], + [-0.7654, 0.2335]]]]) + + To apply planckian jitter on image(s) from list of interested jitters + + >>> rng = torch.manual_seed(0) + >>> input = torch.randn(2, 3, 2, 2) + >>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2]) + >>> aug(input) + tensor([[[[-1.1258, -1.1524], + [-0.2506, -0.4339]], + + [[ 0.8487, 0.6920], + [-0.3160, -2.1152]], + + [[ 0.4681, -0.1577], + [ 1.4437, 0.2660]]], + + + [[[ 0.2465, 1.0000], + [-0.2125, -0.1653]], + + [[ 0.9318, 1.0000], + [ 1.0000, 0.0537]], + + [[ 0.2426, -0.1621], + [-0.3302, -0.9093]]]]) + + """ + + def __init__( + self, + mode: str = "blackbody", + select_from: Optional[Union[int, List[int]]] = None, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + if isinstance(select_from, int): + select_from = [select_from] + + _pl = get_planckian_coeffs(mode) + if select_from is not None: + _pl = _pl[select_from] + self.register_buffer("pl", _pl) + self.pl: Tensor + + # the range of the sampling parameters + _param_min: float = 0.0 + _param_max: float = float(self.pl.shape[0]) + + self._param_generator = rg.PlanckianJitterGenerator([_param_min, _param_max]) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + list_idx = params["idx"].tolist() + KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"]) + self.pl = self.pl.to(device=input.device) + coeffs = self.pl[list_idx] + + r_w = coeffs[:, 0][..., None, None] + b_w = coeffs[:, 1][..., None, None] + + r = input[..., 0, :, :] * r_w + g = input[..., 1, :, :] + b = input[..., 2, :, :] * b_w + + output = stack([r, g, b], -3) + + return output.clamp(max=1.0) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..570e7e32792bea415fd886e6c8e2c5c6c5011b94 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/__init__.py @@ -0,0 +1,20 @@ +# 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. +# + +from kornia.augmentation._3d.geometric import * +from kornia.augmentation._3d.intensity import * +from kornia.augmentation._3d.mix import * diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/base.py new file mode 100644 index 0000000000000000000000000000000000000000..4fefa116b636631a7cea73c306f1fe6bc8aa987b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/base.py @@ -0,0 +1,138 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from torch import float16, float32, float64 + +import kornia +from kornia.augmentation.base import _AugmentationBase +from kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype +from kornia.core import Tensor +from kornia.geometry.boxes import Boxes3D +from kornia.geometry.keypoints import Keypoints3D + + +class AugmentationBase3D(_AugmentationBase): + r"""AugmentationBase3D base class for customized augmentation implementations. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + + """ + + def validate_tensor(self, input: Tensor) -> None: + """Check if the input tensor is formatted as expected.""" + _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64]) + if len(input.shape) != 5: + raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.") + + def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor: + """Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W).""" + _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64]) + if shape is None: + return _transform_input3d(input) + else: + return _transform_input3d_by_shape(input, reference_shape=shape, match_channel=match_channel) + + def identity_matrix(self, input: Tensor) -> Tensor: + """Return 4x4 identity matrix.""" + return kornia.eye_like(4, input) + + +class RigidAffineAugmentationBase3D(AugmentationBase3D): + r"""AugmentationBase2D base class for rigid/affine augmentation implementations. + + RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices + for different data types like masks, boxes, and keypoints. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch + form ``False``. + + """ + + _transform_matrix: Optional[Tensor] + + @property + def transform_matrix(self) -> Optional[Tensor]: + return self._transform_matrix + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + raise NotImplementedError + + def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + """Generate transformation matrices with the given input and param settings.""" + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + in_tensor = self.transform_tensor(input) + if not to_apply.any(): + trans_matrix = self.identity_matrix(in_tensor) + elif to_apply.all(): + trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags) + else: + trans_matrix = self.identity_matrix(in_tensor) + trans_matrix = trans_matrix.index_put( + (to_apply,), self.compute_transformation(in_tensor[to_apply], params=params, flags=flags) + ) + return trans_matrix + + def inverse_inputs( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def inverse_masks( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def inverse_boxes( + self, input: Boxes3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Boxes3D: + raise NotImplementedError + + def inverse_keypoints( + self, input: Keypoints3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Keypoints3D: + raise NotImplementedError + + def inverse_classes( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + raise NotImplementedError + + def apply_func( + self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None + ) -> Tensor: + if flags is None: + flags = self.flags + + trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags) + output = self.transform_inputs(in_tensor, params, flags, trans_matrix) + self._transform_matrix = trans_matrix + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1be9b503244d1b6424bca783b8d8a25a522d328b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/__init__.py @@ -0,0 +1,25 @@ +# 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. +# + +from kornia.augmentation._3d.geometric.affine import RandomAffine3D +from kornia.augmentation._3d.geometric.center_crop import CenterCrop3D +from kornia.augmentation._3d.geometric.crop import RandomCrop3D +from kornia.augmentation._3d.geometric.depthical_flip import RandomDepthicalFlip3D +from kornia.augmentation._3d.geometric.horizontal_flip import RandomHorizontalFlip3D +from kornia.augmentation._3d.geometric.perspective import RandomPerspective3D +from kornia.augmentation._3d.geometric.rotation import RandomRotation3D +from kornia.augmentation._3d.geometric.vertical_flip import RandomVerticalFlip3D diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/affine.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/affine.py new file mode 100644 index 0000000000000000000000000000000000000000..7a774055c2ec3e19a0c6760903fa029595b7f104 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/affine.py @@ -0,0 +1,172 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry import deg2rad, get_affine_matrix3d, warp_affine3d + + +class RandomAffine3D(GeometricAugmentationBase3D): + r"""Apply affine transformation 3D volumes (5D tensor). + + The transformation is computed so that the center is kept invariant. + + Args: + degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from. + If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees). + If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). + If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) + and (-c, c). + If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from + (a, b), (m, n) and (x, y). + Set to 0 to deactivate rotations. + translate: tuple of maximum absolute fraction for horizontal, vertical and + depthical translations (dx,dy,dz). For example translate=(a, b, c), then + horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a + vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b. + depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c. + Will not translate by default. + scale: scaling factor interval. + If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b. + If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b, + c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default. + shears: Range of degrees to select from. + If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied. + If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied. + If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i]) + will be applied. + If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1]) + will be applied. + resample: resample mode from "nearest" (0) or "bilinear" (1). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). Default: False. + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3, 3) + >>> aug = RandomAffine3D((15., 20., 20.), p=1.) + >>> aug(input), aug.transform_matrix + (tensor([[[[[0.4503, 0.4763, 0.1680], + [0.2029, 0.4267, 0.3515], + [0.3195, 0.5436, 0.3706]], + + [[0.5255, 0.3508, 0.4858], + [0.0795, 0.1689, 0.4220], + [0.5306, 0.7234, 0.6879]], + + [[0.2971, 0.2746, 0.3471], + [0.4924, 0.4960, 0.6460], + [0.3187, 0.4556, 0.7596]]]]]), tensor([[[ 0.9722, -0.0603, 0.2262, -0.1381], + [ 0.1131, 0.9669, -0.2286, 0.1486], + [-0.2049, 0.2478, 0.9469, 0.0102], + [ 0.0000, 0.0000, 0.0000, 1.0000]]])) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomAffine3D((15., 20., 20.), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + degrees: Union[ + Tensor, + float, + Tuple[float, float], + Tuple[float, float, float], + Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]], + ], + translate: Optional[Union[Tensor, Tuple[float, float, float]]] = None, + scale: Optional[ + Union[Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]] + ] = None, + shears: Union[ + None, + Tensor, + float, + Tuple[float, float], + Tuple[float, float, float, float, float, float], + Tuple[ + Tuple[float, float], + Tuple[float, float], + Tuple[float, float], + Tuple[float, float], + Tuple[float, float], + Tuple[float, float], + ], + ] = None, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.degrees = degrees + self.shears = shears + self.translate = translate + self.scale = scale + + self.flags = {"resample": Resample.get(resample), "align_corners": align_corners} + self._param_generator = rg.AffineGenerator3D(degrees, translate, scale, shears) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + transform: Tensor = get_affine_matrix3d( + params["translations"], + params["center"], + params["scale"], + params["angles"], + deg2rad(params["sxy"]), + deg2rad(params["sxz"]), + deg2rad(params["syx"]), + deg2rad(params["syz"]), + deg2rad(params["szx"]), + deg2rad(params["szy"]), + ).to(input) + return transform + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}") + + return warp_affine3d( + input, + transform[:, :3, :], + (input.shape[-3], input.shape[-2], input.shape[-1]), + flags["resample"].name.lower(), + align_corners=flags["align_corners"], + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/base.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a25e3d0cfdb648dbfed9393463ff1836d2f500 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/base.py @@ -0,0 +1,22 @@ +# 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. +# + +from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D + + +class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D): + pass diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/center_crop.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/center_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..1537126ef3e3a16f3fc7b6cb8b261def6df4df3d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/center_crop.py @@ -0,0 +1,114 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union, cast + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d + + +class CenterCrop3D(GeometricAugmentationBase3D): + r"""Apply center crop on 3D volumes (5D tensor). + + Args: + p: probability of applying the transformation for the whole batch. + size (Tuple[int, int, int] or int): Desired output size (out_d, out_h, out_w) of the crop. + If integer, out_d = out_h = out_w = size. + If Tuple[int, int, int], out_d = size[0], out_h = size[1], out_w = size[2]. + resample: resample mode from "nearest" (0) or "bilinear" (1). + align_corners: interpolation flag. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, out_d, out_h, out_w)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> inputs = torch.randn(1, 1, 2, 4, 6) + >>> inputs + tensor([[[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487, 0.6920], + [-0.3160, -2.1152, 0.3223, -1.2633, 0.3500, 0.3081], + [ 0.1198, 1.2377, 1.1168, -0.2473, -1.3527, -1.6959], + [ 0.5667, 0.7935, 0.5988, -1.5551, -0.3414, 1.8530]], + + [[ 0.7502, -0.5855, -0.1734, 0.1835, 1.3894, 1.5863], + [ 0.9463, -0.8437, -0.6136, 0.0316, -0.4927, 0.2484], + [ 0.4397, 0.1124, 0.6408, 0.4412, -0.1023, 0.7924], + [-0.2897, 0.0525, 0.5229, 2.3022, -1.4689, -1.5867]]]]]) + >>> aug = CenterCrop3D(2, p=1.) + >>> aug(inputs) + tensor([[[[[ 0.3223, -1.2633], + [ 1.1168, -0.2473]], + + [[-0.6136, 0.0316], + [ 0.6408, 0.4412]]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = CenterCrop3D(24, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + size: Union[int, Tuple[int, int, int]], + align_corners: bool = True, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + # same_on_batch is always True for CenterCrop + # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely. + super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim) + if isinstance(size, tuple): + self.size = (size[0], size[1], size[2]) + elif isinstance(size, int): + self.size = (size, size, size) + else: + raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.") + self.flags = {"align_corners": align_corners, "resample": Resample.get(resample)} + + def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + return rg.center_crop_generator3d( + batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device + ) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + transform: Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input)) + transform = transform.expand(input.shape[0], -1, -1) + return transform + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + transform = cast(Tensor, transform) + return crop_by_transform_mat3d( + input, transform, self.size, mode=flags["resample"].name.lower(), align_corners=flags["align_corners"] + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/crop.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/crop.py new file mode 100644 index 0000000000000000000000000000000000000000..818a5a0a702700c1d02e72058d41fd2d5ba52d1e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/crop.py @@ -0,0 +1,155 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.constants import Resample +from kornia.core import Tensor, pad +from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d + + +class RandomCrop3D(GeometricAugmentationBase3D): + r"""Apply random crop on 3D volumes (5D tensor). + + Crops random sub-volumes on a given size. + + Args: + p: probability of applying the transformation for the whole batch. + size: Desired output size (out_d, out_h, out_w) of the crop. + Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2]. + padding: Optional padding on each border of the image. + Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to pad + left, top, right, bottom, front, back borders respectively. + If a sequence of length 3 is provided, it is used to pad left/right, + top/bottom, front/back borders, respectively. + pad_if_needed: It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill: Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. + resample: resample mode from "nearest" (0) or "bilinear" (1). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, , out_d, out_h, out_w)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> inputs = torch.randn(1, 1, 3, 3, 3) + >>> aug = RandomCrop3D((2, 2, 2), p=1.) + >>> aug(inputs) + tensor([[[[[-1.1258, -1.1524], + [-0.4339, 0.8487]], + + [[-1.2633, 0.3500], + [ 0.1665, 0.8744]]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomCrop3D((24, 24, 24), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + size: Tuple[int, int, int], + padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None, + pad_if_needed: Optional[bool] = False, + fill: int = 0, + padding_mode: str = "constant", + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = True, + p: float = 1.0, + keepdim: bool = False, + ) -> None: + # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely. + super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim) + self.flags = { + "size": size, + "padding": padding, + "pad_if_needed": pad_if_needed, + "padding_mode": padding_mode, + "fill": fill, + "resample": Resample.get(resample), + "align_corners": align_corners, + } + self._param_generator = rg.CropGenerator3D(size, None) + + def precrop_padding(self, input: Tensor, flags: Optional[Dict[str, Any]] = None) -> Tensor: + flags = self.flags if flags is None else flags + padding = flags["padding"] + if padding is not None: + if isinstance(padding, int): + padding = [padding, padding, padding, padding, padding, padding] + elif isinstance(padding, (tuple, list)) and len(padding) == 3: + padding = [padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]] + elif isinstance(padding, (tuple, list)) and len(padding) == 6: + padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]] + else: + raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.") + input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"]) + + if flags["pad_if_needed"] and input.shape[-3] < flags["size"][0]: + padding = [0, 0, 0, 0, flags["size"][0] - input.shape[-3], flags["size"][0] - input.shape[-3]] + input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"]) + + if flags["pad_if_needed"] and input.shape[-2] < flags["size"][1]: + padding = [0, 0, (flags["size"][1] - input.shape[-2]), flags["size"][1] - input.shape[-2], 0, 0] + input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"]) + + if flags["pad_if_needed"] and input.shape[-1] < flags["size"][2]: + padding = [flags["size"][2] - input.shape[-1], flags["size"][2] - input.shape[-1], 0, 0, 0, 0] + input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"]) + + return input + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + transform: Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input)) + transform = transform.expand(input.shape[0], -1, -1) + return transform + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}") + + return crop_by_transform_mat3d( + input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"] + ) + + def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor: + # TODO: need to align 2D implementations + input = self.precrop_padding(input) + return super().forward(input, params) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/depthical_flip.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/depthical_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..50821127f088881c375a33b376736b66c81a014e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/depthical_flip.py @@ -0,0 +1,91 @@ +# 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. +# + +from typing import Any, Dict, Optional + +import torch +from torch import Tensor + +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D + + +class RandomDepthicalFlip3D(GeometricAugmentationBase3D): + r"""Apply random flip along the depth axis of 3D volumes (5D tensor). + + Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`. + If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second, + the corresponding transformation matrix that has been applied to them. In this case the module + will Depthically flip the tensors and concatenate the corresponding transformation matrix to the + previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module. + + Args: + p: probability of the image being flipped. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> x = torch.eye(3).repeat(3, 1, 1) + >>> seq = RandomDepthicalFlip3D(p=1.0) + >>> seq(x), seq.transform_matrix + (tensor([[[[[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]], + + [[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]], + + [[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]]]]), tensor([[[ 1., 0., 0., 0.], + [ 0., 1., 0., 0.], + [ 0., 0., -1., 2.], + [ 0., 0., 0., 1.]]])) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomDepthicalFlip3D(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + d: int = input.shape[-3] + flip_mat: Tensor = torch.tensor( + [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype + ) + return flip_mat.expand(input.shape[0], 4, 4) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return torch.flip(input, [-3]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/horizontal_flip.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/horizontal_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..2498982efd3187feb84b2afd885db23a162e9828 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/horizontal_flip.py @@ -0,0 +1,85 @@ +# 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. +# + +from typing import Any, Dict, Optional + +import torch +from torch import Tensor + +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D + + +class RandomHorizontalFlip3D(GeometricAugmentationBase3D): + r"""Apply random horizontal flip to 3D volumes (5D tensor). + + Args: + p: probability of the image being flipped. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> x = torch.eye(3).repeat(3, 1, 1) + >>> seq = RandomHorizontalFlip3D(p=1.0) + >>> seq(x), seq.transform_matrix + (tensor([[[[[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]], + + [[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]], + + [[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]]]]]), tensor([[[-1., 0., 0., 2.], + [ 0., 1., 0., 0.], + [ 0., 0., 1., 0.], + [ 0., 0., 0., 1.]]])) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomHorizontalFlip3D(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + w: int = input.shape[-1] + flip_mat: Tensor = torch.tensor( + [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype + ) + return flip_mat.expand(input.shape[0], 4, 4) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return torch.flip(input, [-1]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/perspective.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/perspective.py new file mode 100644 index 0000000000000000000000000000000000000000..e46d08c08a44f454697789bba9c4856be82c61f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/perspective.py @@ -0,0 +1,112 @@ +# 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. +# + +from typing import Any, Dict, Optional, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry import get_perspective_transform3d, warp_perspective3d + + +class RandomPerspective3D(GeometricAugmentationBase3D): + r"""Apply andom perspective transformation to 3D volumes (5D tensor). + + Args: + p: probability of the image being perspectively transformed. + distortion_scale: it controls the degree of distortion and ranges from 0 to 1. + resample: resample mode from "nearest" (0) or "bilinear" (1). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> inputs= torch.tensor([[[ + ... [[1., 0., 0.], + ... [0., 1., 0.], + ... [0., 0., 1.]], + ... [[1., 0., 0.], + ... [0., 1., 0.], + ... [0., 0., 1.]], + ... [[1., 0., 0.], + ... [0., 1., 0.], + ... [0., 0., 1.]] + ... ]]]) + >>> aug = RandomPerspective3D(0.5, p=1., align_corners=True) + >>> aug(inputs) + tensor([[[[[0.3976, 0.5507, 0.0000], + [0.0901, 0.3668, 0.0000], + [0.0000, 0.0000, 0.0000]], + + [[0.2651, 0.4657, 0.0000], + [0.1390, 0.5174, 0.0000], + [0.0000, 0.0000, 0.0000]], + + [[0.0000, 0.1153, 0.0000], + [0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000]]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomPerspective3D(0.5, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + distortion_scale: Union[Tensor, float] = 0.5, + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.flags = {"resample": Resample.get(resample), "align_corners": align_corners} + self._param_generator = rg.PerspectiveGenerator3D(distortion_scale) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}") + + return warp_perspective3d( + input, + transform, + (input.shape[-3], input.shape[-2], input.shape[-1]), + flags=flags["resample"].name.lower(), + align_corners=flags["align_corners"], + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/rotation.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..3f26334962dae58bc80dc3ef264a43597203daf4 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/rotation.py @@ -0,0 +1,131 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +import kornia +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.constants import Resample +from kornia.core import Tensor +from kornia.geometry import affine3d +from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d + + +class RandomRotation3D(GeometricAugmentationBase3D): + r"""Apply random rotations to 3D volumes (5D tensor). + + Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`. + If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second, + the corresponding transformation matrix that has been applied to them. In this case the module + will rotate the tensors and concatenate the corresponding transformation matrix to the + previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module. + + Args: + degrees: Range of degrees to select from. + If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees). + If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). + If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) + and (-c, c). + If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from + (a, b), (m, n) and (x, y). + Set to 0 to deactivate rotations. + resample: resample mode from "nearest" (0) or "bilinear" (1). + same_on_batch: apply the same transformation across the batch. + align_corners: interpolation flag. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3, 3) + >>> aug = RandomRotation3D((15., 20., 20.), p=1.0) + >>> aug(input), aug.transform_matrix + (tensor([[[[[0.3819, 0.4886, 0.2111], + [0.1196, 0.3833, 0.4722], + [0.3432, 0.5951, 0.4223]], + + [[0.5553, 0.4374, 0.2780], + [0.2423, 0.1689, 0.4009], + [0.4516, 0.6376, 0.7327]], + + [[0.1605, 0.3112, 0.3673], + [0.4931, 0.4620, 0.5700], + [0.3505, 0.4685, 0.8092]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196], + [-0.0603, 0.9669, 0.2478, -0.1545], + [ 0.2262, -0.2286, 0.9469, 0.0556], + [ 0.0000, 0.0000, 0.0000, 1.0000]]])) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomRotation3D((15., 20., 20.), p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + degrees: Union[ + Tensor, + float, + Tuple[float, float, float], + Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]], + ], + resample: Union[str, int, Resample] = Resample.BILINEAR.name, + same_on_batch: bool = False, + align_corners: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + self.flags = {"resample": Resample.get(resample), "align_corners": align_corners} + self._param_generator = rg.RotationGenerator3D(degrees) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + yaw: Tensor = params["yaw"].to(input) + pitch: Tensor = params["pitch"].to(input) + roll: Tensor = params["roll"].to(input) + + center: Tensor = _compute_tensor_center3d(input) + rotation_mat: Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1)) + + # rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix + trans_mat: Tensor = kornia.eye_like(4, input) + trans_mat[:, 0] = rotation_mat[:, 0] + trans_mat[:, 1] = rotation_mat[:, 1] + trans_mat[:, 2] = rotation_mat[:, 2] + + return trans_mat + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + if not isinstance(transform, Tensor): + raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}") + + return affine3d(input, transform[..., :3, :4], flags["resample"].name.lower(), "zeros", flags["align_corners"]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/vertical_flip.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/vertical_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..c952678df2e6e52d8e2982d983ccae4a12cb2748 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/geometric/vertical_flip.py @@ -0,0 +1,91 @@ +# 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. +# + +from typing import Any, Dict, Optional + +import torch +from torch import Tensor + +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D + + +class RandomVerticalFlip3D(GeometricAugmentationBase3D): + r"""Apply random vertical flip to 3D volumes (5D tensor). + + Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`. + If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second, + the corresponding transformation matrix that has been applied to them. In this case the module + will Vertically flip the tensors and concatenate the corresponding transformation matrix to the + previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module. + + Args: + p: probability of the image being flipped. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> x = torch.eye(3).repeat(3, 1, 1) + >>> seq = RandomVerticalFlip3D(p=1.0) + >>> seq(x), seq.transform_matrix + (tensor([[[[[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]], + + [[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]], + + [[0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]]]]]), tensor([[[ 1., 0., 0., 0.], + [ 0., -1., 0., 2.], + [ 0., 0., 1., 0.], + [ 0., 0., 0., 1.]]])) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomVerticalFlip3D(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + h: int = input.shape[-2] + flip_mat: Tensor = torch.tensor( + [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype + ) + return flip_mat.expand(input.shape[0], 4, 4) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return torch.flip(input, [-2]) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11edb47cd9a88c2b2f90bfd8136ba4b14aface2d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from kornia.augmentation._3d.intensity.equalize import RandomEqualize3D +from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3D diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/base.py new file mode 100644 index 0000000000000000000000000000000000000000..fe26ec1599b3469f6e029a41a59efd21724595f8 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/base.py @@ -0,0 +1,22 @@ +# 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. +# + +from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D + + +class IntensityAugmentationBase3D(RigidAffineAugmentationBase3D): + pass diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/equalize.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/equalize.py new file mode 100644 index 0000000000000000000000000000000000000000..c82747cc5f01ca0c81b8524a08bec44adf862d5c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/equalize.py @@ -0,0 +1,79 @@ +# 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. +# + +from typing import Any, Dict, Optional + +from torch import Tensor + +from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D +from kornia.enhance import equalize3d + + +class RandomEqualize3D(IntensityAugmentationBase3D): + r"""Apply random equalization to 3D volumes (5D tensor). + + Args: + p: probability of the image being equalized. + same_on_batch): apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 3, 3) + >>> aug = RandomEqualize3D(p=1.0) + >>> aug(input) + tensor([[[[[0.4963, 0.7682, 0.0885], + [0.1320, 0.3074, 0.6341], + [0.4901, 0.8964, 0.4556]], + + [[0.6323, 0.3489, 0.4017], + [0.0223, 0.1689, 0.2939], + [0.5185, 0.6977, 0.8000]], + + [[0.1610, 0.2823, 0.6816], + [0.9152, 0.3971, 0.8742], + [0.4194, 0.5529, 0.9527]]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomEqualize3D(p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__(self, p: float = 0.5, same_on_batch: bool = False, keepdim: bool = False) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return self.identity_matrix(input) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + return equalize3d(input) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/motion_blur.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/motion_blur.py new file mode 100644 index 0000000000000000000000000000000000000000..52eb49321b85815244500e87d0d9379bfca8de26 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/intensity/motion_blur.py @@ -0,0 +1,131 @@ +# 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. +# + +from typing import Any, Dict, Optional, Tuple, Union + +from kornia.augmentation import random_generator as rg +from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D +from kornia.constants import BorderType, Resample +from kornia.core import Tensor +from kornia.filters import motion_blur3d + + +class RandomMotionBlur3D(IntensityAugmentationBase3D): + r"""Apply random motion blur on 3D volumes (5D tensor). + + Args: + p: probability of applying the transformation. + kernel_size: motion kernel size (odd and positive). + If int, the kernel will have a fixed size. + If Tuple[int, int], it will randomly generate the value from the range batch-wisely. + angle: Range of degrees to select from. + If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle). + If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max). + If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b) + and (-c, c). + If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from + (a, b), (m, n) and (x, y). + Set to 0 to deactivate rotations. + direction: forward/backward direction of the motion blur. + Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle), + while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a + uniformly (but still angled) motion blur. + If float, it will generate the value from (-direction, direction). + If Tuple[int, int], it will randomly generate the value from the range. + border_type: the padding mode to be applied before convolving. + CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT. + resample: resample mode from "nearest" (0) or "bilinear" (1). + keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). + + Shape: + - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)` + - Output: :math:`(B, C, D, H, W)` + + Note: + Input tensor must be float and normalized into [0, 1] for the best differentiability support. + Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the + applied transformation will be merged int to the input transformation tensor and returned. + + Examples: + >>> import torch + >>> rng = torch.manual_seed(0) + >>> input = torch.rand(1, 1, 3, 5, 5) + >>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.) + >>> motion_blur(input) + tensor([[[[[0.1654, 0.4772, 0.2004, 0.3566, 0.2613], + [0.4557, 0.3131, 0.4809, 0.2574, 0.2696], + [0.2721, 0.5998, 0.3956, 0.5363, 0.1541], + [0.3006, 0.4773, 0.6395, 0.2856, 0.3989], + [0.4491, 0.5595, 0.1836, 0.3811, 0.1398]], + + [[0.1843, 0.4240, 0.3370, 0.1231, 0.2186], + [0.4047, 0.3332, 0.1901, 0.5329, 0.3023], + [0.3070, 0.3088, 0.4807, 0.4928, 0.2590], + [0.2416, 0.4614, 0.7091, 0.5237, 0.1433], + [0.1582, 0.4577, 0.2749, 0.1369, 0.1607]], + + [[0.2733, 0.4040, 0.4396, 0.2284, 0.3319], + [0.3856, 0.6730, 0.4624, 0.3878, 0.3076], + [0.4307, 0.4217, 0.2977, 0.5086, 0.5406], + [0.3686, 0.2778, 0.5228, 0.7592, 0.6455], + [0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]]) + + To apply the exact augmenation again, you may take the advantage of the previous parameter state: + >>> input = torch.rand(1, 3, 32, 32, 32) + >>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.) + >>> (aug(input) == aug(input, params=aug._params)).all() + tensor(True) + + """ + + def __init__( + self, + kernel_size: Union[int, Tuple[int, int]], + angle: Union[ + Tensor, + float, + Tuple[float, float, float], + Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]], + ], + direction: Union[Tensor, float, Tuple[float, float]], + border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name, + resample: Union[str, int, Resample] = Resample.NEAREST.name, + same_on_batch: bool = False, + p: float = 0.5, + keepdim: bool = False, + ) -> None: + super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim) + self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)} + self._param_generator = rg.MotionBlurGenerator3D(kernel_size, angle, direction) + + def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return self.identity_matrix(input) + + def apply_transform( + self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None + ) -> Tensor: + kernel_size = int(params["ksize_factor"].unique().item()) + angle = params["angle_factor"] + direction = params["direction_factor"] + return motion_blur3d( + input, + kernel_size, + angle, + direction, + self.flags["border_type"].name.lower(), + self.flags["resample"].name.lower(), + ) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c668c4666fa7cebea40ad816d787168c7f98985 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/__init__.py @@ -0,0 +1,18 @@ +# 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. +# + +from kornia.augmentation._3d.mix.transplantation import RandomTransplantation3D diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/transplantation.py b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/transplantation.py new file mode 100644 index 0000000000000000000000000000000000000000..3f343cd16ebd7ef7096f773589107775272971b2 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/_3d/mix/transplantation.py @@ -0,0 +1,31 @@ +# 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. +# + +from kornia.augmentation._2d.mix.transplantation import RandomTransplantation +from kornia.augmentation._3d.base import AugmentationBase3D + +__all__ = ["RandomTransplantation3D"] + + +class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D): # type: ignore + """RandomTransplantation3D augmentation. + + 3D version of the :class:`kornia.augmentation.RandomTransplantation` augmentation intended to be used with + :class:`kornia.augmentation.AugmentationSequential`. The interface is identical to the 2D version. + """ + + pass diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c899e17ffe7e7f4e51f31a40a020c99f60eaf6f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/__init__.py @@ -0,0 +1,199 @@ +# 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. +# + +# Lazy loading auto module +from kornia.augmentation import auto, container +from kornia.augmentation._2d import ( + CenterCrop, + ColorJiggle, + ColorJitter, + Denormalize, + LongestMaxSize, + Normalize, + PadTo, + RandomAffine, + RandomAutoContrast, + RandomBoxBlur, + RandomBrightness, + RandomChannelDropout, + RandomChannelShuffle, + RandomClahe, + RandomContrast, + RandomCrop, + RandomCutMixV2, + RandomDissolving, + RandomElasticTransform, + RandomEqualize, + RandomErasing, + RandomFisheye, + RandomGamma, + RandomGaussianBlur, + RandomGaussianIllumination, + RandomGaussianNoise, + RandomGrayscale, + RandomHorizontalFlip, + RandomHue, + RandomInvert, + RandomJigsaw, + RandomJPEG, + RandomLinearCornerIllumination, + RandomLinearIllumination, + RandomMedianBlur, + RandomMixUpV2, + RandomMosaic, + RandomMotionBlur, + RandomPerspective, + RandomPlanckianJitter, + RandomPlasmaBrightness, + RandomPlasmaContrast, + RandomPlasmaShadow, + RandomPosterize, + RandomRain, + RandomResizedCrop, + RandomRGBShift, + RandomRotation, + RandomRotation90, + RandomSaltAndPepperNoise, + RandomSaturation, + RandomSharpness, + RandomShear, + RandomSnow, + RandomSolarize, + RandomThinPlateSpline, + RandomTranslate, + RandomTransplantation, + RandomVerticalFlip, + Resize, + SmallestMaxSize, +) +from kornia.augmentation._2d.base import AugmentationBase2D, RigidAffineAugmentationBase2D +from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D +from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D +from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2 +from kornia.augmentation._3d import ( + CenterCrop3D, + RandomAffine3D, + RandomCrop3D, + RandomDepthicalFlip3D, + RandomEqualize3D, + RandomHorizontalFlip3D, + RandomMotionBlur3D, + RandomPerspective3D, + RandomRotation3D, + RandomTransplantation3D, + RandomVerticalFlip3D, +) +from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D +from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D +from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D +from kornia.augmentation.container import ( + AugmentationSequential, + ImageSequential, + ManyToManyAugmentationDispather, + ManyToOneAugmentationDispather, + PatchSequential, + VideoSequential, +) + +__all__ = [ + "AugmentationBase2D", + "AugmentationBase3D", + "AugmentationSequential", + "CenterCrop", + "CenterCrop3D", + "ColorJiggle", + "ColorJitter", + "Denormalize", + "GeometricAugmentationBase2D", + "GeometricAugmentationBase3D", + "ImageSequential", + "IntensityAugmentationBase2D", + "IntensityAugmentationBase3D", + "LongestMaxSize", + "ManyToManyAugmentationDispather", + "ManyToOneAugmentationDispather", + "MixAugmentationBaseV2", + "Normalize", + "PadTo", + "PatchSequential", + "RandomAffine", + "RandomAffine3D", + "RandomAutoContrast", + "RandomBoxBlur", + "RandomBrightness", + "RandomChannelDropout", + "RandomChannelShuffle", + "RandomContrast", + "RandomCrop", + "RandomCrop3D", + "RandomCutMixV2", + "RandomDepthicalFlip3D", + "RandomDissolving", + "RandomElasticTransform", + "RandomEqualize", + "RandomEqualize3D", + "RandomErasing", + "RandomFisheye", + "RandomGamma", + "RandomGaussianBlur", + "RandomGaussianIllumination", + "RandomGaussianNoise", + "RandomGrayscale", + "RandomHorizontalFlip", + "RandomHorizontalFlip3D", + "RandomHue", + "RandomInvert", + "RandomJigsaw", + "RandomLinearCornerIllumination", + "RandomLinearIllumination", + "RandomMedianBlur", + "RandomMixUpV2", + "RandomMosaic", + "RandomMotionBlur", + "RandomMotionBlur3D", + "RandomPerspective", + "RandomPerspective3D", + "RandomPlanckianJitter", + "RandomPlasmaBrightness", + "RandomPlasmaContrast", + "RandomPlasmaShadow", + "RandomPosterize", + "RandomRGBShift", + "RandomRGBShift", + "RandomRain", + "RandomResizedCrop", + "RandomRotation", + "RandomRotation3D", + "RandomRotation90", + "RandomSaltAndPepperNoise", + "RandomSaturation", + "RandomSharpness", + "RandomShear", + "RandomSnow", + "RandomSolarize", + "RandomThinPlateSpline", + "RandomTranslate", + "RandomVerticalFlip", + "RandomVerticalFlip3D", + "Resize", + "RigidAffineAugmentationBase2D", + "RigidAffineAugmentationBase3D", + "SmallestMaxSize", + "VideoSequential", + "auto", + "container", +] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/auto/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/auto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb12a413e626bff85a6c040445268985cc109edc --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/auto/__init__.py @@ -0,0 +1,24 @@ +# 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. +# + +from .autoaugment import AutoAugment +from .base import PolicyAugmentBase +from .operations import PolicySequential +from .rand_augment import RandAugment +from .trivial_augment import TrivialAugment + +__all__ = ["AutoAugment", "PolicyAugmentBase", "PolicySequential", "RandAugment", "TrivialAugment"] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/auto/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/auto/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3b1f6be75c18d3591f53c3f158d20a942c5b5f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/auto/base.py @@ -0,0 +1,137 @@ +# 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. +# + +from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast + +import torch + +from kornia.augmentation.auto.operations.base import OperationBase +from kornia.augmentation.auto.operations.policy import PolicySequential +from kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn +from kornia.augmentation.container.ops import InputSequentialOps +from kornia.augmentation.container.params import ParamItem +from kornia.core import Module, Tensor +from kornia.utils import eye_like + +NUMBER = Union[float, int] +OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]] +SUBPOLICY_CONFIG = List[OP_CONFIG] + + +class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn): + """Policy-based image augmentation.""" + + def __init__(self, policy: List[SUBPOLICY_CONFIG], transformation_matrix_mode: str = "silence") -> None: + policies = self.compose_policy(policy) + super().__init__(*policies) + self._parse_transformation_matrix_mode(transformation_matrix_mode) + self._valid_ops_for_transform_computation: Tuple[Any, ...] = (PolicySequential,) + + def _update_transform_matrix_for_valid_op(self, module: PolicySequential) -> None: # type: ignore + self._transform_matrices.append(module.transform_matrix) + + def clear_state(self) -> None: + self._reset_transform_matrix_state() + return super().clear_state() + + def compose_policy(self, policy: List[SUBPOLICY_CONFIG]) -> List[PolicySequential]: + """Compose policy by the provided policy config.""" + return [self.compose_subpolicy_sequential(subpolicy) for subpolicy in policy] + + def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential: + raise NotImplementedError + + def identity_matrix(self, input: Tensor) -> Tensor: + """Return identity matrix.""" + return eye_like(3, input) + + def get_transformation_matrix( + self, + input: Tensor, + params: Optional[List[ParamItem]] = None, + recompute: bool = False, + extra_args: Optional[Dict[str, Any]] = None, + ) -> Optional[Tensor]: + """Compute the transformation matrix according to the provided parameters. + + Args: + input: the input tensor. + params: params for the sequence. + recompute: if to recompute the transformation matrix according to the params. + default: False. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + + """ + if params is None: + raise NotImplementedError("requires params to be provided.") + named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params) + + # Define as 1 for broadcasting + res_mat: Optional[Tensor] = None + for (_, module), param in zip(named_modules, params if params is not None else []): + module = cast(PolicySequential, module) + mat = module.get_transformation_matrix( + input, params=cast(Optional[List[ParamItem]], param.data), recompute=recompute, extra_args=extra_args + ) + res_mat = mat if res_mat is None else mat @ res_mat + return res_mat + + def is_intensity_only(self, params: Optional[List[ParamItem]] = None) -> bool: + named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params) + for _, module in named_modules: + module = cast(PolicySequential, module) + if not module.is_intensity_only(): + return False + return True + + def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]: + named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence() + + params: List[ParamItem] = [] + mod_param: Union[Dict[str, Tensor], List[ParamItem]] + for name, module in named_modules: + module = cast(OperationBase, module) + mod_param = module.forward_parameters(batch_shape) + param = ParamItem(name, mod_param) + params.append(param) + return params + + def transform_inputs( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + for param in params: + module = self.get_submodule(param.name) + input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + return input + + def forward( + self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + self.clear_state() + + if params is None: + inp = input + _, out_shape = self.autofill_dim(inp, dim_range=(2, 4)) + params = self.forward_parameters(out_shape) + + for param in params: + module = self.get_submodule(param.name) + input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + self._update_transform_matrix_by_module(module) + + self._params = params + return input diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/base.py new file mode 100644 index 0000000000000000000000000000000000000000..34bb67f4ec4244c89e840a0141cedb717fa39aa0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/base.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. +# + +from enum import Enum +from typing import Any, Callable, Dict, Optional, Tuple, Union + +import torch +from torch.distributions import Bernoulli, Distribution, RelaxedBernoulli + +from kornia.augmentation.random_generator import RandomGeneratorBase +from kornia.augmentation.utils import ( + _adapted_rsampling, + _adapted_sampling, + _transform_output_shape, + override_parameters, +) +from kornia.core import ImageModule as Module +from kornia.core import Tensor, tensor, zeros +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints +from kornia.utils import is_autocast_enabled + +TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]] + + +# Trick mypy into not applying contravariance rules to inputs by defining +# forward as a value, rather than a function. See also +# https://github.com/python/mypy/issues/8795 +# Based on the trick that torch.nn.Module does for the forward method +def _apply_transform_unimplemented(self: Module, *input: Any) -> Tensor: + r"""Define the computation performed at every call. + + Should be overridden by all subclasses. + """ + raise NotImplementedError(f'Module [{type(self).__name__}] is missing the required "apply_tranform" function') + + +class _BasicAugmentationBase(Module): + r"""_BasicAugmentationBase base class for customized augmentation implementations. + + Plain augmentation base class without the functionality of transformation matrix calculations. + By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``. + To change this behaviour, please use ``set_rng_device_and_dtype``. + + For automatically generating the corresponding ``__repr__`` with full customized parameters, you may need to + implement ``_param_generator`` by inheriting ``RandomGeneratorBase`` for generating random parameters and + put all static parameters inside ``self.flags``. You may take the advantage of ``PlainUniformGenerator`` to + generate simple uniform parameters with less boilerplate code. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities element-wise. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to + the batch form ``False``. + + """ + + # TODO: Hard to support. Many codes are not ONNX-friendly that contains lots of if-else blocks, etc. + # Please contribute if anyone interested. + ONNX_EXPORTABLE = False + + def __init__( + self, + p: float = 0.5, + p_batch: float = 1.0, + same_on_batch: bool = False, + keepdim: bool = False, + ) -> None: + super().__init__() + self.p = p + self.p_batch = p_batch + self.same_on_batch = same_on_batch + self.keepdim = keepdim + self._params: Dict[str, Tensor] = {} + self._p_gen: Distribution + self._p_batch_gen: Distribution + if p != 0.0 or p != 1.0: + self._p_gen = Bernoulli(self.p) + if p_batch != 0.0 or p_batch != 1.0: + self._p_batch_gen = Bernoulli(self.p_batch) + self._param_generator: Optional[RandomGeneratorBase] = None + self.flags: Dict[str, Any] = {} + self.set_rng_device_and_dtype(torch.device("cpu"), torch.get_default_dtype()) + + apply_transform: Callable[..., Tensor] = _apply_transform_unimplemented + + def to(self, *args: Any, **kwargs: Any) -> "_BasicAugmentationBase": + r"""Set the device and dtype for the random number generator.""" + device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs) + self.set_rng_device_and_dtype(device, dtype) + return super().to(*args, **kwargs) + + def __repr__(self) -> str: + txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}" + if isinstance(self._param_generator, RandomGeneratorBase): + txt = f"{self._param_generator!s}, {txt}" + for k, v in self.flags.items(): + if isinstance(v, Enum): + txt += f", {k}={v.name.lower()}" + else: + txt += f", {k}={v}" + return f"{self.__class__.__name__}({txt})" + + def __unpack_input__(self, input: Tensor) -> Tensor: + return input + + def transform_tensor( + self, + input: Tensor, + *, + shape: Optional[Tensor] = None, + match_channel: bool = True, + ) -> Tensor: + """Standardize input tensors.""" + raise NotImplementedError + + def validate_tensor(self, input: Tensor) -> None: + """Check if the input tensor is formatted as expected.""" + raise NotImplementedError + + def transform_output_tensor(self, output: Tensor, output_shape: Tuple[int, ...]) -> Tensor: + """Standardize output tensors.""" + return _transform_output_shape(output, output_shape) if self.keepdim else output + + def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + if self._param_generator is not None: + return self._param_generator(batch_shape, self.same_on_batch) + return {} + + def set_rng_device_and_dtype(self, device: torch.device, dtype: torch.dtype) -> None: + """Change the random generation device and dtype. + + Note: + The generated random numbers are not reproducible across different devices and dtypes. + + """ + self.device = device + self.dtype = dtype + if self._param_generator is not None: + self._param_generator.set_rng_device_and_dtype(device, dtype) + + def __batch_prob_generator__( + self, + batch_shape: Tuple[int, ...], + p: float, + p_batch: float, + same_on_batch: bool, + ) -> Tensor: + batch_prob: Tensor + if p_batch == 1: + batch_prob = zeros(1) + 1 + elif p_batch == 0: + batch_prob = zeros(1) + elif isinstance(self._p_batch_gen, (RelaxedBernoulli,)): + # NOTE: there is no simple way to know if the sampler has `rsample` or not + batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch) + else: + batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch) + + if batch_prob.sum() == 1: + elem_prob: Tensor + if p == 1: + elem_prob = zeros(batch_shape[0]) + 1 + elif p == 0: + elem_prob = zeros(batch_shape[0]) + elif isinstance(self._p_gen, (RelaxedBernoulli,)): + elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch) + else: + elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch) + batch_prob = batch_prob * elem_prob + else: + batch_prob = batch_prob.repeat(batch_shape[0]) + if len(batch_prob.shape) == 2: + return batch_prob[..., 0] + return batch_prob + + def _process_kwargs_to_params_and_flags( + self, + params: Optional[Dict[str, Tensor]] = None, + flags: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> Tuple[Dict[str, Tensor], Dict[str, Any]]: + # NOTE: determine how to save self._params + save_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False + + params = self._params if params is None else params + flags = self.flags if flags is None else flags + + if save_kwargs: + params = override_parameters(params, kwargs, in_place=True) + self._params = params + else: + self._params = params + params = override_parameters(params, kwargs, in_place=False) + + flags = override_parameters(flags, kwargs, in_place=False) + return params, flags + + def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]: + batch_prob = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch) + to_apply = batch_prob > 0.5 + _params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:]))) + if _params is None: + _params = {} + _params["batch_prob"] = batch_prob + # Added another input_size parameter for geometric transformations + # This might be needed for correctly inversing. + input_size = tensor(batch_shape, dtype=torch.long) + _params.update({"forward_input_shape": input_size}) + return _params + + def apply_func(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor: + return self.apply_transform(input, params, flags) + + def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor: + """Perform forward operations. + + Args: + input: the input tensor. + params: the corresponding parameters for an operation. + If None, a new parameter suite will be generated. + **kwargs: key-value pairs to override the parameters and flags. + + Note: + By default, all the overwriting parameters in kwargs will not be recorded + as in ``self._params``. If you wish it to be recorded, you may pass + ``save_kwargs=True`` additionally. + + """ + in_tensor = self.__unpack_input__(input) + input_shape = in_tensor.shape + in_tensor = self.transform_tensor(in_tensor) + batch_shape = in_tensor.shape + if params is None: + params = self.forward_parameters(batch_shape) + + if "batch_prob" not in params: + params["batch_prob"] = tensor([True] * batch_shape[0]) + + params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs) + + output = self.apply_func(in_tensor, params, flags) + return self.transform_output_tensor(output, input_shape) if self.keepdim else output + + +class _AugmentationBase(_BasicAugmentationBase): + r"""_AugmentationBase base class for customized augmentation implementations. + + Advanced augmentation base class with the functionality of transformation matrix calculations. + + Args: + p: probability for applying an augmentation. This param controls the augmentation probabilities + element-wise for a batch. + p_batch: probability for applying an augmentation to a batch. This param controls the augmentation + probabilities batch-wise. + same_on_batch: apply the same transformation across the batch. + keepdim: whether to keep the output shape the same as input ``True`` or broadcast it + to the batch form ``False``. + + """ + + def apply_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + # apply transform for the input image tensor + raise NotImplementedError + + def apply_non_transform( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + # apply additional transform for the images that are skipped from transformation + # where batch_prob == False. + return input + + def transform_inputs( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + ori_shape = input.shape + in_tensor = self.transform_tensor(input) + + self.validate_tensor(in_tensor) + if to_apply.all(): + output = self.apply_transform(in_tensor, params, flags, transform=transform) + elif not to_apply.any(): + output = self.apply_non_transform(in_tensor, params, flags, transform=transform) + else: # If any tensor needs to be transformed. + output = self.apply_non_transform(in_tensor, params, flags, transform=transform) + applied = self.apply_transform( + in_tensor[to_apply], + params, + flags, + transform=transform if transform is None else transform[to_apply], + ) + + if is_autocast_enabled(): + output = output.type(input.dtype) + applied = applied.type(input.dtype) + output = output.index_put((to_apply,), applied) + + output = _transform_output_shape(output, ori_shape) if self.keepdim else output + + if is_autocast_enabled(): + output = output.type(input.dtype) + return output + + def transform_masks( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + ori_shape = input.shape + + shape = params["forward_input_shape"] + in_tensor = self.transform_tensor(input, shape=shape, match_channel=False) + + self.validate_tensor(in_tensor) + if to_apply.all(): + output = self.apply_transform_mask(in_tensor, params, flags, transform=transform) + elif not to_apply.any(): + output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform) + else: # If any tensor needs to be transformed. + output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform) + applied = self.apply_transform_mask( + in_tensor[to_apply], + params, + flags, + transform=transform if transform is None else transform[to_apply], + ) + output = output.index_put((to_apply,), applied) + output = _transform_output_shape(output, ori_shape, reference_shape=shape) if self.keepdim else output + return output + + def transform_boxes( + self, + input: Boxes, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Boxes: + if not isinstance(input, Boxes): + raise RuntimeError(f"Only `Boxes` is supported. Got {type(input)}.") + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + output: Boxes + if to_apply.bool().all(): + output = self.apply_transform_box(input, params, flags, transform=transform) + elif not to_apply.any(): + output = self.apply_non_transform_box(input, params, flags, transform=transform) + else: # If any tensor needs to be transformed. + output = self.apply_non_transform_box(input, params, flags, transform=transform) + applied = self.apply_transform_box( + input[to_apply], + params, + flags, + transform=transform if transform is None else transform[to_apply], + ) + if is_autocast_enabled(): + output = output.type(input.dtype) + applied = applied.type(input.dtype) + + output = output.index_put((to_apply,), applied) + return output + + def transform_keypoints( + self, + input: Keypoints, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Keypoints: + if not isinstance(input, Keypoints): + raise RuntimeError(f"Only `Keypoints` is supported. Got {type(input)}.") + + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + if to_apply.all(): + output = self.apply_transform_keypoint(input, params, flags, transform=transform) + elif not to_apply.any(): + output = self.apply_non_transform_keypoint(input, params, flags, transform=transform) + else: # If any tensor needs to be transformed. + output = self.apply_non_transform_keypoint(input, params, flags, transform=transform) + applied = self.apply_transform_keypoint( + input[to_apply], + params, + flags, + transform=transform if transform is None else transform[to_apply], + ) + if is_autocast_enabled(): + output = output.type(input.dtype) + applied = applied.type(input.dtype) + output = output.index_put((to_apply,), applied) + return output + + def transform_classes( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + **kwargs: Any, + ) -> Tensor: + params, flags = self._process_kwargs_to_params_and_flags( + self._params if params is None else params, flags, **kwargs + ) + + batch_prob = params["batch_prob"] + to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions. + if to_apply.all(): + output = self.apply_transform_class(input, params, flags, transform=transform) + elif not to_apply.any(): + output = self.apply_non_transform_class(input, params, flags, transform=transform) + else: # If any tensor needs to be transformed. + output = self.apply_non_transform_class(input, params, flags, transform=transform) + applied = self.apply_transform_class( + input[to_apply], + params, + flags, + transform=transform if transform is None else transform[to_apply], + ) + output = output.index_put((to_apply,), applied) + return output + + def apply_non_transform_mask( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + """Process masks corresponding to the inputs that are no transformation applied.""" + raise NotImplementedError + + def apply_transform_mask( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + """Process masks corresponding to the inputs that are transformed.""" + raise NotImplementedError + + def apply_non_transform_box( + self, + input: Boxes, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Boxes: + """Process boxes corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_box( + self, + input: Boxes, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Boxes: + """Process boxes corresponding to the inputs that are transformed.""" + raise NotImplementedError + + def apply_non_transform_keypoint( + self, + input: Keypoints, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Keypoints: + """Process keypoints corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_keypoint( + self, + input: Keypoints, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Keypoints: + """Process keypoints corresponding to the inputs that are transformed.""" + raise NotImplementedError + + def apply_non_transform_class( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + """Process class tags corresponding to the inputs that are no transformation applied.""" + return input + + def apply_transform_class( + self, + input: Tensor, + params: Dict[str, Tensor], + flags: Dict[str, Any], + transform: Optional[Tensor] = None, + ) -> Tensor: + """Process class tags corresponding to the inputs that are transformed.""" + raise NotImplementedError + + def apply_func( + self, + in_tensor: Tensor, + params: Dict[str, Tensor], + flags: Optional[Dict[str, Any]] = None, + ) -> Tensor: + if flags is None: + flags = self.flags + + output = self.transform_inputs(in_tensor, params, flags) + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76e2dfac3aa0b082e2e64d4edbf0251a756417a6 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/__init__.py @@ -0,0 +1,23 @@ +# 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. +# + +from kornia.augmentation.container.augment import AugmentationSequential +from kornia.augmentation.container.base import ImageSequentialBase +from kornia.augmentation.container.dispatcher import ManyToManyAugmentationDispather, ManyToOneAugmentationDispather +from kornia.augmentation.container.image import ImageSequential +from kornia.augmentation.container.patch import PatchSequential +from kornia.augmentation.container.video import VideoSequential diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/augment.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/augment.py new file mode 100644 index 0000000000000000000000000000000000000000..d16f7729823eaf3ea4b8c88518f1c6f63ca81290 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/augment.py @@ -0,0 +1,678 @@ +# 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. +# + +import warnings +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast + +import torch + +from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D +from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D +from kornia.augmentation.base import _AugmentationBase +from kornia.constants import DataKey, Resample +from kornia.core import Module, Tensor +from kornia.geometry.boxes import Boxes, VideoBoxes +from kornia.geometry.keypoints import Keypoints, VideoKeypoints +from kornia.utils import eye_like, is_autocast_enabled + +from .base import TransformMatrixMinIn +from .image import ImageSequential +from .ops import AugmentationSequentialOps, DataType +from .params import ParamItem +from .patch import PatchSequential +from .video import VideoSequential + +__all__ = ["AugmentationSequential"] + +_BOXES_OPTIONS = {DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH} +_KEYPOINTS_OPTIONS = {DataKey.KEYPOINTS} +_IMG_OPTIONS = {DataKey.INPUT, DataKey.IMAGE} +_MSK_OPTIONS = {DataKey.MASK} +_CLS_OPTIONS = {DataKey.CLASS, DataKey.LABEL} + +MaskDataType = Union[Tensor, List[Tensor]] + + +class AugmentationSequential(TransformMatrixMinIn, ImageSequential): + r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once. + + .. image:: _static/img/AugmentationSequential.png + + Args: + *args: a list of kornia augmentation modules. + + data_keys: the input type sequential for applying augmentations. Accepts "input", "image", "mask", + "bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "class", "label". + + same_on_batch: apply the same transformation across the batch. If None, it will not overwrite the function-wise + settings. + + keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). + If None, it will not overwrite the function-wise settings. + + random_apply: randomly select a sublist (order agnostic) of args to apply transformation. + If int, a fixed number of transformations will be selected. + If (a,), x number of transformations (a <= x <= len(args)) will be selected. + If (a, b), x number of transformations (a <= x <= b) will be selected. + If True, the whole list of args will be processed as a sequence in a random order. + If False, the whole list of args will be processed as a sequence in original order. + + transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix` + attribute. + If `silent`, transformation matrix will be computed silently and the non-rigid + modules will be ignored as identity transformations. + If `rigid`, transformation matrix will be computed silently and the non-rigid + modules will trigger errors. + If `skip`, transformation matrix will be totally ignored. + + extra_args: to control the behaviour for each datakeys. By default, masks are handled by nearest interpolation + strategies. + + .. note:: + Mix augmentations (e.g. RandomMixUp, RandomCutMix) can only be working with "input"/"image" data key. + It is not clear how to deal with the conversions of masks, bounding boxes and keypoints. + + .. note:: + See a working example `here `__. + + Examples: + >>> import kornia + >>> input = torch.randn(2, 3, 5, 6) + >>> mask = torch.ones(2, 3, 5, 6) + >>> bbox = torch.tensor([[ + ... [1., 1.], + ... [2., 1.], + ... [2., 2.], + ... [1., 2.], + ... ]]).expand(2, 1, -1, -1) + >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1) + >>> aug_list = AugmentationSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... data_keys=["input", "mask", "bbox", "keypoints"], + ... same_on_batch=False, + ... random_apply=10, + ... ) + >>> out = aug_list(input, mask, bbox, points) + >>> [o.shape for o in out] + [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 1, 4, 2]), torch.Size([2, 1, 2])] + >>> # apply the exact augmentation again. + >>> out_rep = aug_list(input, mask, bbox, points, params=aug_list._params) + >>> [(o == o_rep).all() for o, o_rep in zip(out, out_rep)] + [tensor(True), tensor(True), tensor(True), tensor(True)] + >>> # inverse the augmentations + >>> out_inv = aug_list.inverse(*out) + >>> [o.shape for o in out_inv] + [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 1, 4, 2]), torch.Size([2, 1, 2])] + + This example demonstrates the integration of VideoSequential and AugmentationSequential. + + >>> import kornia + >>> input = torch.randn(2, 3, 5, 6)[None] + >>> mask = torch.ones(2, 3, 5, 6)[None] + >>> bbox = torch.tensor([[ + ... [1., 1.], + ... [2., 1.], + ... [2., 2.], + ... [1., 2.], + ... ]]).expand(2, 1, -1, -1)[None] + >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None] + >>> aug_list = AugmentationSequential( + ... VideoSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... ), + ... data_keys=["input", "mask", "bbox", "keypoints"] + ... ) + >>> out = aug_list(input, mask, bbox, points) + >>> [o.shape for o in out] # doctest: +ELLIPSIS + [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])] + + Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` + in ``AugmentationSequential``. + + >>> import kornia + >>> input = torch.randn(2, 3, 5, 6)[None] + >>> mask = torch.ones(2, 3, 5, 6)[None] + >>> bbox = torch.tensor([[ + ... [1., 1.], + ... [2., 1.], + ... [2., 2.], + ... [1., 2.], + ... ]]).expand(2, 1, -1, -1)[None] + >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None] + >>> aug_list = AugmentationSequential( + ... VideoSequential( + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... ), + ... VideoSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... ), + ... data_keys=["input", "mask", "bbox", "keypoints"], + ... random_apply=1, + ... random_apply_weights=[0.5, 0.3] + ... ) + >>> out = aug_list(input, mask, bbox, points) + >>> [o.shape for o in out] # doctest: +ELLIPSIS + [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])] + + This example shows how to use a list of masks and boxes within AugmentationSequential + + >>> import kornia.augmentation as K + >>> input = torch.randn(2, 3, 256, 256) + >>> mask = [torch.ones(1, 3, 256, 256), torch.ones(1, 2, 256, 256)] + >>> bbox = [ + ... torch.tensor([[28.0, 53.0, 143.0, 164.0], [254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]), + ... torch.tensor([[254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]) + ... ] + >>> bbox = [Boxes.from_tensor(i).data for i in bbox] + + >>> aug_list = K.AugmentationSequential( + ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... K.RandomHorizontalFlip(p=1.0), + ... K.ImageSequential(K.RandomHorizontalFlip(p=1.0)), + ... K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)), + ... data_keys=["input", "mask", "bbox"], + ... same_on_batch=False, + ... random_apply=10, + ... ) + >>> out = aug_list(input, mask, bbox) + + How to use a dictionary as input with AugmentationSequential? The dictionary keys that start with + one of the available datakeys will be augmented accordingly. Otherwise, the dictionary item is passed + without any augmentation. + + >>> import kornia.augmentation as K + >>> img = torch.randn(1, 3, 256, 256) + >>> mask = [torch.ones(1, 3, 256, 256), torch.ones(1, 2, 256, 256)] + >>> bbox = [ + ... torch.tensor([[28.0, 53.0, 143.0, 164.0], [254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]), + ... torch.tensor([[254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]) + ... ] + >>> bbox = [Boxes.from_tensor(i).data for i in bbox] + >>> aug_dict = K.AugmentationSequential( + ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... K.RandomHorizontalFlip(p=1.0), + ... K.ImageSequential(K.RandomHorizontalFlip(p=1.0)), + ... K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)), + ... data_keys=None, + ... same_on_batch=False, + ... random_apply=10, + ... ) + >>> data = {'image': img, 'mask': mask[0], 'mask-b': mask[1], 'bbox': bbox[0], 'bbox-other':bbox[1]} + >>> out = aug_dict(data) + >>> out.keys() + dict_keys(['image', 'mask', 'mask-b', 'bbox', 'bbox-other']) + + """ + + input_dtype = None + mask_dtype = None + + def __init__( + self, + *args: Union[_AugmentationBase, ImageSequential], + data_keys: Optional[Union[Sequence[str], Sequence[int], Sequence[DataKey]]] = (DataKey.INPUT,), + same_on_batch: Optional[bool] = None, + keepdim: Optional[bool] = None, + random_apply: Union[int, bool, Tuple[int, int]] = False, + random_apply_weights: Optional[List[float]] = None, + transformation_matrix_mode: str = "silent", + extra_args: Optional[Dict[DataKey, Dict[str, Any]]] = None, + ) -> None: + self._transform_matrix: Optional[Tensor] + self._transform_matrices: List[Optional[Tensor]] = [] + + super().__init__( + *args, + same_on_batch=same_on_batch, + keepdim=keepdim, + random_apply=random_apply, + random_apply_weights=random_apply_weights, + ) + + self._parse_transformation_matrix_mode(transformation_matrix_mode) + + self._valid_ops_for_transform_computation: Tuple[Any, ...] = ( + RigidAffineAugmentationBase2D, + RigidAffineAugmentationBase3D, + AugmentationSequential, + ) + + self.data_keys: Optional[List[DataKey]] + if data_keys is not None: + self.data_keys = [DataKey.get(inp) for inp in data_keys] + else: + self.data_keys = data_keys + + if self.data_keys: + if any(in_type not in DataKey for in_type in self.data_keys): + raise AssertionError(f"`data_keys` must be in {DataKey}. Got {self.data_keys}.") + + if self.data_keys[0] != DataKey.INPUT: + raise NotImplementedError(f"The first input must be {DataKey.INPUT}.") + + self.transform_op = AugmentationSequentialOps(self.data_keys) + + self.contains_video_sequential: bool = False + self.contains_3d_augmentation: bool = False + for arg in args: + if isinstance(arg, PatchSequential) and not arg.is_intensity_only(): + warnings.warn( + "Geometric transformation detected in PatchSeqeuntial, which would break bbox, mask.", stacklevel=1 + ) + if isinstance(arg, VideoSequential): + self.contains_video_sequential = True + # NOTE: only for images are supported for 3D. + if isinstance(arg, AugmentationBase3D): + self.contains_3d_augmentation = True + self._transform_matrix = None + self.extra_args = extra_args or {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}} + + def clear_state(self) -> None: + self._reset_transform_matrix_state() + return super().clear_state() + + def _update_transform_matrix_for_valid_op(self, module: Module) -> None: + self._transform_matrices.append(module.transform_matrix) + + def identity_matrix(self, input: Tensor) -> Tensor: + """Return identity matrix.""" + if self.contains_3d_augmentation: + return eye_like(4, input) + else: + return eye_like(3, input) + + def inverse( # type: ignore[override] + self, + *args: Union[DataType, Dict[str, DataType]], + params: Optional[List[ParamItem]] = None, + data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None, + ) -> Union[DataType, List[DataType], Dict[str, DataType]]: + """Reverse the transformation applied. + + Number of input tensors must align with the number of``data_keys``. If ``data_keys`` is not set, use + ``self.data_keys`` by default. + """ + original_keys = None + if len(args) == 1 and isinstance(args[0], dict): + original_keys, data_keys, args, invalid_data = self._preproc_dict_data(args[0]) + + # args here should already be `DataType` + # NOTE: how to right type to: unpacked args <-> tuple of args to unpack + # issue with `self._preproc_dict_data` return args type + + self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys) + + self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys) # type: ignore + + in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore + + if params is None: + if self._params is None: + raise ValueError( + "No parameters available for inversing, please run a forward pass first " + "or passing valid params into this function." + ) + params = self._params + + outputs: List[DataType] = in_args + for param in params[::-1]: + module = self.get_submodule(param.name) + outputs = self.transform_op.inverse( # type: ignore + *outputs, module=module, param=param, extra_args=self.extra_args + ) + if not isinstance(outputs, (list, tuple)): + # Make sure we are unpacking a list whilst post-proc + outputs = [outputs] + + outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore + + if isinstance(original_keys, tuple): + result = {k: v for v, k in zip(outputs, original_keys)} + if invalid_data: + result.update(invalid_data) + return result + + if len(outputs) == 1 and isinstance(outputs, list): + return outputs[0] + + return outputs + + def _validate_args_datakeys(self, *args: DataType, data_keys: List[DataKey]) -> None: + if len(args) != len(data_keys): + raise AssertionError( + f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}." + ) + # TODO: validate args batching, and its consistency + + def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]: + inp: List[DataType] = [] + for arg, dcate in zip(args, data_keys): + if DataKey.get(dcate) in _IMG_OPTIONS: + arg = cast(Tensor, arg) + self.input_dtype = arg.dtype + inp.append(arg) + elif DataKey.get(dcate) in _MSK_OPTIONS: + if isinstance(inp, list): + arg = cast(List[Tensor], arg) + self.mask_dtype = arg[0].dtype + else: + arg = cast(Tensor, arg) + self.mask_dtype = arg.dtype + inp.append(self._preproc_mask(arg)) + elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS: + inp.append(self._preproc_keypoints(arg, dcate)) + elif DataKey.get(dcate) in _BOXES_OPTIONS: + inp.append(self._preproc_boxes(arg, dcate)) + elif DataKey.get(dcate) in _CLS_OPTIONS: + inp.append(arg) + else: + raise NotImplementedError(f"input type of {dcate} is not implemented.") + return inp + + def _arguments_postproc( + self, in_args: List[DataType], out_args: List[DataType], data_keys: List[DataKey] + ) -> List[DataType]: + out: List[DataType] = [] + for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys): + if DataKey.get(dcate) in _IMG_OPTIONS: + # It is tensor type already. + out.append(out_arg) + # TODO: may add the float to integer (for masks), etc. + elif DataKey.get(dcate) in _MSK_OPTIONS: + _out_m = self._postproc_mask(cast(MaskDataType, out_arg)) + out.append(_out_m) + + elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS: + _out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate) + if is_autocast_enabled() and isinstance(in_arg, (Tensor, Keypoints)): + if isinstance(_out_k, list): + _out_k = [i.type(in_arg.dtype) for i in _out_k] + else: + _out_k = _out_k.type(in_arg.dtype) + out.append(_out_k) + + elif DataKey.get(dcate) in _BOXES_OPTIONS: + _out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate) + if is_autocast_enabled() and isinstance(in_arg, (Tensor, Boxes)): + if isinstance(_out_b, list): + _out_b = [i.type(in_arg.dtype) for i in _out_b] + else: + _out_b = _out_b.type(in_arg.dtype) + out.append(_out_b) + + elif DataKey.get(dcate) in _CLS_OPTIONS: + out.append(out_arg) + + else: + raise NotImplementedError(f"input type of {dcate} is not implemented.") + + return out + + def forward( # type: ignore[override] + self, + *args: Union[DataType, Dict[str, DataType]], + params: Optional[List[ParamItem]] = None, + data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None, + ) -> Union[DataType, List[DataType], Dict[str, DataType]]: + """Compute multiple tensors simultaneously according to ``self.data_keys``.""" + self.clear_state() + + # Unpack/handle dictionary args + original_keys = None + if len(args) == 1 and isinstance(args[0], dict): + original_keys, data_keys, args, invalid_data = self._preproc_dict_data(args[0]) + + self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys) + + self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys) # type: ignore + + in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore + + if params is None: + # image data must exist if params is not provided. + if DataKey.INPUT in self.transform_op.data_keys: + inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)] + if not isinstance(inp, (Tensor,)): + raise ValueError(f"`INPUT` should be a tensor but `{type(inp)}` received.") + # A video input shall be BCDHW while an image input shall be BCHW + if self.contains_video_sequential or self.contains_3d_augmentation: + _, out_shape = self.autofill_dim(inp, dim_range=(3, 5)) + else: + _, out_shape = self.autofill_dim(inp, dim_range=(2, 4)) + params = self.forward_parameters(out_shape) + else: + raise ValueError("`params` must be provided whilst INPUT is not in data_keys.") + + outputs: Union[Tensor, List[DataType]] = in_args + for param in params: + module = self.get_submodule(param.name) + outputs = self.transform_op.transform( # type: ignore + *outputs, module=module, param=param, extra_args=self.extra_args + ) + if not isinstance(outputs, (list, tuple)): + # Make sure we are unpacking a list whilst post-proc + outputs = [outputs] + self._update_transform_matrix_by_module(module) + + outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore + # Restore it back + self.transform_op.data_keys = self.data_keys + + self._params = params + + if isinstance(original_keys, tuple): + result = {k: v for v, k in zip(outputs, original_keys)} + if invalid_data: + result.update(invalid_data) + return result + + if len(outputs) == 1 and isinstance(outputs, list): + return outputs[0] + + return outputs + + def __call__( + self, + *inputs: Any, + input_names_to_handle: Optional[List[Any]] = None, + output_type: str = "tensor", + **kwargs: Any, + ) -> Any: + """Overwrite the __call__ function to handle various inputs. + + Args: + inputs: Inputs to operate on. + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + kwargs: Additional arguments. + + Returns: + Callable: Decorated function with converted input and output types. + + """ + # Wrap the forward method with the decorator + if not self._disable_features: + # TODO: Some more behaviour for AugmentationSequential needs to be revisited later + # e.g. We convert only images, etc. + decorated_forward = self.convert_input_output( + input_names_to_handle=input_names_to_handle, output_type=output_type + )(super(ImageSequential, self).__call__) + _output_image = decorated_forward(*inputs, **kwargs) + + if len(inputs) == 1 and isinstance(inputs[0], dict): + original_keys, in_data_keys, inputs, invalid_data = self._preproc_dict_data(inputs[0]) + else: + in_data_keys = kwargs.get("data_keys", self.data_keys) + data_keys = self.transform_op.preproc_datakeys(in_data_keys) + + if len(data_keys) > 1 and DataKey.INPUT in data_keys: + # NOTE: we may update it later for more supports of drawing boxes, etc. + idx = data_keys.index(DataKey.INPUT) + if output_type == "tensor": + self._output_image = _output_image + if isinstance(_output_image, dict): + self._output_image[original_keys[idx]] = _output_image[original_keys[idx]] + else: + self._output_image[idx] = _output_image[idx] + elif isinstance(_output_image, dict): + self._output_image[original_keys[idx]] = _output_image[original_keys[idx]] + else: + self._output_image[idx] = _output_image[idx] + else: + self._output_image = _output_image + else: + _output_image = super(ImageSequential, self).__call__(*inputs, **kwargs) + return _output_image + + def _preproc_dict_data( + self, data: Dict[str, DataType] + ) -> Tuple[Tuple[str, ...], List[DataKey], Tuple[DataType, ...], Optional[Dict[str, Any]]]: + if self.data_keys is not None: + raise ValueError("If you are using a dictionary as input, the data_keys should be None.") + + keys = tuple(data.keys()) + data_keys, invalid_keys = self._read_datakeys_from_dict(keys) + invalid_data = {i: data.pop(i) for i in invalid_keys} if invalid_keys else None + keys = tuple(k for k in keys if k not in invalid_keys) if invalid_keys else keys + data_unpacked = tuple(data.values()) + + return keys, data_keys, data_unpacked, invalid_data + + def _read_datakeys_from_dict(self, keys: Sequence[str]) -> Tuple[List[DataKey], Optional[List[str]]]: + def retrieve_key(key: str) -> DataKey: + """Try to retrieve the datakey value by matching `*`.""" + # Alias cases, like INPUT, will not be get by the enum iterator. + if key.upper().startswith("INPUT"): + return DataKey.INPUT + + for dk in DataKey: + if key.upper() in {"BBOX_XYXY", "BBOX_XYWH"}: + return DataKey.get(key.upper()) + if key.upper().startswith(dk.name): + return DataKey.get(dk.name) + + allowed_dk = " | ".join(f"`{d.name}`" for d in DataKey) + raise ValueError( + f"Your input data dictionary keys should start with some of datakey values: {allowed_dk}. Got `{key}`" + ) + + valid_data_keys = [] + invalid_keys = [] + for k in keys: + try: + valid_data_keys.append(DataKey.get(retrieve_key(k))) + except ValueError: + invalid_keys.append(k) + + return valid_data_keys, invalid_keys + + def _preproc_mask(self, arg: MaskDataType) -> MaskDataType: + if isinstance(arg, list): + new_arg = [] + for a in arg: + a_new = a.to(self.input_dtype) if self.input_dtype else a.to(torch.float) + new_arg.append(a_new) + return new_arg + + else: + arg = arg.to(self.input_dtype) if self.input_dtype else arg.to(torch.float) + return arg + + def _postproc_mask(self, arg: MaskDataType) -> MaskDataType: + if isinstance(arg, list): + new_arg = [] + for a in arg: + a_new = a.to(self.mask_dtype) if self.mask_dtype else a.to(torch.float) + new_arg.append(a_new) + return new_arg + + else: + arg = arg.to(self.mask_dtype) if self.mask_dtype else arg.to(torch.float) + return arg + + def _preproc_boxes(self, arg: DataType, dcate: DataKey) -> Boxes: + if DataKey.get(dcate) in [DataKey.BBOX]: + mode = "vertices_plus" + elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]: + mode = "xyxy_plus" + elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]: + mode = "xywh" + else: + raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.") + if isinstance(arg, (Boxes,)): + return arg + elif self.contains_video_sequential: + arg = cast(Tensor, arg) + return VideoBoxes.from_tensor(arg) + elif self.contains_3d_augmentation: + raise NotImplementedError("3D box handlers are not yet supported.") + else: + arg = cast(Tensor, arg) + return Boxes.from_tensor(arg, mode=mode) + + def _postproc_boxes(self, in_arg: DataType, out_arg: Boxes, dcate: DataKey) -> Union[Tensor, List[Tensor], Boxes]: + if DataKey.get(dcate) in [DataKey.BBOX]: + mode = "vertices_plus" + elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]: + mode = "xyxy_plus" + elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]: + mode = "xywh" + else: + raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.") + + # TODO: handle 3d scenarios + if isinstance(in_arg, (Boxes,)): + return out_arg + else: + return out_arg.to_tensor(mode=mode) + + def _preproc_keypoints(self, arg: DataType, dcate: DataKey) -> Keypoints: + dtype = None + + if self.contains_video_sequential: + arg = cast(Union[Tensor, List[Tensor]], arg) + if isinstance(arg, list): + if not torch.is_floating_point(arg[0]): + dtype = arg[0].dtype + arg = [a.float() for a in arg] + elif not torch.is_floating_point(arg): + dtype = arg.dtype + arg = arg.float() + video_result = VideoKeypoints.from_tensor(arg) + return video_result.type(dtype) if dtype else video_result + elif self.contains_3d_augmentation: + raise NotImplementedError("3D keypoint handlers are not yet supported.") + elif isinstance(arg, (Keypoints,)): + return arg + else: + arg = cast(Tensor, arg) + if not torch.is_floating_point(arg): + dtype = arg.dtype + arg = arg.float() + # TODO: Add List[Tensor] in the future. + result = Keypoints.from_tensor(arg) + return result.type(dtype) if dtype else result + + def _postproc_keypoint( + self, in_arg: DataType, out_arg: Keypoints, dcate: DataKey + ) -> Union[Tensor, List[Tensor], Keypoints]: + if isinstance(in_arg, (Keypoints,)): + return out_arg + else: + return out_arg.to_tensor() diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/base.py new file mode 100644 index 0000000000000000000000000000000000000000..43595827ac6cc78ea4d45afa15d5836bde6c054a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/base.py @@ -0,0 +1,364 @@ +# 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. +# + +from collections import OrderedDict +from itertools import zip_longest +from typing import Any, Dict, Iterator, List, Optional, Tuple + +import torch +from torch import nn + +import kornia.augmentation as K +from kornia.augmentation.base import _AugmentationBase +from kornia.core import Module, Tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + +from .ops import BoxSequentialOps, InputSequentialOps, KeypointSequentialOps, MaskSequentialOps +from .params import ParamItem + +__all__ = ["BasicSequentialBase", "ImageSequentialBase", "SequentialBase"] + + +class BasicSequentialBase(nn.Sequential): + r"""BasicSequential for creating kornia modulized processing pipeline. + + Args: + *args : a list of kornia augmentation and image operation modules. + + """ + + def __init__(self, *args: Module) -> None: + # To name the modules properly + _args = OrderedDict() + for idx, mod in enumerate(args): + if not isinstance(mod, Module): + raise NotImplementedError(f"Only Module are supported at this moment. Got {mod}.") + _args.update({f"{mod.__class__.__name__}_{idx}": mod}) + super().__init__(_args) + self._params: Optional[List[ParamItem]] = None + + def get_submodule(self, target: str) -> Module: + """Get submodule. + + This code is taken from torch 1.9.0 since it is not introduced + back to torch 1.7.1. We included this for maintaining more + backward torch versions. + + Args: + target: The fully-qualified string name of the submodule + to look for. (See above example for how to specify a + fully-qualified string.) + + Returns: + Module: The submodule referenced by ``target`` + + Raises: + AttributeError: If the target string references an invalid + path or resolves to something that is not an + ``Module`` + + """ + if len(target) == 0: + return self + + atoms: List[str] = target.split(".") + mod = self + + for item in atoms: + if not hasattr(mod, item): + raise AttributeError(mod._get_name() + " has no attribute `" + item + "`") + + mod = getattr(mod, item) + + if not isinstance(mod, Module): + raise AttributeError("`" + item + "` is not an Module") + + return mod + + def clear_state(self) -> None: + """Reset self._params state to None.""" + self._params = None + + # TODO: Implement this for all submodules. + def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]: + raise NotImplementedError + + def get_children_by_indices(self, indices: Tensor) -> Iterator[Tuple[str, Module]]: + modules = list(self.named_children()) + for idx in indices: + yield modules[idx] + + def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, Module]]: + modules = list(self.named_children()) + # TODO: Wrong params passed here when nested ImageSequential + for param in params: + yield modules[list(dict(self.named_children()).keys()).index(param.name)] + + def get_params_by_module(self, named_modules: Iterator[Tuple[str, Module]]) -> Iterator[ParamItem]: + # This will not take module._params + for name, _ in named_modules: + yield ParamItem(name, None) + + +class SequentialBase(BasicSequentialBase): + r"""SequentialBase for creating kornia modulized processing pipeline. + + Args: + *args : a list of kornia augmentation and image operation modules. + same_on_batch: apply the same transformation across the batch. + If None, it will not overwrite the function-wise settings. + return_transform: if ``True`` return the matrix describing the transformation + applied to each. If None, it will not overwrite the function-wise settings. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). If None, it will not overwrite the function-wise settings. + + """ + + def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None: + # To name the modules properly + super().__init__(*args) + self._same_on_batch = same_on_batch + self._keepdim = keepdim + self.update_attribute(same_on_batch, keepdim=keepdim) + + def update_attribute( + self, + same_on_batch: Optional[bool] = None, + return_transform: Optional[bool] = None, + keepdim: Optional[bool] = None, + ) -> None: + for mod in self.children(): + # MixAugmentation does not have return transform + if isinstance(mod, (_AugmentationBase, K.MixAugmentationBaseV2)): + if same_on_batch is not None: + mod.same_on_batch = same_on_batch + if keepdim is not None: + mod.keepdim = keepdim + if isinstance(mod, SequentialBase): + mod.update_attribute(same_on_batch, return_transform, keepdim) + + @property + def same_on_batch(self) -> Optional[bool]: + return self._same_on_batch + + @same_on_batch.setter + def same_on_batch(self, same_on_batch: Optional[bool]) -> None: + self._same_on_batch = same_on_batch + self.update_attribute(same_on_batch=same_on_batch) + + @property + def keepdim(self) -> Optional[bool]: + return self._keepdim + + @keepdim.setter + def keepdim(self, keepdim: Optional[bool]) -> None: + self._keepdim = keepdim + self.update_attribute(keepdim=keepdim) + + def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]: + """Fill tensor dim to the upper bound of dim_range. + + If input tensor dim is smaller than the lower bound of dim_range, an error will be thrown out. + """ + ori_shape = input.shape + if len(ori_shape) < dim_range[0] or len(ori_shape) > dim_range[1]: + raise RuntimeError(f"input shape expected to be in {dim_range} while got {ori_shape}.") + while len(input.shape) < dim_range[1]: + input = input[None] + return ori_shape, input.shape + + +class ImageSequentialBase(SequentialBase): + def identity_matrix(self, input: Tensor) -> Tensor: + """Return identity matrix.""" + raise NotImplementedError + + def get_transformation_matrix( + self, + input: Tensor, + params: Optional[List[ParamItem]] = None, + recompute: bool = False, + extra_args: Optional[Dict[str, Any]] = None, + ) -> Optional[Tensor]: + """Compute the transformation matrix according to the provided parameters. + + Args: + input: the input tensor. + params: params for the sequence. + recompute: if to recompute the transformation matrix according to the params. + default: False. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + raise NotImplementedError + + def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]: + raise NotImplementedError + + def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]: + """Get module sequence by input params.""" + raise NotImplementedError + + def transform_inputs( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + for param in params: + module = self.get_submodule(param.name) + input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + return input + + def inverse_inputs( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]): + input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args) + return input + + def transform_masks( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + for param in params: + module = self.get_submodule(param.name) + input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + return input + + def inverse_masks( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]): + input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args) + return input + + def transform_boxes( + self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + for param in params: + module = self.get_submodule(param.name) + input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + return input + + def inverse_boxes( + self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]): + input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args) + return input + + def transform_keypoints( + self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + for param in params: + module = self.get_submodule(param.name) + input = KeypointSequentialOps.transform(input, module=module, param=param, extra_args=extra_args) + return input + + def inverse_keypoints( + self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]): + input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args) + return input + + def inverse( + self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Inverse transformation. + + Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to + provided parameters. + """ + if params is None: + if self._params is None: + raise ValueError( + "No parameters available for inversing, please run a forward pass first " + "or passing valid params into this function." + ) + params = self._params + + input = self.inverse_inputs(input, params, extra_args=extra_args) + + return input + + def forward( + self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + self.clear_state() + + if params is None: + inp = input + _, out_shape = self.autofill_dim(inp, dim_range=(2, 4)) + params = self.forward_parameters(out_shape) + + input = self.transform_inputs(input, params=params, extra_args=extra_args) + + self._params = params + return input + + +class TransformMatrixMinIn: + """Enables computation matrix computation.""" + + _valid_ops_for_transform_computation: Tuple[Any, ...] = () + _transformation_matrix_arg: str = "silent" + + def __init__(self, *args, **kwargs) -> None: # type:ignore + super().__init__(*args, **kwargs) + self._transform_matrix: Optional[Tensor] = None + self._transform_matrices: List[Optional[Tensor]] = [] + + def _parse_transformation_matrix_mode(self, transformation_matrix_mode: str) -> None: + _valid_transformation_matrix_args = {"silence", "silent", "rigid", "skip"} + if transformation_matrix_mode not in _valid_transformation_matrix_args: + raise ValueError( + f"`transformation_matrix` has to be one of {_valid_transformation_matrix_args}. " + f"Got {transformation_matrix_mode}." + ) + self._transformation_matrix_arg = transformation_matrix_mode + + @property + def transform_matrix(self) -> Optional[Tensor]: + # In AugmentationSequential, the parent class is accessed first. + # So that it was None in the beginning. We hereby use lazy computation here. + if self._transform_matrix is None and len(self._transform_matrices) != 0: + self._transform_matrix = self._transform_matrices[0] + for mat in self._transform_matrices[1:]: + self._update_transform_matrix(mat) + return self._transform_matrix + + def _update_transform_matrix_for_valid_op(self, module: Module) -> None: + raise NotImplementedError(module) + + def _update_transform_matrix_by_module(self, module: Module) -> None: + if self._transformation_matrix_arg == "skip": + return + if isinstance(module, self._valid_ops_for_transform_computation): + self._update_transform_matrix_for_valid_op(module) + elif self._transformation_matrix_arg == "rigid": + raise RuntimeError( + f"Non-rigid module `{module}` is not supported under `rigid` computation mode. " + "Please either update the module or change the `transformation_matrix` argument." + ) + + def _update_transform_matrix(self, transform_matrix: Optional[Tensor]) -> None: + if self._transform_matrix is None: + self._transform_matrix = transform_matrix + else: + self._transform_matrix = transform_matrix @ self._transform_matrix + + def _reset_transform_matrix_state(self) -> None: + self._transform_matrix = None + self._transform_matrices = [] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/dispatcher.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..b98089aec48f06aed92c4ac13de8a1d06c8a0201 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/dispatcher.py @@ -0,0 +1,114 @@ +# 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. +# + +from typing import List, Tuple, Union + +from torch import Tensor, nn + +from .augment import AugmentationSequential + + +class ManyToManyAugmentationDispather(nn.Module): + r"""Dispatches different augmentations to different inputs element-wisely. + + Args: + augmentations: a list or a sequence of kornia AugmentationSequential modules. + + Examples: + >>> import torch + >>> input_1, input_2 = torch.randn(2, 3, 5, 6), torch.randn(2, 3, 5, 6) + >>> mask_1, mask_2 = torch.ones(2, 3, 5, 6), torch.ones(2, 3, 5, 6) + >>> aug_list = ManyToManyAugmentationDispather( + ... AugmentationSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... data_keys=["input", "mask",], + ... ), + ... AugmentationSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... data_keys=["input", "mask",], + ... ) + ... ) + >>> output = aug_list((input_1, mask_1), (input_2, mask_2)) + + """ + + def __init__(self, *augmentations: AugmentationSequential) -> None: + super().__init__() + self._check_consistency(*augmentations) + self.augmentations = augmentations + + def _check_consistency(self, *augmentations: AugmentationSequential) -> bool: + for i, aug in enumerate(augmentations): + if not isinstance(aug, AugmentationSequential): + raise ValueError(f"Please wrap your augmentations[`{i}`] with `AugmentationSequentials`.") + return True + + def forward(self, *input: Union[List[Tensor], List[Tuple[Tensor]]]) -> Union[List[Tensor], List[Tuple[Tensor]]]: + return [aug(*inp) for inp, aug in zip(input, self.augmentations)] + + +class ManyToOneAugmentationDispather(nn.Module): + r"""Dispatches different augmentations to a single input and returns a list. + + Same `datakeys` must be applied across different augmentations. By default, with input + (image, mask), the augmentations must not mess it as (mask, image) to avoid unexpected + errors. This check can be cancelled with `strict=False` if needed. + + Args: + augmentations: a list or a sequence of kornia AugmentationSequential modules. + + Examples: + >>> import torch + >>> input = torch.randn(2, 3, 5, 6) + >>> mask = torch.ones(2, 3, 5, 6) + >>> aug_list = ManyToOneAugmentationDispather( + ... AugmentationSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... data_keys=["input", "mask",], + ... ), + ... AugmentationSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... data_keys=["input", "mask",], + ... ) + ... ) + >>> output = aug_list(input, mask) + + """ + + def __init__(self, *augmentations: AugmentationSequential, strict: bool = True) -> None: + super().__init__() + self.strict = strict + self._check_consistency(*augmentations) + self.augmentations = augmentations + + def _check_consistency(self, *augmentations: AugmentationSequential) -> bool: + for i, aug in enumerate(augmentations): + if not isinstance(aug, AugmentationSequential): + raise ValueError(f"Please wrap your augmentations[`{i}`] with `AugmentationSequentials`.") + if self.strict and i != 0 and aug.data_keys != augmentations[i - 1].data_keys: + raise RuntimeError( + f"Different `data_keys` between {i - 1} and {i} elements, " + f"got {aug.data_keys} and {augmentations[i - 1].data_keys}." + ) + return True + + def forward(self, *input: Union[Tensor, Tuple[Tensor]]) -> Union[List[Tensor], List[Tuple[Tensor]]]: + return [aug(*input) for aug in self.augmentations] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/image.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/image.py new file mode 100644 index 0000000000000000000000000000000000000000..f50db7fb3442846b417de84b040379170531c30b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/image.py @@ -0,0 +1,390 @@ +# 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. +# + +from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast + +import torch + +import kornia.augmentation as K +from kornia.augmentation.base import _AugmentationBase +from kornia.augmentation.utils import override_parameters +from kornia.core import ImageModule, Module, Tensor, as_tensor +from kornia.core.module import ImageModuleMixIn +from kornia.utils import eye_like + +from .base import ImageSequentialBase +from .params import ParamItem + +__all__ = ["ImageSequential"] + + +class ImageModuleForSequentialMixIn(ImageModuleMixIn): + _disable_features: bool = False + + @property + def disable_features(self) -> bool: + return self._disable_features + + @disable_features.setter + def disable_features(self, value: bool = True) -> None: + self._disable_features = value + + def disable_item_features(self, *args: Module) -> None: + for arg in args: + if isinstance(arg, (ImageModule,)): + arg.disable_features = True + + +class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn): + r"""Sequential for creating kornia image processing pipeline. + + Args: + *args : a list of kornia augmentation and image operation modules. + same_on_batch: apply the same transformation across the batch. + If None, it will not overwrite the function-wise settings. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). If None, it will not overwrite the function-wise settings. + random_apply: randomly select a sublist (order agnostic) of args to + apply transformation. The selection probability aligns to the ``random_apply_weights``. + If int, a fixed number of transformations will be selected. + If (a,), x number of transformations (a <= x <= len(args)) will be selected. + If (a, b), x number of transformations (a <= x <= b) will be selected. + If True, the whole list of args will be processed as a sequence in a random order. + If False, the whole list of args will be processed as a sequence in original order. + random_apply_weights: a list of selection weights for each operation. The length shall be as + same as the number of operations. By default, operations are sampled uniformly. + + .. note:: + Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module. + Those transformations in ``kornia.geometry`` will not be taken into account. + + Examples: + >>> _ = torch.manual_seed(77) + >>> import kornia + >>> input = torch.randn(2, 3, 5, 6) + >>> aug_list = ImageSequential( + ... kornia.color.BgrToRgb(), + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.filters.MedianBlur((3, 3)), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... kornia.enhance.Invert(), + ... kornia.augmentation.RandomMixUpV2(p=1.0), + ... same_on_batch=True, + ... random_apply=10, + ... ) + >>> out = aug_list(input) + >>> out.shape + torch.Size([2, 3, 5, 6]) + + Reproduce with provided params. + >>> out2 = aug_list(input, params=aug_list._params) + >>> torch.equal(out, out2) + True + + Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``ImageSequential``. + + >>> import kornia + >>> input = torch.randn(2, 3, 5, 6) + >>> aug_list = ImageSequential( + ... kornia.color.BgrToRgb(), + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.filters.MedianBlur((3, 3)), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... random_apply=1, + ... random_apply_weights=[0.5, 0.3, 0.2, 0.5] + ... ) + >>> out= aug_list(input) + >>> out.shape + torch.Size([2, 3, 5, 6]) + + """ + + def __init__( + self, + *args: Module, + same_on_batch: Optional[bool] = None, + keepdim: Optional[bool] = None, + random_apply: Union[int, bool, Tuple[int, int]] = False, + random_apply_weights: Optional[List[float]] = None, + if_unsupported_ops: str = "raise", + disable_item_features: bool = True, + disable_sequential_features: bool = False, + ) -> None: + if disable_item_features: + self.disable_item_features(*args) + if disable_sequential_features: + self.disable_features = True + super().__init__(*args, same_on_batch=same_on_batch, keepdim=keepdim) + + self.random_apply = self._read_random_apply(random_apply, len(args)) + if random_apply_weights is not None and len(random_apply_weights) != len(self): + raise ValueError( + "The length of `random_apply_weights` must be as same as the number of operations." + f"Got {len(random_apply_weights)} and {len(self)}." + ) + self.random_apply_weights = as_tensor(random_apply_weights or torch.ones((len(self),))) + self.if_unsupported_ops = if_unsupported_ops + + def _read_random_apply( + self, random_apply: Union[int, bool, Tuple[int, int]], max_length: int + ) -> Union[Tuple[int, int], bool]: + """Process the scenarios for random apply.""" + if isinstance(random_apply, (bool,)) and random_apply is False: + random_apply = False + elif isinstance(random_apply, (bool,)) and random_apply is True: + random_apply = (max_length, max_length + 1) + elif isinstance(random_apply, (int,)): + random_apply = (random_apply, random_apply + 1) + elif ( + isinstance(random_apply, (tuple,)) + and len(random_apply) == 2 + and isinstance(random_apply[0], (int,)) + and isinstance(random_apply[1], (int,)) + ): + random_apply = (random_apply[0], random_apply[1] + 1) + elif isinstance(random_apply, (tuple,)) and len(random_apply) == 1 and isinstance(random_apply[0], (int,)): + random_apply = (random_apply[0], max_length + 1) + else: + raise ValueError(f"Non-readable random_apply. Got {random_apply}.") + if random_apply is not False and not ( + isinstance(random_apply, (tuple,)) + and len(random_apply) == 2 + and isinstance(random_apply[0], (int,)) + and isinstance(random_apply[0], (int,)) + ): + raise AssertionError(f"Expect a tuple of (int, int). Got {random_apply}.") + return random_apply + + def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, Module]], bool]: + """Get a forward sequence when random apply is in need. + + Args: + with_mix: if to require a mix augmentation for the sequence. + + Note: + Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward. + + """ + if isinstance(self.random_apply, tuple): + num_samples = int(torch.randint(*self.random_apply, (1,)).item()) + else: + raise TypeError(f"random apply should be a tuple. Gotcha {type(self.random_apply)}") + + multinomial_weights = self.random_apply_weights.clone() + # Mix augmentation can only be applied once per forward + mix_indices = self.get_mix_augmentation_indices(self.named_children()) + # kick out the mix augmentations + multinomial_weights[mix_indices] = 0 + indices = torch.multinomial( + multinomial_weights, + num_samples, + # enable replacement if non-mix augmentation is less than required + replacement=num_samples > multinomial_weights.sum().item(), + ) + + mix_added = False + if with_mix and len(mix_indices) != 0: + # Make the selection fair. + if (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item(): + indices[-1] = torch.multinomial((~multinomial_weights.bool()).float(), 1) + indices = indices[torch.randperm(len(indices))] + mix_added = True + + return self.get_children_by_indices(indices), mix_added + + def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, Module]]) -> List[int]: + """Get all the mix augmentations since they are label-involved. + + Special operations needed for label-involved augmentations. + """ + # NOTE: MixV2 will not be a special op in the future. + return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, K.MixAugmentationBaseV2)] + + def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]: + if params is None: + # Mix augmentation can only be applied once per forward + mix_indices = self.get_mix_augmentation_indices(self.named_children()) + + if self.random_apply: + return self.get_random_forward_sequence()[0] + + if len(mix_indices) > 1: + raise ValueError( + "Multiple mix augmentation is prohibited without enabling random_apply." + f"Detected {len(mix_indices)} mix augmentations." + ) + + return self.named_children() + + return self.get_children_by_params(params) + + def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]: + named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence() + + params: List[ParamItem] = [] + mod_param: Union[Dict[str, Tensor], List[ParamItem]] + for name, module in named_modules: + if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2, ImageSequentialBase)): + mod_param = module.forward_parameters(batch_shape) + param = ParamItem(name, mod_param) + else: + param = ParamItem(name, None) + batch_shape = _get_new_batch_shape(param, batch_shape) + params.append(param) + return params + + def identity_matrix(self, input: Tensor) -> Tensor: + """Return identity matrix.""" + return eye_like(3, input) + + def get_transformation_matrix( + self, + input: Tensor, + params: Optional[List[ParamItem]] = None, + recompute: bool = False, + extra_args: Optional[Dict[str, Any]] = None, + ) -> Optional[Tensor]: + """Compute the transformation matrix according to the provided parameters. + + Args: + input: the input tensor. + params: params for the sequence. + recompute: if to recompute the transformation matrix according to the params. + default: False. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if params is None: + raise NotImplementedError("requires params to be provided.") + if extra_args is None: + extra_args = {} + named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params) + + # Define as 1 for broadcasting + res_mat: Optional[Tensor] = None + for (_, module), param in zip(named_modules, params if params is not None else []): + if isinstance(module, (K.GeometricAugmentationBase2D,)) and isinstance(param.data, dict): + ori_shape = input.shape + try: + input = module.transform_tensor(input) + except ValueError: + # Ignore error for 5-dim video + pass + # Standardize shape + if recompute: + flags = override_parameters(module.flags, extra_args, in_place=False) + mat = module.generate_transformation_matrix(input, param.data, flags) + elif module._transform_matrix is not None: + mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype) + else: + raise RuntimeError(f"{module}._transform_matrix is None while `recompute=False`.") + res_mat = mat if res_mat is None else mat @ res_mat + input = module.transform_output_tensor(input, ori_shape) + if module.keepdim and ori_shape != input.shape: + res_mat = res_mat.squeeze() + elif isinstance(module, (ImageSequentialBase,)): + # If not augmentationSequential + if isinstance(module, (K.AugmentationSequential,)) and not recompute: + mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype) + else: + maybe_param_data = cast(Optional[List[ParamItem]], param.data) + _mat = module.get_transformation_matrix( + input, maybe_param_data, recompute=recompute, extra_args=extra_args + ) + mat = module.identity_matrix(input) if _mat is None else _mat + res_mat = mat if res_mat is None else mat @ res_mat + return res_mat + + # TODO: Make this as a class property to avoid running every time. + def is_intensity_only(self, strict: bool = True) -> bool: + """Check if all transformations are intensity-based. + + Args: + strict: if strict is False, it will allow non-augmentation Modules to be passed. + e.g. `kornia.enhance.AdjustBrightness` will be recognized as non-intensity module + if strict is set to True. + + Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks). + + """ + for arg in self.children(): + if isinstance(arg, (ImageSequential,)) and not arg.is_intensity_only(strict): + return False + elif isinstance(arg, (ImageSequential,)): + pass + elif isinstance(arg, K.IntensityAugmentationBase2D): + pass + elif strict: + # disallow non-registered ops if in strict mode + # TODO: add an ops register module + return False + return True + + def __call__( + self, + *inputs: Any, + input_names_to_handle: Optional[List[Any]] = None, + output_type: str = "tensor", + **kwargs: Any, + ) -> Any: + """Overwrite the __call__ function to handle various inputs. + + Args: + inputs: Inputs to operate on. + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + kwargs: Additional arguments. + + Returns: + Callable: Decorated function with converted input and output types. + + """ + # Wrap the forward method with the decorator + if not self._disable_features: + decorated_forward = self.convert_input_output( + input_names_to_handle=input_names_to_handle, output_type=output_type + )(super().__call__) + _output_image = decorated_forward(*inputs, **kwargs) + if output_type == "tensor": + self._output_image = self._detach_tensor_to_cpu(_output_image) + else: + self._output_image = _output_image + else: + _output_image = super().__call__(*inputs, **kwargs) + return _output_image + + +def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size: + """Get the new batch shape if the augmentation changes the image size. + + Note: + Augmentations that change the image size must provide the parameter `output_size`. + + """ + if param.data is None: + return batch_shape + if isinstance(param.data, list): + for p in param.data: + batch_shape = _get_new_batch_shape(p, batch_shape) + elif "output_size" in param.data: + if not (param.data["batch_prob"] > 0.5)[0]: + # Augmentations that change the image size must be applied equally to all elements in batch. + # If the augmentation is not applied, return the same batch shape. + return batch_shape + new_batch_shape = list(batch_shape) + new_batch_shape[-2:] = param.data["output_size"][0] + batch_shape = torch.Size(new_batch_shape) + return batch_shape diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/ops.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb2b52ab8a13c834be16653bc4f1070cc954f4e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/ops.py @@ -0,0 +1,615 @@ +# 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. +# + +import copy +from abc import ABCMeta, abstractmethod +from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union + +from typing_extensions import ParamSpec + +import kornia.augmentation as K +from kornia.augmentation.base import _AugmentationBase +from kornia.constants import DataKey +from kornia.core import Module, Tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + +from .params import ParamItem + +DataType = Union[Tensor, List[Tensor], Boxes, Keypoints] + +# NOTE: shouldn't this SequenceDataType alias be equals to List[DataType]? +SequenceDataType = Union[List[Tensor], List[List[Tensor]], List[Boxes], List[Keypoints]] + +T = TypeVar("T") + + +class SequentialOpsInterface(Generic[T], metaclass=ABCMeta): + """Abstract interface for applying and inversing transformations.""" + + @classmethod + def get_instance_module_param(cls, param: ParamItem) -> Dict[str, Tensor]: + if isinstance(param, ParamItem) and isinstance(param.data, dict): + _params = param.data + else: + raise TypeError(f"Expected param (ParamItem.data) be a dictionary. Gotcha {param}.") + return _params + + @classmethod + def get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]: + if isinstance(param, ParamItem) and isinstance(param.data, list): + _params = param.data + else: + raise TypeError(f"Expected param (ParamItem.data) be a list. Gotcha {param}.") + return _params + + @classmethod + @abstractmethod + def transform(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T: + """Apply a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def inverse(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T: + """Inverse a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + raise NotImplementedError + + +class AugmentationSequentialOps: + def __init__(self, data_keys: Optional[List[DataKey]]) -> None: + self._data_keys = data_keys + + @property + def data_keys(self) -> Optional[List[DataKey]]: + return self._data_keys + + @data_keys.setter + def data_keys(self, data_keys: Optional[Union[List[DataKey], List[str], List[int]]]) -> None: + if data_keys: + self._data_keys = [DataKey.get(inp) for inp in data_keys] + else: + self._data_keys = None + + def preproc_datakeys(self, data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None) -> List[DataKey]: + if data_keys is None: + if isinstance(self.data_keys, list): + return self.data_keys + raise ValueError("Sequential ops needs data keys to be able to process.") + else: + return [DataKey.get(inp) for inp in data_keys] + + def _get_op(self, data_key: DataKey) -> Type[SequentialOpsInterface[Any]]: + """Return the corresponding operation given a data key.""" + if data_key == DataKey.INPUT: + return InputSequentialOps + if data_key == DataKey.MASK: + return MaskSequentialOps + if data_key in {DataKey.BBOX, DataKey.BBOX_XYWH, DataKey.BBOX_XYXY}: + return BoxSequentialOps + if data_key == DataKey.KEYPOINTS: + return KeypointSequentialOps + if data_key == DataKey.CLASS: + return ClassSequentialOps + raise RuntimeError(f"Operation for `{data_key.name}` is not found.") + + def transform( + self, + *arg: DataType, + module: Module, + param: ParamItem, + extra_args: Dict[DataKey, Dict[str, Any]], + data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None, + ) -> Union[DataType, SequenceDataType]: + _data_keys = self.preproc_datakeys(data_keys) + + if isinstance(module, K.RandomTransplantation): + # For transforms which require the full input to calculate the parameters (e.g. RandomTransplantation) + param = ParamItem( + name=param.name, + data=module.params_from_input( + *arg, # type: ignore[arg-type] + data_keys=_data_keys, + params=param.data, # type: ignore[arg-type] + extra_args=extra_args, + ), + ) + + outputs = [] + for inp, dcate in zip(arg, _data_keys): + op = self._get_op(dcate) + extra_arg = extra_args.get(dcate, {}) + if dcate.name == "MASK" and isinstance(inp, list): + outputs.append(MaskSequentialOps.transform_list(inp, module, param=param, extra_args=extra_arg)) + else: + outputs.append(op.transform(inp, module, param=param, extra_args=extra_arg)) + if len(outputs) == 1 and isinstance(outputs, (list, tuple)): + return outputs[0] + return outputs + + def inverse( + self, + *arg: DataType, + module: Module, + param: ParamItem, + extra_args: Dict[DataKey, Dict[str, Any]], + data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None, + ) -> Union[DataType, SequenceDataType]: + _data_keys = self.preproc_datakeys(data_keys) + outputs = [] + for inp, dcate in zip(arg, _data_keys): + op = self._get_op(dcate) + extra_arg = extra_args[dcate] if dcate in extra_args else {} + outputs.append(op.inverse(inp, module, param=param, extra_args=extra_arg)) + if len(outputs) == 1 and isinstance(outputs, (list, tuple)): + return outputs[0] + return outputs + + +P = ParamSpec("P") + + +def make_input_only_sequential(module: "K.container.ImageSequentialBase") -> Callable[P, Tensor]: + """Disable all other additional inputs (e.g. ) for ImageSequential.""" + + def f(*args: P.args, **kwargs: P.kwargs) -> Tensor: + return module(*args, **kwargs) + + return f + + +def get_geometric_only_param(module: "K.container.ImageSequentialBase", param: List[ParamItem]) -> List[ParamItem]: + """Return geometry param.""" + named_modules = module.get_forward_sequence(param) + + res: List[ParamItem] = [] + for (_, mod), p in zip(named_modules, param): + if isinstance(mod, (K.GeometricAugmentationBase2D, K.GeometricAugmentationBase3D)): + res.append(p) + return res + + +class InputSequentialOps(SequentialOpsInterface[Tensor]): + @classmethod + def transform( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if extra_args is None: + extra_args = {} + if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)): + input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.INPUT], **extra_args) + elif isinstance(module, (K.container.ImageSequentialBase,)): + input = module.transform_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + elif isinstance(module, (K.auto.operations.OperationBase,)): + input = module(input, params=cls.get_instance_module_param(param)) + else: + if param.data is not None: + raise AssertionError(f"Non-augmentaion operation {param.name} require empty parameters. Got {param}.") + input = module(input) + return input + + @classmethod + def inverse( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if extra_args is None: + extra_args = {} + if isinstance(module, K.GeometricAugmentationBase2D): + input = module.inverse(input, params=cls.get_instance_module_param(param), **extra_args) + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d inverse operations are not yet supported. You are welcome to file a PR in our repo." + ) + elif isinstance(module, (K.auto.operations.OperationBase,)): + return InputSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args) + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + input = module.inverse_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + elif isinstance(module, K.container.ImageSequentialBase): + input = module.inverse_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + return input + + +class ClassSequentialOps(SequentialOpsInterface[Tensor]): + """Apply and inverse transformations for class labels if needed.""" + + @classmethod + def transform( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if isinstance(module, K.MixAugmentationBaseV2): + raise NotImplementedError( + "The support for class labels for mix augmentations that change the class label is not yet supported." + ) + return input + + @classmethod + def inverse( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + return input + + +class MaskSequentialOps(SequentialOpsInterface[Tensor]): + """Apply and inverse transformations for mask tensors.""" + + @classmethod + def transform( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Apply a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + input = module.transform_masks( + input, + params=cls.get_instance_module_param(param), + flags=module.flags, + transform=module.transform_matrix, + **extra_args, + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.RandomTransplantation): + input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.MASK], **extra_args) + + elif isinstance(module, (_AugmentationBase)): + input = module.transform_masks( + input, params=cls.get_instance_module_param(param), flags=module.flags, **extra_args + ) + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + input = module.transform_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + + elif isinstance(module, K.container.ImageSequentialBase): + input = module.transform_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + input = MaskSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args) + + return input + + @classmethod + def transform_list( + cls, input: List[Tensor], module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> List[Tensor]: + """Apply a transformation with respect to the parameters. + + Args: + input: list of input tensors. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + if isinstance(module, (K.GeometricAugmentationBase2D,)): + tfm_input = [] + params = cls.get_instance_module_param(param) + params_i = copy.deepcopy(params) + for i, inp in enumerate(input): + params_i["batch_prob"] = params["batch_prob"][i] + tfm_inp = module.transform_masks( + inp, params=params_i, flags=module.flags, transform=module.transform_matrix, **extra_args + ) + tfm_input.append(tfm_inp) + input = tfm_input + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo." + ) + + elif isinstance(module, (_AugmentationBase)): + tfm_input = [] + params = cls.get_instance_module_param(param) + params_i = copy.deepcopy(params) + for i, inp in enumerate(input): + params_i["batch_prob"] = params["batch_prob"][i] + tfm_inp = module.transform_masks(inp, params=params_i, flags=module.flags, **extra_args) + tfm_input.append(tfm_inp) + input = tfm_input + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + tfm_input = [] + seq_params = cls.get_sequential_module_param(param) + for inp in input: + tfm_inp = module.transform_masks(inp, params=seq_params, extra_args=extra_args) + tfm_input.append(tfm_inp) + input = tfm_input + + elif isinstance(module, K.container.ImageSequentialBase): + tfm_input = [] + seq_params = cls.get_sequential_module_param(param) + for inp in input: + tfm_inp = module.transform_masks(inp, params=seq_params, extra_args=extra_args) + tfm_input.append(tfm_inp) + input = tfm_input + + elif isinstance(module, (K.auto.operations.OperationBase,)): + raise NotImplementedError( + "The support for list of masks under auto operations are not yet supported. You are welcome to file a" + " PR in our repo." + ) + return input + + @classmethod + def inverse( + cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Inverse a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + if module.transform_matrix is None: + raise ValueError(f"No valid transformation matrix found in {module.__class__}.") + transform = module.compute_inverse_transformation(module.transform_matrix) + input = module.inverse_masks( + input, + params=cls.get_instance_module_param(param), + flags=module.flags, + transform=transform, + **extra_args, + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.container.ImageSequentialBase): + input = module.inverse_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + input = MaskSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args) + + return input + + +class BoxSequentialOps(SequentialOpsInterface[Boxes]): + """Apply and inverse transformations for bounding box tensors. + + This is for transform boxes in the format (B, N, 4, 2). + """ + + @classmethod + def transform( + cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + """Apply a transformation with respect to the parameters. + + Args: + input: the input tensor, (B, N, 4, 2) or (B, 4, 2). + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + _input = input.clone() + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + _input = module.transform_boxes( + _input, + cls.get_instance_module_param(param), + module.flags, + transform=module.transform_matrix, + **extra_args, + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + _input = module.transform_boxes( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, K.container.ImageSequentialBase): + _input = module.transform_boxes( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + return BoxSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args) + + return _input + + @classmethod + def inverse( + cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + """Inverse a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + _input = input.clone() + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + if module.transform_matrix is None: + raise ValueError(f"No valid transformation matrix found in {module.__class__}.") + transform = module.compute_inverse_transformation(module.transform_matrix) + _input = module.inverse_boxes( + _input, + param.data, # type: ignore[arg-type] + module.flags, + transform=transform, + **extra_args, + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + _input = module.inverse_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + + elif isinstance(module, K.container.ImageSequentialBase): + _input = module.inverse_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + return BoxSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args) + return _input + + +class KeypointSequentialOps(SequentialOpsInterface[Keypoints]): + """Apply and inverse transformations for keypoints tensors. + + This is for transform keypoints in the format (B, N, 2). + """ + + @classmethod + def transform( + cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + """Apply a transformation with respect to the parameters. + + Args: + input: the input tensor, (B, N, 4, 2) or (B, 4, 2). + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + _input = input.clone() + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + _input = module.transform_keypoints( + _input, + cls.get_instance_module_param(param), + module.flags, + transform=module.transform_matrix, + **extra_args, + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d keypoint operations are not yet supported. " + "You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + _input = module.transform_keypoints( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, K.container.ImageSequentialBase): + _input = module.transform_keypoints( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + return KeypointSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args) + + return _input + + @classmethod + def inverse( + cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + """Inverse a transformation with respect to the parameters. + + Args: + input: the input tensor. + module: any torch Module but only kornia augmentation modules will count + to apply transformations. + param: the corresponding parameters to the module. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if extra_args is None: + extra_args = {} + _input = input.clone() + + if isinstance(module, (K.GeometricAugmentationBase2D,)): + if module.transform_matrix is None: + raise ValueError(f"No valid transformation matrix found in {module.__class__}.") + transform = module.compute_inverse_transformation(module.transform_matrix) + _input = module.inverse_keypoints( + _input, cls.get_instance_module_param(param), module.flags, transform=transform, **extra_args + ) + + elif isinstance(module, (K.GeometricAugmentationBase3D,)): + raise NotImplementedError( + "The support for 3d keypoint operations are not yet supported. " + "You are welcome to file a PR in our repo." + ) + + elif isinstance(module, K.ImageSequential) and not module.is_intensity_only(): + _input = module.inverse_keypoints( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, K.container.ImageSequentialBase): + _input = module.inverse_keypoints( + _input, params=cls.get_sequential_module_param(param), extra_args=extra_args + ) + + elif isinstance(module, (K.auto.operations.OperationBase,)): + return KeypointSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args) + + return _input diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/params.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/params.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0aa042df95b7b8e3e012e7a94f92e2f6ed8ab3 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/params.py @@ -0,0 +1,32 @@ +# 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. +# + +from typing import Dict, List, NamedTuple, Optional, Union + +from kornia.core import Tensor + +__all__ = ["ParamItem", "PatchParamItem"] + + +class ParamItem(NamedTuple): + name: str + data: Optional[Union[Dict[str, Tensor], List["ParamItem"]]] + + +class PatchParamItem(NamedTuple): + indices: List[int] + param: ParamItem diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/patch.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b8d8c48ce23c4c930404f198d56ccfa4ce8803 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/patch.py @@ -0,0 +1,426 @@ +# 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. +# + +from itertools import cycle, islice +from typing import Any, Dict, Iterator, List, Optional, Tuple, Union + +import torch + +import kornia.augmentation as K +from kornia.augmentation.base import _AugmentationBase +from kornia.contrib.extract_patches import extract_tensor_patches +from kornia.core import Module, Tensor, concatenate +from kornia.core import pad as fpad +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + +from .base import SequentialBase +from .image import ImageSequential +from .ops import InputSequentialOps +from .params import ParamItem, PatchParamItem + +__all__ = ["PatchSequential"] + + +class PatchSequential(ImageSequential): + r"""Container for performing patch-level image data augmentation. + + .. image:: _static/img/PatchSequential.png + + PatchSequential breaks input images into patches by a given grid size, which will be resembled back + afterwards. + + Different image processing and augmentation methods will be performed on each patch region as + in :cite:`lin2021patch`. + + Args: + *args: a list of processing modules. + grid_size: controls the grid board separation. + padding: same or valid padding. If same padding, it will pad to include all pixels if the input + tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed. + same_on_batch: apply the same transformation across the batch. + If None, it will not overwrite the function-wise settings. + keepdim: whether to keep the output shape the same as input (True) or broadcast it + to the batch form (False). If None, it will not overwrite the function-wise settings. + patchwise_apply: apply image processing args will be applied patch-wisely. + if ``True``, the number of args must be equal to grid number. + if ``False``, the image processing args will be applied as a sequence to all patches. + random_apply: randomly select a sublist (order agnostic) of args to + apply transformation. + If ``int`` (batchwise mode only), a fixed number of transformations will be selected. + If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected. + If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected. + If ``True``, the whole list of args will be processed in a random order. + If ``False`` and not ``patchwise_apply``, the whole list of args will be processed in original order. + If ``False`` and ``patchwise_apply``, the whole list of args will be processed in original order + location-wisely. + + .. note:: + Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module. + Those transformations in ``kornia.geometry`` will not be taken into account. + + .. note:: + See a working example `here `__. + + Examples: + >>> import kornia.augmentation as K + >>> input = torch.randn(2, 3, 224, 224) + >>> seq = PatchSequential( + ... ImageSequential( + ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5), + ... K.RandomPerspective(0.2, p=0.5), + ... K.RandomSolarize(0.1, 0.1, p=0.5), + ... ), + ... K.RandomAffine(360, p=1.0), + ... ImageSequential( + ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5), + ... K.RandomPerspective(0.2, p=0.5), + ... K.RandomSolarize(0.1, 0.1, p=0.5), + ... ), + ... K.RandomSolarize(0.1, 0.1, p=0.1), + ... grid_size=(2,2), + ... patchwise_apply=True, + ... same_on_batch=True, + ... random_apply=False, + ... ) + >>> out = seq(input) + >>> out.shape + torch.Size([2, 3, 224, 224]) + >>> out1 = seq(input, params=seq._params) + >>> torch.equal(out, out1) + True + + Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``PatchSequential``. + + >>> import kornia + >>> input = torch.randn(2, 3, 224, 224) + >>> seq = PatchSequential( + ... ImageSequential( + ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5), + ... K.RandomPerspective(0.2, p=0.5), + ... K.RandomSolarize(0.1, 0.1, p=0.5), + ... ), + ... K.RandomAffine(360, p=1.0), + ... K.RandomSolarize(0.1, 0.1, p=0.1), + ... grid_size=(2,2), + ... patchwise_apply=False, + ... random_apply=1, + ... random_apply_weights=[0.5, 0.3, 0.8] + ... ) + >>> out = seq(input) + >>> out.shape + torch.Size([2, 3, 224, 224]) + + """ + + def __init__( + self, + *args: Module, + grid_size: Tuple[int, int] = (4, 4), + padding: str = "same", + same_on_batch: Optional[bool] = None, + keepdim: Optional[bool] = None, + patchwise_apply: bool = True, + random_apply: Union[int, bool, Tuple[int, int]] = False, + random_apply_weights: Optional[List[float]] = None, + ) -> None: + _random_apply: Optional[Union[int, Tuple[int, int]]] + + if patchwise_apply and random_apply is True: + # will only apply [1, 4] augmentations per patch + _random_apply = (1, 4) + elif patchwise_apply and random_apply is False: + if len(args) != grid_size[0] * grid_size[1]: + raise ValueError( + "The number of processing modules must be equal with grid size." + f"Got {len(args)} and {grid_size[0] * grid_size[1]}. " + "Please set random_apply = True or patchwise_apply = False." + ) + _random_apply = random_apply + elif patchwise_apply and isinstance(random_apply, (int, tuple)): + raise ValueError(f"Only boolean value allowed when `patchwise_apply` is set to True. Got {random_apply}.") + else: + _random_apply = random_apply + super().__init__( + *args, + same_on_batch=same_on_batch, + keepdim=keepdim, + random_apply=_random_apply, + random_apply_weights=random_apply_weights, + ) + if padding not in ("same", "valid"): + raise ValueError(f"`padding` must be either `same` or `valid`. Got {padding}.") + self.grid_size = grid_size + self.padding = padding + self.patchwise_apply = patchwise_apply + self._params: Optional[List[PatchParamItem]] # type: ignore[assignment] + + def compute_padding( + self, input: Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None + ) -> Tuple[int, int, int, int]: + if grid_size is None: + grid_size = self.grid_size + if padding == "valid": + ph, pw = input.size(-2) // grid_size[0], input.size(-1) // grid_size[1] + return (-pw // 2, pw // 2 - pw, -ph // 2, ph // 2 - ph) + if padding == "same": + ph = input.size(-2) - input.size(-2) // grid_size[0] * grid_size[0] + pw = input.size(-1) - input.size(-1) // grid_size[1] * grid_size[1] + return (pw // 2, pw - pw // 2, ph // 2, ph - ph // 2) + raise NotImplementedError(f"Expect `padding` as either 'valid' or 'same'. Got {padding}.") + + def extract_patches( + self, + input: Tensor, + grid_size: Optional[Tuple[int, int]] = None, + pad: Optional[Tuple[int, int, int, int]] = None, + ) -> Tensor: + """Extract patches from tensor. + + Example: + >>> import kornia.augmentation as K + >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False) + >>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2)) + tensor([[[[[ 0, 1], + [ 4, 5]]], + + + [[[ 2, 3], + [ 6, 7]]], + + + [[[ 8, 9], + [12, 13]]], + + + [[[10, 11], + [14, 15]]]]]) + >>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -1, -2, -2)) + tensor([[[[[19, 20, 21]]], + + + [[[22, 23, 24]]], + + + [[[28, 29, 30]]], + + + [[[31, 32, 33]]]]]) + + """ + if pad is not None: + input = fpad(input, list(pad)) + if grid_size is None: + grid_size = self.grid_size + window_size = (input.size(-2) // grid_size[-2], input.size(-1) // grid_size[-1]) + stride = window_size + return extract_tensor_patches(input, window_size, stride) + + def restore_from_patches( + self, patches: Tensor, grid_size: Tuple[int, int] = (4, 4), pad: Optional[Tuple[int, int, int, int]] = None + ) -> Tensor: + """Restore input from patches. + + Example: + >>> import kornia.augmentation as K + >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False) + >>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2)) + >>> pas.restore_from_patches(out, grid_size=(2, 2)) + tensor([[[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]]]) + + """ + if grid_size is None: + grid_size = self.grid_size + patches_tensor = patches.view(-1, grid_size[0], grid_size[1], *patches.shape[-3:]) + restored_tensor = concatenate(torch.chunk(patches_tensor, grid_size[0], 1), -2).squeeze(1) + restored_tensor = concatenate(torch.chunk(restored_tensor, grid_size[1], 1), -1).squeeze(1) + + if pad is not None: + restored_tensor = fpad(restored_tensor, [-i for i in pad]) + return restored_tensor + + def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override] + out_param: List[PatchParamItem] = [] + if not self.patchwise_apply: + params = self.generate_parameters(torch.Size([1, batch_shape[0] * batch_shape[1], *batch_shape[2:]])) + indices = torch.arange(0, batch_shape[0] * batch_shape[1]) + out_param = [PatchParamItem(indices.tolist(), p) for p, _ in params] + # "append" of "list" does not return a value + elif not self.same_on_batch: + params = self.generate_parameters(torch.Size([batch_shape[0] * batch_shape[1], 1, *batch_shape[2:]])) + out_param = [PatchParamItem([i], p) for p, i in params] + # "append" of "list" does not return a value + else: + params = self.generate_parameters(torch.Size([batch_shape[1], batch_shape[0], *batch_shape[2:]])) + indices = torch.arange(0, batch_shape[0] * batch_shape[1], step=batch_shape[1]) + out_param = [PatchParamItem((indices + i).tolist(), p) for p, i in params] + # "append" of "list" does not return a value + return out_param + + def generate_parameters(self, batch_shape: torch.Size) -> Iterator[Tuple[ParamItem, int]]: + """Get multiple forward sequence but maximumly one mix augmentation in between. + + Args: + batch_shape: 5-dim shape arranged as :math:``(N, B, C, H, W)``, in which N represents + the number of sequence. + + """ + if not self.same_on_batch and self.random_apply: + # diff_on_batch and random_apply => patch-wise augmentation + with_mix = False + for i in range(batch_shape[0]): + seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix) + with_mix = mix_added + for s in seq: + if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)): + yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i + else: + yield ParamItem(s[0], None), i + elif not self.same_on_batch and not self.random_apply: + for i, nchild in enumerate(self.named_children()): + if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)): + yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i + else: + yield ParamItem(nchild[0], None), i + elif not self.random_apply: + # same_on_batch + not random_apply => location-wise augmentation + for i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])): + if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)): + yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i + else: + yield ParamItem(nchild[0], None), i + else: + # same_on_batch + random_apply => location-wise augmentation + with_mix = False + for i in range(batch_shape[0]): + seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix) + with_mix = mix_added + for s in seq: + if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)): + yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i + else: + yield ParamItem(s[0], None), i + + def forward_by_params(self, input: Tensor, params: List[PatchParamItem]) -> Tensor: + in_shape = input.shape + input = input.reshape(-1, *in_shape[-3:]) + + for patch_param in params: + # input, out_param = self.apply_by_param(input, params=patch_param) + module = self.get_submodule(patch_param.param.name) + _input = input[patch_param.indices] + output = InputSequentialOps.transform(_input, module, patch_param.param, extra_args={}) + input[patch_param.indices] = output + + return input.reshape(in_shape) + + def transform_inputs( # type: ignore[override] + self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + pad = self.compute_padding(input, self.padding) + input = self.extract_patches(input, self.grid_size, pad) + input = self.forward_by_params(input, params) + input = self.restore_from_patches(input, self.grid_size, pad=pad) + + return input + + def inverse_inputs( # type: ignore[override] + self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.") + + def transform_masks( # type: ignore[override] + self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.") + + def inverse_masks( # type: ignore[override] + self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.") + + def transform_boxes( # type: ignore[override] + self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.") + + def inverse_boxes( # type: ignore[override] + self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Boxes: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.") + + def transform_keypoints( # type: ignore[override] + self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential for keypoints cannot be used with geometric transformations.") + + def inverse_keypoints( # type: ignore[override] + self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Keypoints: + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.") + + def inverse( # type: ignore[override] + self, input: Tensor, params: Optional[List[PatchParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Inverse transformation. + + Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to + provided parameters. + """ + if self.is_intensity_only(): + return input + + raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.") + + def forward(self, input: Tensor, params: Optional[List[PatchParamItem]] = None) -> Tensor: # type: ignore[override] + """Input transformation will be returned if input is a tuple.""" + # BCHW -> B(patch)CHW + if isinstance(input, (tuple,)): + raise ValueError("tuple input is not currently supported.") + + if params is None: + params = self.forward_parameters(input.shape) + + output = self.transform_inputs(input, params=params) + + self._params = params + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/container/video.py b/python_embeded/Lib/site-packages/kornia/augmentation/container/video.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f5b970b8c022acb062f86c29d5ada730b36fc6 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/container/video.py @@ -0,0 +1,374 @@ +# 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. +# + +from typing import Any, Dict, List, Optional, Tuple, Union, cast + +import torch + +import kornia.augmentation as K +from kornia.augmentation.base import _AugmentationBase +from kornia.augmentation.container.base import SequentialBase +from kornia.augmentation.container.image import ImageSequential, _get_new_batch_shape +from kornia.core import Module, Tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + +from .params import ParamItem + +__all__ = ["VideoSequential"] + + +class VideoSequential(ImageSequential): + r"""VideoSequential for processing 5-dim video data like (B, T, C, H, W) and (B, C, T, H, W). + + `VideoSequential` is used to replace `nn.Sequential` for processing video data augmentations. + By default, `VideoSequential` enabled `same_on_frame` to make sure the same augmentations happen + across temporal dimension. Meanwhile, it will not affect other augmentation behaviours like the + settings on `same_on_batch`, etc. + + Args: + *args: a list of augmentation module. + data_format: only BCTHW and BTCHW are supported. + same_on_frame: apply the same transformation across the channel per frame. + random_apply: randomly select a sublist (order agnostic) of args to + apply transformation. + If int, a fixed number of transformations will be selected. + If (a,), x number of transformations (a <= x <= len(args)) will be selected. + If (a, b), x number of transformations (a <= x <= b) will be selected. + If None, the whole list of args will be processed as a sequence. + + Note: + Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module. + Those transformations in ``kornia.geometry`` will not be taken into account. + + Example: + If set `same_on_frame` to True, we would expect the same augmentation has been applied to each + timeframe. + + >>> import kornia + >>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1) + >>> aug_list = VideoSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.color.BgrToRgb(), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... random_apply=10, + ... data_format="BCTHW", + ... same_on_frame=True) + >>> output = aug_list(input) + >>> (output[0, :, 0] == output[0, :, 1]).all() + tensor(True) + >>> (output[0, :, 1] == output[0, :, 2]).all() + tensor(True) + >>> (output[0, :, 2] == output[0, :, 3]).all() + tensor(True) + + If set `same_on_frame` to False: + + >>> aug_list = VideoSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... kornia.augmentation.RandomMixUpV2(p=1.0), + ... data_format="BCTHW", + ... same_on_frame=False) + >>> output = aug_list(input) + >>> output.shape + torch.Size([2, 3, 4, 5, 6]) + >>> (output[0, :, 0] == output[0, :, 1]).all() + tensor(False) + + Reproduce with provided params. + >>> out2 = aug_list(input, params=aug_list._params) + >>> torch.equal(output, out2) + True + + Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``VideoSequential``. + + >>> import kornia + >>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1]) + >>> aug_list = VideoSequential( + ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), + ... kornia.augmentation.RandomAffine(360, p=1.0), + ... kornia.augmentation.RandomMixUpV2(p=1.0), + ... data_format="BCTHW", + ... same_on_frame=False, + ... random_apply=1, + ... random_apply_weights=[0.5, 0.3, 0.8] + ... ) + >>> out = aug_list(input) + >>> out.shape + torch.Size([2, 3, 4, 5, 6]) + + """ + + # TODO: implement transform_matrix + + def __init__( + self, + *args: Module, + data_format: str = "BTCHW", + same_on_frame: bool = True, + random_apply: Union[int, bool, Tuple[int, int]] = False, + random_apply_weights: Optional[List[float]] = None, + ) -> None: + super().__init__( + *args, + same_on_batch=None, + keepdim=None, + random_apply=random_apply, + random_apply_weights=random_apply_weights, + ) + self.same_on_frame = same_on_frame + self.data_format = data_format.upper() + if self.data_format not in ["BCTHW", "BTCHW"]: + raise AssertionError(f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`.") + self._temporal_channel: int + if self.data_format == "BCTHW": + self._temporal_channel = 2 + elif self.data_format == "BTCHW": + self._temporal_channel = 1 + + def __infer_channel_exclusive_batch_shape__(self, batch_shape: torch.Size, chennel_index: int) -> torch.Size: + # Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size") + return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :]) + + def __repeat_param_across_channels__(self, param: Tensor, frame_num: int) -> Tensor: + """Repeat parameters across channels. + + The input is shaped as (B, ...), while to output (B * same_on_frame, ...), which + to guarantee that the same transformation would happen for each frame. + + (B1, B2, ..., Bn) => (B1, ... B1, B2, ..., B2, ..., Bn, ..., Bn) + | ch_size | | ch_size | ..., | ch_size | + """ + repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:]))) + return repeated.reshape(-1, *list(param.shape[1:])) + + def _input_shape_convert_in(self, input: Tensor, frame_num: int) -> Tensor: + # Convert any shape to (B, T, C, H, W) + if self.data_format == "BCTHW": + # Convert (B, C, T, H, W) to (B, T, C, H, W) + input = input.transpose(1, 2) + if self.data_format == "BTCHW": + pass + + input = input.reshape(-1, *input.shape[2:]) + return input + + def _input_shape_convert_back(self, input: Tensor, frame_num: int) -> Tensor: + input = input.view(-1, frame_num, *input.shape[1:]) + if self.data_format == "BCTHW": + input = input.transpose(1, 2) + if self.data_format == "BTCHW": + pass + + return input + + def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]: + frame_num = batch_shape[self._temporal_channel] + named_modules = self.get_forward_sequence() + # Got param generation shape to (B, C, H, W). Ignoring T. + batch_shape = self.__infer_channel_exclusive_batch_shape__(batch_shape, self._temporal_channel) + + if not self.same_on_frame: + # Overwrite param generation shape to (B * T, C, H, W). + batch_shape = torch.Size([batch_shape[0] * frame_num, *batch_shape[1:]]) + + params = [] + for name, module in named_modules: + if isinstance(module, K.RandomCrop): + mod_param = module.forward_parameters(batch_shape) + if self.same_on_frame: + mod_param["src"] = mod_param["src"].repeat(frame_num, 1, 1) + mod_param["dst"] = mod_param["dst"].repeat(frame_num, 1, 1) + param = ParamItem(name, mod_param) + elif isinstance(module, (SequentialBase,)): + seq_param = module.forward_parameters(batch_shape) + if self.same_on_frame: + raise ValueError("Sequential is currently unsupported for ``same_on_frame``.") + param = ParamItem(name, seq_param) + elif isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)): + mod_param = module.forward_parameters(batch_shape) + if self.same_on_frame: + for k, v in mod_param.items(): + # TODO: revise ColorJiggle and ColorJitter order param in the future to align the standard. + if k == "order" and (isinstance(module, (K.ColorJiggle, K.ColorJitter))): + continue + if k == "forward_input_shape": + mod_param.update({k: v}) + continue + mod_param.update({k: self.__repeat_param_across_channels__(v, frame_num)}) + param = ParamItem(name, mod_param) + else: + param = ParamItem(name, None) + batch_shape = _get_new_batch_shape(param, batch_shape) + params.append(param) + return params + + def transform_inputs( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + frame_num: int = input.size(self._temporal_channel) + input = self._input_shape_convert_in(input, frame_num) + + input = super().transform_inputs(input, params, extra_args=extra_args) + + input = self._input_shape_convert_back(input, frame_num) + return input + + def inverse_inputs( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + frame_num: int = input.size(self._temporal_channel) + input = self._input_shape_convert_in(input, frame_num) + + input = super().inverse_inputs(input, params, extra_args=extra_args) + + input = self._input_shape_convert_back(input, frame_num) + return input + + def transform_masks( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + frame_num: int = input.size(self._temporal_channel) + input = self._input_shape_convert_in(input, frame_num) + + input = super().transform_masks(input, params, extra_args=extra_args) + + input = self._input_shape_convert_back(input, frame_num) + return input + + def inverse_masks( + self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + frame_num: int = input.size(self._temporal_channel) + input = self._input_shape_convert_in(input, frame_num) + + input = super().inverse_masks(input, params, extra_args=extra_args) + + input = self._input_shape_convert_back(input, frame_num) + return input + + def transform_boxes( # type: ignore[override] + self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Union[Tensor, Boxes]: + """Transform bounding boxes. + + Args: + input: tensor with shape :math:`(B, T, N, 4, 2)`. + If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`. + params: params for the sequence. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if isinstance(input, Tensor): + batchsize, frame_num = input.size(0), input.size(1) + input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus") + input = super().transform_boxes(input, params, extra_args=extra_args) + input = input.data.view(batchsize, frame_num, -1, 4, 2) + else: + input = super().transform_boxes(input, params, extra_args=extra_args) + return input + + def inverse_boxes( # type: ignore[override] + self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Union[Tensor, Boxes]: + """Transform bounding boxes. + + Args: + input: tensor with shape :math:`(B, T, N, 4, 2)`. + If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`. + params: params for the sequence. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if isinstance(input, Tensor): + batchsize, frame_num = input.size(0), input.size(1) + input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus") + input = super().inverse_boxes(input, params, extra_args=extra_args) + input = input.data.view(batchsize, frame_num, -1, 4, 2) + else: + input = super().inverse_boxes(input, params, extra_args=extra_args) + return input + + def transform_keypoints( # type: ignore[override] + self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Union[Tensor, Keypoints]: + """Transform bounding boxes. + + Args: + input: tensor with shape :math:`(B, T, N, 2)`. + If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`. + params: params for the sequence. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if isinstance(input, Tensor): + batchsize, frame_num = input.size(0), input.size(1) + input = Keypoints(input.view(-1, input.size(2), input.size(3))) + input = super().transform_keypoints(input, params, extra_args=extra_args) + input = input.data.view(batchsize, frame_num, -1, 2) + else: + input = super().transform_keypoints(input, params, extra_args=extra_args) + return input + + def inverse_keypoints( # type: ignore[override] + self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None + ) -> Union[Tensor, Keypoints]: + """Transform bounding boxes. + + Args: + input: tensor with shape :math:`(B, T, N, 2)`. + If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`. + params: params for the sequence. + extra_args: Optional dictionary of extra arguments with specific options for different input types. + """ + if isinstance(input, Tensor): + frame_num, batchsize = input.size(0), input.size(1) + input = Keypoints(input.view(-1, input.size(2), input.size(3))) + input = super().inverse_keypoints(input, params, extra_args=extra_args) + input = input.data.view(batchsize, frame_num, -1, 2) + else: + input = super().inverse_keypoints(input, params, extra_args=extra_args) + return input + + def inverse( + self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Inverse transformation. + + Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to + provided parameters. + """ + if params is None: + if self._params is not None: + params = self._params + else: + raise RuntimeError("No valid params to inverse the transformation.") + + return self.inverse_inputs(input, params, extra_args=extra_args) + + def forward( + self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None + ) -> Tensor: + """Define the video computation performed.""" + if len(input.shape) != 5: + raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.") + + if params is None: + self._params = self.forward_parameters(input.shape) + params = self._params + + output = self.transform_inputs(input, params, extra_args=extra_args) + + return output diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6245f10940f94032c8228e68149831f15ecfc9 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/__init__.py @@ -0,0 +1,21 @@ +# 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. +# + +from kornia.augmentation.random_generator._2d import * +from kornia.augmentation.random_generator._3d import * + +from .base import DistributionWithMapper, UniformDistribution diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/base.py b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/base.py new file mode 100644 index 0000000000000000000000000000000000000000..299f3c06f52633830e6a1a265533733746ef2433 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/base.py @@ -0,0 +1,137 @@ +# 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. +# + +from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar + +import torch +from torch.distributions import Distribution, Uniform + +from kornia.augmentation.utils.helpers import MultiprocessWrapper +from kornia.core import Device, Module, Tensor + +T = TypeVar("T") + + +class _PostInitInjectionMetaClass(type): + """To inject the ``__post_init__`` function after the creation of each instance.""" + + def __call__(cls: Type[T], *args: Any, **kwargs: Any) -> T: + obj = type.__call__(cls, *args, **kwargs) + obj.__post_init__() + return obj + + +class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass): + """Base class for generating random augmentation parameters.""" + + device: Optional[Device] = None + dtype: torch.dtype + + def __init__(self) -> None: + super().__init__() + + def __post_init__(self) -> None: + self.set_rng_device_and_dtype() + + def set_rng_device_and_dtype( + self, + device: Optional[torch.device] = None, + dtype: torch.dtype = torch.float32, + ) -> None: + """Change the random generation device and dtype. + + Note: + The generated random numbers are not reproducible across different devices and dtypes. + + """ + if device is None: + device = torch.device("cpu") + if self.device != device or self.dtype != dtype: + self.make_samplers(device, dtype) + self.device = device + self.dtype = dtype + + # TODO: refine the logic with module.to() + def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase": + device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs) + self.set_rng_device_and_dtype(device=device, dtype=dtype) + return self + + def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None: + raise NotImplementedError + + def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]: + raise NotImplementedError + + +class DistributionWithMapper(Distribution): + """Wraps a distribution with a value mapper function. + + This is used to restrict the output values of a given distribution by a value mapper function. + The value mapper function can be functions like sigmoid, tanh, etc. + + Args: + dist: the target distribution. + map_fn: the callable function to adjust the output from distributions. + + Example: + >>> from torch.distributions import Normal + >>> import torch.nn as nn + >>> # without mapper + >>> dist = DistributionWithMapper(Normal(0., 1.,), map_fn=None) + >>> _ = torch.manual_seed(0) + >>> dist.rsample((8,)) + tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845, -1.3986, 0.4033, 0.8380]) + >>> # with sigmoid mapper + >>> dist = DistributionWithMapper(Normal(0., 1.,), map_fn=nn.Sigmoid()) + >>> _ = torch.manual_seed(0) + >>> dist.rsample((8,)) + tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980]) + + """ + + def __init__(self, dist: Distribution, map_fn: Optional[Callable[[Tensor], Tensor]] = None) -> None: + self.dist = dist + self.map_fn = map_fn + + def rsample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override] + out = self.dist.rsample(torch.Size(sample_shape)) + if self.map_fn is not None: + out = self.map_fn(out) + return out + + def sample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override] + out = self.dist.sample(torch.Size(sample_shape)) + if self.map_fn is not None: + out = self.map_fn(out) + return out + + def sample_n(self, n: int) -> Tensor: + out = self.dist.sample_n(n) + if self.map_fn is not None: + out = self.map_fn(out) + return out + + def __getattr__(self, attr: str) -> Any: + try: + return getattr(self, attr) + except AttributeError: + return getattr(self.dist, attr) + + +class UniformDistribution(MultiprocessWrapper, Uniform): + """Wrapper around torch Uniform distribution which makes it work with the 'spawn' multiprocessing context.""" diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/utils.py b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3582d06847f09961a8a4c3796fd56dce38fe49 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/random_generator/utils.py @@ -0,0 +1,31 @@ +# 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. +# + +from typing import Any + +import torch + +from kornia.core import Tensor + + +def randperm(n: int, ensure_perm: bool = True, **kwargs: Any) -> Tensor: + """`randomperm` with the ability to ensure the different arrangement generated.""" + perm = torch.randperm(n, **kwargs) + if ensure_perm: + while torch.all(torch.eq(perm, torch.arange(n, device=perm.device))): + perm = torch.randperm(n, **kwargs) + return perm diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/utils/__init__.py b/python_embeded/Lib/site-packages/kornia/augmentation/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ede66c83e7cb180e45221047253289208c41593 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/utils/__init__.py @@ -0,0 +1,72 @@ +# 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. +# + +from kornia.augmentation.utils.helpers import ( + _adapted_beta, + _adapted_rsampling, + _adapted_sampling, + _adapted_uniform, + _infer_batch_shape, + _infer_batch_shape3d, + _shape_validation, + _transform_input, + _transform_input3d, + _transform_input3d_by_shape, + _transform_input_by_shape, + _transform_output_shape, + _validate_input, + _validate_input3d, + _validate_input_dtype, + _validate_input_shape, + _validate_shape, + deepcopy_dict, + override_parameters, +) +from kornia.augmentation.utils.param_validation import ( + _common_param_check, + _joint_range_check, + _range_bound, + _singular_range_check, + _tuple_range_reader, +) + +__all__ = [ + "_adapted_beta", + "_adapted_rsampling", + "_adapted_sampling", + "_adapted_uniform", + "_common_param_check", + "_infer_batch_shape", + "_infer_batch_shape3d", + "_joint_range_check", + "_range_bound", + "_shape_validation", + "_singular_range_check", + "_transform_input", + "_transform_input3d", + "_transform_input3d_by_shape", + "_transform_input_by_shape", + "_transform_output_shape", + "_tuple_range_reader", + "_validate_input", + "_validate_input3d", + "_validate_input_dtype", + "_validate_input_shape", + "_validate_shape", + "deepcopy_dict", + "override_parameters", +] diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/utils/helpers.py b/python_embeded/Lib/site-packages/kornia/augmentation/utils/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..1507532b565aadce64691b650dcec75535f9b18f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/utils/helpers.py @@ -0,0 +1,488 @@ +# 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. +# + +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import torch +from torch.distributions import Beta, Uniform + +from kornia.core import Tensor, as_tensor +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints +from kornia.utils import _extract_device_dtype + + +def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]: + r"""Validate the 2D input of the wrapped function. + + Args: + f: a function that takes the first argument as tensor. + + Returns: + the wrapped function after input is validated. + + """ + + @wraps(f) + def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any: + if not torch.is_tensor(input): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + _validate_shape(input.shape, required_shapes=("BCHW",)) + _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64]) + + return f(input, *args, **kwargs) + + return wrapper + + +def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]: + r"""Validate the 3D input of the wrapped function. + + Args: + f: a function that takes the first argument as tensor. + + Returns: + the wrapped function after input is validated. + + """ + + @wraps(f) + def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any: + if not torch.is_tensor(input): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + input_shape = len(input.shape) + if input_shape != 5: + raise AssertionError(f"Expect input of 5 dimensions, got {input_shape} instead") + _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64]) + + return f(input, *args, **kwargs) + + return wrapper + + +def _infer_batch_shape(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size: + r"""Infer input shape. + + Input may be either (tensor,) or (tensor, transform_matrix) + """ + if isinstance(input, tuple): + tensor = _transform_input(input[0]) + else: + tensor = _transform_input(input) + return tensor.shape + + +def _infer_batch_shape3d(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size: + r"""Infer input shape. + + Input may be either (tensor,) or (tensor, transform_matrix) + """ + if isinstance(input, tuple): + tensor = _transform_input3d(input[0]) + else: + tensor = _transform_input3d(input) + return tensor.shape + + +def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor: + """Reshape an input tensor to have the same dimensions as the reference_shape. + + Arguments: + input: tensor to be transformed + reference_shape: shape used as reference + match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default + + """ + B = reference_shape[-4] if len(reference_shape) >= 4 else None + C = reference_shape[-3] if len(reference_shape) >= 3 else None + + if len(input.shape) == 2: + input = input.unsqueeze(0) + + if len(input.shape) == 3: + # If the first dim matches within the batch_size, add a `C` dim + # Useful to handler Masks without `C` dimensions + input = input.unsqueeze(1) if B == input.shape[-3] else input.unsqueeze(0) + + if match_channel and C: + if not input.shape[-3] == C: + raise ValueError("The C dimension of tensor did not match with the reference tensor.") + elif match_channel and C is None: + raise ValueError("The reference tensor do not have a C dimension!") + + return input + + +def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor: + """Reshape an input tensor to have the same dimensions as the reference_shape. + + Arguments: + input: tensor to be transformed + reference_shape: shape used as reference + match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default + + """ + B = reference_shape[-5] if len(reference_shape) >= 5 else None + C = reference_shape[-4] if len(reference_shape) >= 4 else None + + if len(input.shape) == 3: + input = input.unsqueeze(0) + + if len(input.shape) == 4 and B == input.shape[-4]: + # If the first dim matches within the batch_size, add a `C` dim + # Useful to handler Masks without `C` dimensions + input = input.unsqueeze(2) + + if match_channel and C: + if not input.shape[-4] == C: + raise ValueError("The C dimension of tensor did not match with the reference tensor.") + elif match_channel and C is None: + raise ValueError("The reference tensor do not have a C dimension!") + + return input + + +def _transform_input(input: Tensor) -> Tensor: + r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W). + + Args: + input: Tensor + + Returns: + Tensor + + """ + if not torch.is_tensor(input): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if len(input.shape) not in [2, 3, 4]: + raise ValueError(f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}") + + if len(input.shape) == 2: + input = input.unsqueeze(0) + + if len(input.shape) == 3: + input = input.unsqueeze(0) + + return input + + +def _transform_input3d(input: Tensor) -> Tensor: + r"""Reshape an input tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W). + + Args: + input: Tensor + + Returns: + Tensor + + """ + if not torch.is_tensor(input): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if len(input.shape) not in [3, 4, 5]: + raise ValueError( + f"Input size must have a shape of either (D, H, W), (C, D, H, W) or (*, C, D, H, W). Got {input.shape}" + ) + + if len(input.shape) == 3: + input = input.unsqueeze(0) + + if len(input.shape) == 4: + input = input.unsqueeze(0) + + return input + + +def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) -> None: + r"""Check if the dtype of the input tensor is in the range of accepted_dtypes. + + Args: + input: Tensor + accepted_dtypes: List. e.g. [torch.float32, torch.float64] + """ + if input.dtype not in accepted_dtypes: + raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}") + + +def _transform_output_shape( + output: Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[Tensor] = None +) -> Tensor: + r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape. + + Args: + output: Tensor + shape: List/tuple of int + reference_shape: Tensor representation of shape to control which dimensions are collapsed. + + Returns: + Tensor + + """ + out_tensor = output.clone() + + for dim in range(len(out_tensor.shape) - len(shape)): + idx = 0 + if reference_shape is not None and out_tensor.shape[0] == reference_shape[0] != 1 and len(shape) > 2: + idx = 1 + if out_tensor.shape[idx] != 1: + raise AssertionError(f"Dimension {dim} of input is expected to be 1, got {out_tensor.shape[idx]}") + out_tensor = out_tensor.squeeze(idx) + + return out_tensor + + +def _validate_shape(shape: Union[Tuple[int, ...], torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None: + r"""Check if the dtype of the input tensor is in the range of accepted_dtypes. + + Args: + shape: tensor shape + required_shapes: List. e.g. ["BCHW", "BCDHW"] + """ + passed = False + for required_shape in required_shapes: + if len(shape) == len(required_shape): + passed = True + break + if not passed: + raise TypeError(f"Expected input shape in {required_shape}. Got {shape}.") + + +def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> bool: + r"""Validate if an input has the right shape. + + e.g. to check if an input is channel first. + If channel first, the second channel of an RGB input shall be fixed to 3. To verify using: + _validate_input_shape(input, 1, 3) + + Args: + input: Tensor + channel_index: int + number: int + Returns: + bool + + """ + return input.shape[channel_index] == number + + +def _adapted_rsampling( + shape: Union[Tuple[int, ...], torch.Size], + dist: torch.distributions.Distribution, + same_on_batch: Optional[bool] = False, +) -> Tensor: + r"""Sample from a uniform reparameterized sampling function that accepts 'same_on_batch'. + + If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default, + same_on_batch is set to False. + """ + if isinstance(shape, tuple): + shape = torch.Size(shape) + + if same_on_batch: + rsample_size = torch.Size((1, *shape[1:])) + rsample = dist.rsample(rsample_size) + return rsample.repeat(shape[0], *[1] * (len(rsample.shape) - 1)) + return dist.rsample(shape) + + +def _adapted_sampling( + shape: Union[Tuple[int, ...], torch.Size], + dist: torch.distributions.Distribution, + same_on_batch: Optional[bool] = False, +) -> Tensor: + r"""Sample from a uniform sampling function that accepts 'same_on_batch'. + + If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default, + same_on_batch is set to False. + """ + if isinstance(shape, tuple): + shape = torch.Size(shape) + + if same_on_batch: + return dist.sample(torch.Size((1, *shape[1:]))).repeat(shape[0], *[1] * (len(shape) - 1)) + return dist.sample(shape) + + +def _adapted_uniform( + shape: Union[Tuple[int, ...], torch.Size], + low: Union[float, Tensor], + high: Union[float, Tensor], + same_on_batch: bool = False, +) -> Tensor: + r"""Sample from a uniform sampling function that accepts 'same_on_batch'. + + If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default, + same_on_batch is set to False. + + By default, sampling happens on the default device and dtype. If low/high is a tensor, sampling will happen in the + same device/dtype as low/high tensor. + """ + device, dtype = _extract_device_dtype( + [low if isinstance(low, Tensor) else None, high if isinstance(high, Tensor) else None] + ) + low = as_tensor(low, device=device, dtype=dtype) + high = as_tensor(high, device=device, dtype=dtype) + # validate_args=False to fix pytorch 1.7.1 error: + # ValueError: Uniform is not defined when low>= high. + dist = Uniform(low, high, validate_args=False) + return _adapted_rsampling(shape, dist, same_on_batch) + + +def _adapted_beta( + shape: Union[Tuple[int, ...], torch.Size], + a: Union[float, Tensor], + b: Union[float, Tensor], + same_on_batch: bool = False, +) -> Tensor: + r"""Sample from a beta sampling function that accepts 'same_on_batch'. + + If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default, + same_on_batch is set to False. + + By default, sampling happens on the default device and dtype. If a/b is a tensor, sampling will happen in the same + device/dtype as a/b tensor. + """ + device, dtype = _extract_device_dtype([a if isinstance(a, Tensor) else None, b if isinstance(b, Tensor) else None]) + a = as_tensor(a, device=device, dtype=dtype) + b = as_tensor(b, device=device, dtype=dtype) + dist = Beta(a, b, validate_args=False) + return _adapted_rsampling(shape, dist, same_on_batch) + + +def _shape_validation(param: Tensor, shape: Union[Tuple[int, ...], List[int]], name: str) -> None: + if param.shape != torch.Size(shape): + raise AssertionError(f"Invalid shape for {name}. Expected {shape}. Got {param.shape}") + + +def deepcopy_dict(params: Dict[str, Any]) -> Dict[str, Any]: + """Perform deep copy on any dict. + + Support tensor copying here. + """ + out = {} + for k, v in params.items(): + # NOTE: Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol + if isinstance(v, Tensor): + out.update({k: v.clone()}) + else: + out.update({k: v}) + return out + + +def override_parameters( + params: Dict[str, Any], + params_override: Optional[Dict[str, Any]] = None, + if_none_exist: str = "ignore", + in_place: bool = False, +) -> Dict[str, Any]: + """Override params dict w.r.t params_override. + + Args: + params: source parameters. + params_override: key-values to override the source parameters. + if_none_exist: behaviour if the key in `params_override` does not exist in `params`. + 'raise' | 'ignore'. + in_place: if to override in-place or not. + + """ + if params_override is None: + return params + out = params if in_place else deepcopy_dict(params) + for k, v in params_override.items(): + if k in params_override: + out[k] = v + elif if_none_exist == "ignore": + pass + elif if_none_exist == "raise": + raise RuntimeError(f"Param `{k}` not existed in `{params_override}`.") + else: + raise ValueError(f"`{if_none_exist}` is not a valid option.") + return out + + +def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -> Boxes: + r"""Preprocess input boxes. + + Args: + input: 2D boxes, shape of :math:`(N, 4, 2)`, :math:`(B, N, 4, 2)` or a list of :math:`(N, 4, 2)`. + See below for more details. + mode: The format in which the boxes are provided. + + * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin`` + and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`. + * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as + ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. + With shape :math:`(N, 4)`, :math:`(B, N, 4)`. + * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where + ``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`. + * 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order: + *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally, + box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``. + With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`. + * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as + ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``. + With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`. + + Note: + **2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2`` + where each box is a `quadrilateral `_ defined by it's 4 vertices + coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of a box is defined as + ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of + `quadrilaterals `_ are rectangles, rhombus and trapezoids. + + """ + # TODO: We may allow list here. + # input is BxNx4x2 or Boxes. + if isinstance(input, Tensor): + if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])): + raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.") + input = Boxes.from_tensor(input, mode=mode) + if not isinstance(input, Boxes): + raise RuntimeError(f"Expect `Boxes` type. Got {type(input)}.") + return input + + +def preprocess_keypoints(input: Union[Tensor, Keypoints]) -> Keypoints: + """Preprocess input keypoints.""" + # TODO: We may allow list here. + if isinstance(input, Tensor): + if not (len(input.shape) == 3 and input.shape[1:] == torch.Size([2])): + raise RuntimeError(f"Only BxNx2 tensor is supported. Got {input.shape}.") + input = Keypoints(input, False) + if isinstance(input, Keypoints): + raise RuntimeError(f"Expect `Keypoints` type. Got {type(input)}.") + return input + + +def preprocess_classes(input: Tensor) -> Tensor: + """Preprocess input class tags.""" + # TODO: We may allow list here. + return input + + +class MultiprocessWrapper: + """When used as a base class, makes the class work with the 'spawn' multiprocessing context.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + args = tuple(arg.clone() if isinstance(arg, torch.Tensor) else arg for arg in args) + kwargs = {key: val.clone() if isinstance(val, torch.Tensor) else val for key, val in kwargs.items()} + + super().__init__(*args, **kwargs) diff --git a/python_embeded/Lib/site-packages/kornia/augmentation/utils/param_validation.py b/python_embeded/Lib/site-packages/kornia/augmentation/utils/param_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2e740214179cd6e854bda7ccf45458091c618e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/augmentation/utils/param_validation.py @@ -0,0 +1,195 @@ +# 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. +# + +from typing import Any, List, Optional, Tuple, Union + +import torch + +from kornia.core import Tensor, as_tensor, tensor + + +def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -> None: + """Check valid batch_size and same_on_batch params.""" + if not (isinstance(batch_size, int) and batch_size >= 0): + raise AssertionError(f"`batch_size` shall be a positive integer. Got {batch_size}.") + if same_on_batch is not None and not isinstance(same_on_batch, bool): + raise AssertionError(f"`same_on_batch` shall be boolean. Got {same_on_batch}.") + + +def _range_bound( + factor: Union[Tensor, float, Tuple[float, float], List[float]], + name: str, + center: Optional[float] = 0.0, + bounds: Optional[Tuple[float, float]] = (0, float("inf")), + check: Optional[str] = "joint", + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +) -> Tensor: + r"""Check inputs and compute the corresponding factor bounds.""" + if device is None: + device = torch.device("cpu") + if dtype is None: + dtype = torch.get_default_dtype() + if not isinstance(factor, (Tensor)): + factor = tensor(factor, device=device, dtype=dtype) + factor_bound: Tensor + + if factor.dim() == 0: + if factor < 0: + raise ValueError(f"If {name} is a single number, it must be non negative. Got {factor}.") + if center is None or bounds is None: + raise ValueError(f"`center` and `bounds` cannot be None for single number. Got {center}, {bounds}.") + # Should be something other than clamp + # Currently, single value factor will not out of scope as long as the user provided it. + # Note: I personally think throw an error will be better than a coarse clamp. + factor_bound = factor.repeat(2) * tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center + factor_bound = factor_bound.clamp(bounds[0], bounds[1]).to(device=device, dtype=dtype) + else: + factor_bound = as_tensor(factor, device=device, dtype=dtype) + + if check is not None: + if check == "joint": + _joint_range_check(factor_bound, name, bounds) + elif check == "singular": + _singular_range_check(factor_bound, name, bounds) + else: + raise NotImplementedError(f"methods '{check}' not implemented.") + + return factor_bound + + +def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None: + """Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1].""" + if bounds is None: + bounds = (float("-inf"), float("inf")) + if ranged_factor.dim() == 1 and len(ranged_factor) == 2: + if not bounds[0] <= ranged_factor[0] or not bounds[1] >= ranged_factor[1]: + raise ValueError(f"{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.") + + if not bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]: + raise ValueError(f"{name}[0] should be smaller than {name}[1] got {ranged_factor}") + else: + raise TypeError(f"{name} should be a tensor with length 2 whose values between {bounds}. Got {ranged_factor}.") + + +def _singular_range_check( + ranged_factor: Tensor, + name: str, + bounds: Optional[Tuple[float, float]] = None, + skip_none: bool = False, + mode: str = "2d", +) -> None: + """Check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1].""" + if mode == "2d": + dim_size = 2 + elif mode == "3d": + dim_size = 3 + else: + raise ValueError(f"'mode' shall be either 2d or 3d. Got {mode}") + + if skip_none and ranged_factor is None: + return + if bounds is None: + bounds = (float("-inf"), float("inf")) + if ranged_factor.dim() == 1 and len(ranged_factor) == dim_size: + for f in ranged_factor: + if not bounds[0] <= f <= bounds[1]: + raise ValueError(f"{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.") + else: + raise TypeError( + f"{name} should be a float number or a tuple with length {dim_size} whose values between {bounds}." + f"Got {ranged_factor}" + ) + + +def _tuple_range_reader( + input_range: Union[Tensor, float, Tuple[Any, ...]], + target_size: int, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +) -> Tensor: + """Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params. + + Example: + >>> degree = tensor([0.2, 0.3]) + >>> _tuple_range_reader(degree, 3) # read degree for yaw, pitch and roll. + tensor([[0.2000, 0.3000], + [0.2000, 0.3000], + [0.2000, 0.3000]]) + + """ + target_shape = torch.Size([target_size, 2]) + + if isinstance(input_range, Tensor): + if (len(input_range.shape) == 0) or (len(input_range.shape) == 1 and len(input_range) == 1): + if input_range < 0: + raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}") + input_range_tmp = input_range.repeat(2).to(device=device, dtype=dtype) * tensor( + [-1, 1], device=device, dtype=dtype + ) + input_range_tmp = input_range_tmp.repeat(target_shape[0], 1) + + elif len(input_range.shape) == 1 and len(input_range) == 2: + input_range_tmp = input_range.repeat(target_shape[0], 1).to(device=device, dtype=dtype) + + elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]: + input_range_tmp = input_range.unsqueeze(1).repeat(1, 2).to(device=device, dtype=dtype) * tensor( + [-1, 1], device=device, dtype=dtype + ) + + elif input_range.shape == target_shape: + input_range_tmp = input_range.to(device=device, dtype=dtype) + + else: + raise ValueError( + f"Degrees must be a {list(target_shape)} tensor for the degree range for independent operation." + f"Got {input_range}" + ) + elif isinstance(input_range, (float, int)): + if input_range < 0: + raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}") + input_range_tmp = tensor([-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1) + + elif ( + isinstance(input_range, (tuple, list)) + and len(input_range) == 2 + and isinstance(input_range[0], (float, int)) + and isinstance(input_range[1], (float, int)) + ): + input_range_tmp = tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1) + + elif ( + isinstance(input_range, (tuple, list)) + and len(input_range) == target_shape[0] + and all(isinstance(x, (float, int)) for x in input_range) + ): + input_range_tmp = tensor([(-s, s) for s in input_range], device=device, dtype=dtype) + + elif ( + isinstance(input_range, (tuple, list)) + and len(input_range) == target_shape[0] + and all(isinstance(x, (tuple, list)) for x in input_range) + ): + input_range_tmp = tensor(input_range, device=device, dtype=dtype) + + else: + raise TypeError( + "If not pass a tensor, it must be float, (float, float) for isotropic operation or a tuple of " + f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}." + ) + + return input_range_tmp diff --git a/python_embeded/Lib/site-packages/kornia/color/__init__.py b/python_embeded/Lib/site-packages/kornia/color/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7420bd3e15af78c38c2c7d216ab75388b5e4319a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/__init__.py @@ -0,0 +1,154 @@ +# 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. +# + +from .colormap import AUTUMN, ApplyColorMap, ColorMap, ColorMapType, RGBColor, apply_colormap +from .gray import BgrToGrayscale, GrayscaleToRgb, RgbToGrayscale, bgr_to_grayscale, grayscale_to_rgb, rgb_to_grayscale +from .hls import HlsToRgb, RgbToHls, hls_to_rgb, rgb_to_hls +from .hsv import HsvToRgb, RgbToHsv, hsv_to_rgb, rgb_to_hsv +from .lab import LabToRgb, RgbToLab, lab_to_rgb, rgb_to_lab +from .luv import LuvToRgb, RgbToLuv, luv_to_rgb, rgb_to_luv +from .raw import CFA, RawToRgb, RawToRgb2x2Downscaled, RgbToRaw, raw_to_rgb, raw_to_rgb_2x2_downscaled, rgb_to_raw +from .rgb import ( + BgrToRgb, + BgrToRgba, + LinearRgbToRgb, + NormalsToRgb255, + Rgb255ToNormals, + Rgb255ToRgb, + RgbaToBgr, + RgbaToRgb, + RgbToBgr, + RgbToLinearRgb, + RgbToRgb255, + RgbToRgba, + bgr_to_rgb, + bgr_to_rgba, + linear_rgb_to_rgb, + normals_to_rgb255, + rgb255_to_normals, + rgb255_to_rgb, + rgb_to_bgr, + rgb_to_linear_rgb, + rgb_to_rgb255, + rgb_to_rgba, + rgba_to_bgr, + rgba_to_rgb, +) +from .sepia import Sepia, sepia_from_rgb +from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb +from .ycbcr import RgbToYcbcr, YcbcrToRgb, rgb_to_y, rgb_to_ycbcr, ycbcr_to_rgb +from .yuv import ( + RgbToYuv, + RgbToYuv420, + RgbToYuv422, + Yuv420ToRgb, + Yuv422ToRgb, + YuvToRgb, + rgb_to_yuv, + rgb_to_yuv420, + rgb_to_yuv422, + yuv420_to_rgb, + yuv422_to_rgb, + yuv_to_rgb, +) + +__all__ = [ + "AUTUMN", + "CFA", + "ApplyColorMap", + "BgrToGrayscale", + "BgrToRgb", + "BgrToRgba", + "ColorMap", + "ColorMapType", + "GrayscaleToRgb", + "HlsToRgb", + "HsvToRgb", + "LabToRgb", + "LinearRgbToRgb", + "LuvToRgb", + "NormalsToRgb255", + "RGBColor", + "RawToRgb", + "RawToRgb2x2Downscaled", + "Rgb255ToNormals", + "Rgb255ToRgb", + "RgbToBgr", + "RgbToGrayscale", + "RgbToHls", + "RgbToHsv", + "RgbToLab", + "RgbToLinearRgb", + "RgbToLuv", + "RgbToRaw", + "RgbToRgb255", + "RgbToRgba", + "RgbToXyz", + "RgbToYcbcr", + "RgbToYuv", + "RgbToYuv420", + "RgbToYuv422", + "RgbaToBgr", + "RgbaToRgb", + "Sepia", + "XyzToRgb", + "YcbcrToRgb", + "Yuv420ToRgb", + "Yuv422ToRgb", + "YuvToRgb", + "apply_colormap", + "bgr_to_grayscale", + "bgr_to_rgb", + "bgr_to_rgba", + "grayscale_to_rgb", + "hls_to_rgb", + "hsv_to_rgb", + "lab_to_rgb", + "linear_rgb_to_rgb", + "luv_to_rgb", + "normals_to_rgb255", + "raw_to_rgb", + "raw_to_rgb_2x2_downscaled", + "rgb255_to_normals", + "rgb255_to_rgb", + "rgb_to_bgr", + "rgb_to_grayscale", + "rgb_to_hls", + "rgb_to_hsv", + "rgb_to_lab", + "rgb_to_linear_rgb", + "rgb_to_luv", + "rgb_to_raw", + "rgb_to_rgb255", + "rgb_to_rgba", + "rgb_to_xyz", + "rgb_to_y", + "rgb_to_ycbcr", + "rgb_to_yuv", + "rgb_to_yuv420", + "rgb_to_yuv422", + "rgba_to_bgr", + "rgba_to_rgb", + "sepia", + "xyz_to_rgb", + "ycbcr_to_rgb", + "yuv420_to_rgb", + "yuv422_to_rgb", + "yuv_to_rgb", +] + +sepia = sepia_from_rgb diff --git a/python_embeded/Lib/site-packages/kornia/color/_colormap_data.py b/python_embeded/Lib/site-packages/kornia/color/_colormap_data.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c487fee90daca8660ba83b49c3cd6c69ef0794 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/_colormap_data.py @@ -0,0 +1,1337 @@ +# 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. +# + +from __future__ import annotations + +from typing import List + +# All colormaps has 64 base colors. Extracted from matplotlib. +# https://matplotlib.org/stable/users/explain/colors/colormaps.html + + +RGBColor = List[float] + + +def get_autumn_base() -> list[RGBColor]: + return [ + [1.0, 0.0, 0.0], + [1.0, 0.015873015873015872, 0.0], + [1.0, 0.031746031746031744, 0.0], + [1.0, 0.047619047619047616, 0.0], + [1.0, 0.06349206349206349, 0.0], + [1.0, 0.07936507936507936, 0.0], + [1.0, 0.09523809523809523, 0.0], + [1.0, 0.1111111111111111, 0.0], + [1.0, 0.12698412698412698, 0.0], + [1.0, 0.14285714285714285, 0.0], + [1.0, 0.15873015873015872, 0.0], + [1.0, 0.1746031746031746, 0.0], + [1.0, 0.19047619047619047, 0.0], + [1.0, 0.20634920634920634, 0.0], + [1.0, 0.2222222222222222, 0.0], + [1.0, 0.23809523809523808, 0.0], + [1.0, 0.25396825396825395, 0.0], + [1.0, 0.2698412698412698, 0.0], + [1.0, 0.2857142857142857, 0.0], + [1.0, 0.30158730158730157, 0.0], + [1.0, 0.31746031746031744, 0.0], + [1.0, 0.3333333333333333, 0.0], + [1.0, 0.3492063492063492, 0.0], + [1.0, 0.36507936507936506, 0.0], + [1.0, 0.38095238095238093, 0.0], + [1.0, 0.3968253968253968, 0.0], + [1.0, 0.4126984126984127, 0.0], + [1.0, 0.42857142857142855, 0.0], + [1.0, 0.4444444444444444, 0.0], + [1.0, 0.4603174603174603, 0.0], + [1.0, 0.47619047619047616, 0.0], + [1.0, 0.49206349206349204, 0.0], + [1.0, 0.5079365079365079, 0.0], + [1.0, 0.5238095238095237, 0.0], + [1.0, 0.5396825396825397, 0.0], + [1.0, 0.5555555555555556, 0.0], + [1.0, 0.5714285714285714, 0.0], + [1.0, 0.5873015873015872, 0.0], + [1.0, 0.6031746031746031, 0.0], + [1.0, 0.6190476190476191, 0.0], + [1.0, 0.6349206349206349, 0.0], + [1.0, 0.6507936507936507, 0.0], + [1.0, 0.6666666666666666, 0.0], + [1.0, 0.6825396825396826, 0.0], + [1.0, 0.6984126984126984, 0.0], + [1.0, 0.7142857142857142, 0.0], + [1.0, 0.7301587301587301, 0.0], + [1.0, 0.746031746031746, 0.0], + [1.0, 0.7619047619047619, 0.0], + [1.0, 0.7777777777777777, 0.0], + [1.0, 0.7936507936507936, 0.0], + [1.0, 0.8095238095238095, 0.0], + [1.0, 0.8253968253968254, 0.0], + [1.0, 0.8412698412698412, 0.0], + [1.0, 0.8571428571428571, 0.0], + [1.0, 0.873015873015873, 0.0], + [1.0, 0.8888888888888888, 0.0], + [1.0, 0.9047619047619047, 0.0], + [1.0, 0.9206349206349206, 0.0], + [1.0, 0.9365079365079365, 0.0], + [1.0, 0.9523809523809523, 0.0], + [1.0, 0.9682539682539681, 0.0], + [1.0, 0.9841269841269841, 0.0], + [1.0, 1.0, 0.0], + ] + + +def get_bone_base() -> list[RGBColor]: + return [ + [0.0, 0.0, 0.0], + [0.013888888888888888, 0.013888883454100847, 0.019323671497584544], + [0.027777777777777776, 0.027777766908201693, 0.03864734299516909], + [0.041666666666666664, 0.04166665036230254, 0.05797101449275363], + [0.05555555555555555, 0.05555553381640339, 0.07729468599033817], + [0.06944444444444445, 0.06944441727050424, 0.09661835748792272], + [0.08333333333333333, 0.08333330072460508, 0.11594202898550726], + [0.09722222222222221, 0.09722218417870591, 0.13526570048309178], + [0.1111111111111111, 0.11111106763280677, 0.15458937198067635], + [0.125, 0.12499995108690763, 0.1739130434782609], + [0.1388888888888889, 0.13888883454100848, 0.19323671497584544], + [0.15277777777777776, 0.1527777179951093, 0.21256038647342998], + [0.16666666666666666, 0.16666660144921017, 0.23188405797101452], + [0.18055555555555555, 0.18055548490331103, 0.2512077294685991], + [0.19444444444444442, 0.19444436835741183, 0.27053140096618356], + [0.2083333333333333, 0.2083332518115127, 0.2898550724637681], + [0.2222222222222222, 0.22222213526561355, 0.3091787439613527], + [0.23611111111111108, 0.2361110187197144, 0.3285024154589372], + [0.25, 0.24999990217381526, 0.3478260869565218], + [0.26388888888888884, 0.2638887856279161, 0.36714975845410636], + [0.2777777777777778, 0.27777766908201695, 0.38647342995169087], + [0.29166666666666663, 0.2916665525361178, 0.4057971014492754], + [0.3055555555555555, 0.3055554359902186, 0.42512077294685996], + [0.3194444444444444, 0.31944443923603627, 0.44444431944451634], + [0.3333333333333333, 0.3385416582030555, 0.45833321145840344], + [0.34722222222222215, 0.35763887717007464, 0.47222210347229054], + [0.3611111111111111, 0.3767360961370938, 0.48611099548617764], + [0.375, 0.395833315104113, 0.49999988750006474], + [0.38888888888888884, 0.4149305340711322, 0.5138887795139518], + [0.40277777777777773, 0.43402775303815133, 0.5277776715278389], + [0.4166666666666666, 0.4531249720051705, 0.5416665635417259], + [0.4305555555555555, 0.47222219097218965, 0.555555455555613], + [0.4444444444444444, 0.49131940993920886, 0.5694443475695001], + [0.4583333333333332, 0.5104166289062279, 0.5833332395833872], + [0.47222222222222215, 0.5295138478732472, 0.5972221315972743], + [0.48611111111111105, 0.5486110668402664, 0.6111110236111614], + [0.5, 0.5677082858072856, 0.6249999156250485], + [0.5138888888888887, 0.5868055047743046, 0.6388888076389355], + [0.5277777777777777, 0.6059027237413239, 0.6527776996528227], + [0.5416666666666666, 0.624999942708343, 0.6666665916667098], + [0.5555555555555556, 0.6440971616753622, 0.6805554836805969], + [0.5694444444444443, 0.6631943806423812, 0.6944443756944839], + [0.5833333333333333, 0.6822915996094006, 0.7083332677083711], + [0.5972222222222221, 0.7013888185764198, 0.7222221597222582], + [0.611111111111111, 0.720486037543439, 0.7361110517361452], + [0.6249999999999998, 0.739583256510458, 0.7499999437500322], + [0.6388888888888888, 0.7586804754774773, 0.7638888357639194], + [0.6527777777777777, 0.7777776944444965, 0.7777777277778065], + [0.6744790494790494, 0.7916666666666666, 0.7916666197916936], + [0.6961804461804459, 0.8055555555555554, 0.8055555118055806], + [0.7178818428818429, 0.8194444444444444, 0.8194444038194678], + [0.7395832395832396, 0.8333333333333333, 0.8333332958333549], + [0.7612846362846363, 0.8472222222222222, 0.8472221878472419], + [0.7829860329860328, 0.8611111111111109, 0.861111079861129], + [0.8046874296874297, 0.875, 0.8749999718750161], + [0.8263888263888264, 0.8888888888888888, 0.8888888638889032], + [0.8480902230902231, 0.9027777777777778, 0.9027777559027903], + [0.8697916197916196, 0.9166666666666665, 0.9166666479166774], + [0.8914930164930165, 0.9305555555555556, 0.9305555399305645], + [0.9131944131944132, 0.9444444444444444, 0.9444444319444516], + [0.9348958098958099, 0.9583333333333334, 0.9583333239583387], + [0.9565972065972064, 0.9722222222222221, 0.9722222159722258], + [0.9782986032986033, 0.9861111111111112, 0.9861111079861129], + [1.0, 1.0, 1.0], + ] + + +def get_jet_base() -> list[RGBColor]: + return [ + [0.0, 0.0, 0.5], + [0.0, 0.0, 0.5721500721500722], + [0.0, 0.0, 0.6443001443001444], + [0.0, 0.0, 0.7164502164502164], + [0.0, 0.0, 0.7886002886002886], + [0.0, 0.0, 0.8607503607503608], + [0.0, 0.0, 0.9329004329004329], + [0.0, 0.0, 1.0], + [0.0, 0.007936507936507936, 1.0], + [0.0, 0.07142857142857142, 1.0], + [0.0, 0.1349206349206349, 1.0], + [0.0, 0.1984126984126984, 1.0], + [0.0, 0.2619047619047619, 1.0], + [0.0, 0.3253968253968254, 1.0], + [0.0, 0.3888888888888889, 1.0], + [0.0, 0.4523809523809524, 1.0], + [0.0, 0.5158730158730159, 1.0], + [0.0, 0.5793650793650794, 1.0], + [0.0, 0.6428571428571429, 1.0], + [0.0, 0.7063492063492064, 1.0], + [0.0, 0.7698412698412699, 1.0], + [0.0, 0.8333333333333334, 1.0], + [0.0, 0.8968253968253969, 0.9703020993343575], + [0.048643113159242315, 0.9603174603174603, 0.9190988223246289], + [0.09984639016897091, 1.0, 0.8678955453149002], + [0.15104966717869953, 1.0, 0.8166922683051716], + [0.20225294418842812, 1.0, 0.765488991295443], + [0.2534562211981567, 1.0, 0.7142857142857144], + [0.30465949820788535, 1.0, 0.6630824372759858], + [0.35586277521761395, 1.0, 0.6118791602662572], + [0.40706605222734255, 1.0, 0.5606758832565285], + [0.45826932923707114, 1.0, 0.5094726062467999], + [0.5094726062467997, 1.0, 0.4582693292370713], + [0.560675883256528, 1.0, 0.40706605222734304], + [0.6118791602662569, 1.0, 0.355862775217614], + [0.6630824372759855, 1.0, 0.3046594982078854], + [0.7142857142857141, 1.0, 0.2534562211981568], + [0.7654889912954423, 1.0, 0.20225294418842854], + [0.8166922683051714, 1.0, 0.1510496671786996], + [0.8678955453149, 1.0, 0.0998463901689709], + [0.9190988223246286, 1.0, 0.0486431131592423], + [0.9703020993343567, 0.9600235155790716, 0.0], + [1.0, 0.9012345679012346, 0.0], + [1.0, 0.8424456202233981, 0.0], + [1.0, 0.7836566725455615, 0.0], + [1.0, 0.7248677248677253, 0.0], + [1.0, 0.6660787771898884, 0.0], + [1.0, 0.6072898295120519, 0.0], + [1.0, 0.5485008818342153, 0.0], + [1.0, 0.48971193415637915, 0.0], + [1.0, 0.4309229864785422, 0.0], + [1.0, 0.3721340388007057, 0.0], + [1.0, 0.3133450911228691, 0.0], + [1.0, 0.25455614344503297, 0.0], + [1.0, 0.19576719576719603, 0.0], + [1.0, 0.13697824808935943, 0.0], + [1.0, 0.07818930041152294, 0.0], + [0.9329004329004335, 0.019400352733686788, 0.0], + [0.8607503607503608, 0.0, 0.0], + [0.7886002886002886, 0.0, 0.0], + [0.7164502164502164, 0.0, 0.0], + [0.6443001443001448, 0.0, 0.0], + [0.5721500721500721, 0.0, 0.0], + [0.5, 0.0, 0.0], + ] + + +def get_winter_base() -> list[RGBColor]: + return [ + [0.0, 0.0, 1.0], + [0.0, 0.015873015873015872, 0.9920634920634921], + [0.0, 0.031746031746031744, 0.9841269841269842], + [0.0, 0.047619047619047616, 0.9761904761904762], + [0.0, 0.06349206349206349, 0.9682539682539683], + [0.0, 0.07936507936507936, 0.9603174603174603], + [0.0, 0.09523809523809523, 0.9523809523809523], + [0.0, 0.1111111111111111, 0.9444444444444444], + [0.0, 0.12698412698412698, 0.9365079365079365], + [0.0, 0.14285714285714285, 0.9285714285714286], + [0.0, 0.15873015873015872, 0.9206349206349207], + [0.0, 0.1746031746031746, 0.9126984126984127], + [0.0, 0.19047619047619047, 0.9047619047619048], + [0.0, 0.20634920634920634, 0.8968253968253969], + [0.0, 0.2222222222222222, 0.8888888888888888], + [0.0, 0.23809523809523808, 0.8809523809523809], + [0.0, 0.25396825396825395, 0.873015873015873], + [0.0, 0.2698412698412698, 0.8650793650793651], + [0.0, 0.2857142857142857, 0.8571428571428572], + [0.0, 0.30158730158730157, 0.8492063492063492], + [0.0, 0.31746031746031744, 0.8412698412698413], + [0.0, 0.3333333333333333, 0.8333333333333334], + [0.0, 0.3492063492063492, 0.8253968253968254], + [0.0, 0.36507936507936506, 0.8174603174603174], + [0.0, 0.38095238095238093, 0.8095238095238095], + [0.0, 0.3968253968253968, 0.8015873015873016], + [0.0, 0.4126984126984127, 0.7936507936507937], + [0.0, 0.42857142857142855, 0.7857142857142857], + [0.0, 0.4444444444444444, 0.7777777777777778], + [0.0, 0.4603174603174603, 0.7698412698412699], + [0.0, 0.47619047619047616, 0.7619047619047619], + [0.0, 0.49206349206349204, 0.753968253968254], + [0.0, 0.5079365079365079, 0.746031746031746], + [0.0, 0.5238095238095237, 0.7380952380952381], + [0.0, 0.5396825396825397, 0.7301587301587302], + [0.0, 0.5555555555555556, 0.7222222222222222], + [0.0, 0.5714285714285714, 0.7142857142857143], + [0.0, 0.5873015873015872, 0.7063492063492064], + [0.0, 0.6031746031746031, 0.6984126984126984], + [0.0, 0.6190476190476191, 0.6904761904761905], + [0.0, 0.6349206349206349, 0.6825396825396826], + [0.0, 0.6507936507936507, 0.6746031746031746], + [0.0, 0.6666666666666666, 0.6666666666666667], + [0.0, 0.6825396825396826, 0.6587301587301587], + [0.0, 0.6984126984126984, 0.6507936507936508], + [0.0, 0.7142857142857142, 0.6428571428571429], + [0.0, 0.7301587301587301, 0.6349206349206349], + [0.0, 0.746031746031746, 0.626984126984127], + [0.0, 0.7619047619047619, 0.6190476190476191], + [0.0, 0.7777777777777777, 0.6111111111111112], + [0.0, 0.7936507936507936, 0.6031746031746033], + [0.0, 0.8095238095238095, 0.5952380952380952], + [0.0, 0.8253968253968254, 0.5873015873015873], + [0.0, 0.8412698412698412, 0.5793650793650794], + [0.0, 0.8571428571428571, 0.5714285714285714], + [0.0, 0.873015873015873, 0.5634920634920635], + [0.0, 0.8888888888888888, 0.5555555555555556], + [0.0, 0.9047619047619047, 0.5476190476190477], + [0.0, 0.9206349206349206, 0.5396825396825398], + [0.0, 0.9365079365079365, 0.5317460317460317], + [0.0, 0.9523809523809523, 0.5238095238095238], + [0.0, 0.9682539682539681, 0.5158730158730159], + [0.0, 0.9841269841269841, 0.5079365079365079], + [0.0, 1.0, 0.5], + ] + + +def get_rainbow_base() -> list[RGBColor]: + return [ + [0.5, 0.0, 1.0], + [0.46825396825396826, 0.049845885660697156, 0.9996891820008162], + [0.4365079365079365, 0.09956784659581665, 0.9987569212189223], + [0.40476190476190477, 0.14904226617617441, 0.9972037971811801], + [0.373015873015873, 0.19814614319939755, 0.9950307753654014], + [0.3412698412698413, 0.24675739769029362, 0.9922392066001721], + [0.30952380952380953, 0.29475517441090415, 0.9888308262251285], + [0.2777777777777778, 0.3420201433256687, 0.984807753012208], + [0.24603174603174605, 0.3884347962746947, 0.9801724878485438], + [0.2142857142857143, 0.4338837391175581, 0.9749279121818236], + [0.18253968253968256, 0.4782539786213182, 0.969077286229078], + [0.1507936507936508, 0.521435203379498, 0.962624246950012], + [0.11904761904761907, 0.563320058063622, 0.9555728057861408], + [0.08730158730158732, 0.6038044103254774, 0.9479273461671318], + [0.05555555555555558, 0.6427876096865393, 0.9396926207859084], + [0.023809523809523836, 0.6801727377709194, 0.9308737486442042], + [0.007936507936507908, 0.7158668492597183, 0.9214762118704076], + [0.03968253968253965, 0.7497812029677341, 0.9115058523116731], + [0.0714285714285714, 0.7818314824680298, 0.9009688679024191], + [0.10317460317460314, 0.8119380057158565, 0.8898718088114687], + [0.13492063492063489, 0.8400259231507714, 0.8782215733702285], + [0.16666666666666663, 0.8660254037844386, 0.8660254037844387], + [0.19841269841269837, 0.8898718088114685, 0.8532908816321557], + [0.23015873015873012, 0.9115058523116731, 0.8400259231507715], + [0.26190476190476186, 0.9308737486442041, 0.8262387743159949], + [0.2936507936507936, 0.9479273461671317, 0.8119380057158566], + [0.32539682539682535, 0.962624246950012, 0.7971325072229225], + [0.3571428571428571, 0.9749279121818236, 0.7818314824680298], + [0.38888888888888884, 0.984807753012208, 0.766044443118978], + [0.4206349206349206, 0.9922392066001721, 0.7497812029677342], + [0.45238095238095233, 0.9972037971811801, 0.7330518718298263], + [0.4841269841269841, 0.9996891820008162, 0.7158668492597184], + [0.5158730158730158, 0.9996891820008162, 0.6982368180860729], + [0.5476190476190474, 0.9972037971811801, 0.6801727377709196], + [0.5793650793650793, 0.9922392066001721, 0.6616858375968595], + [0.6111111111111112, 0.984807753012208, 0.6427876096865394], + [0.6428571428571428, 0.9749279121818236, 0.6234898018587336], + [0.6746031746031744, 0.9626242469500121, 0.6038044103254775], + [0.7063492063492063, 0.9479273461671318, 0.58374367223479], + [0.7380952380952381, 0.9308737486442042, 0.563320058063622], + [0.7698412698412698, 0.9115058523116732, 0.5425462638657594], + [0.8015873015873014, 0.8898718088114688, 0.5214352033794982], + [0.8333333333333333, 0.8660254037844387, 0.5000000000000001], + [0.8650793650793651, 0.8400259231507715, 0.47825397862131824], + [0.8968253968253967, 0.8119380057158566, 0.4562106573531631], + [0.9285714285714284, 0.7818314824680301, 0.43388373911755834], + [0.9603174603174602, 0.7497812029677344, 0.4112871031306117], + [0.9920634920634921, 0.7158668492597186, 0.3884347962746948], + [1.0, 0.6801727377709197, 0.3653410243663952], + [1.0, 0.6427876096865395, 0.3420201433256688], + [1.0, 0.6038044103254777, 0.31848665025168466], + [1.0, 0.5633200580636223, 0.2947551744109043], + [1.0, 0.5214352033794981, 0.27084046814300516], + [1.0, 0.47825397862131847, 0.24675739769029378], + [1.0, 0.43388373911755823, 0.22252093395631445], + [1.0, 0.3884347962746946, 0.19814614319939755], + [1.0, 0.3420201433256689, 0.17364817766693041], + [1.0, 0.2947551744109046, 0.14904226617617464], + [1.0, 0.24675739769029384, 0.12434370464748527], + [1.0, 0.1981461431993976, 0.09956784659581666], + [1.0, 0.14904226617617472, 0.07473009358642439], + [1.0, 0.09956784659581717, 0.04984588566069742], + [1.0, 0.04984588566069748, 0.024930691738073035], + [1.0, 1.2246467991473532e-16, 6.123233995736766e-17], + ] + + +def get_ocean_base() -> list[RGBColor]: + return [ + [0.0, 0.5, 0.0], + [0.0, 0.47619047619047616, 0.015873015873015872], + [0.0, 0.4523809523809524, 0.031746031746031744], + [0.0, 0.4285714285714286, 0.047619047619047616], + [0.0, 0.40476190476190477, 0.06349206349206349], + [0.0, 0.38095238095238093, 0.07936507936507936], + [0.0, 0.35714285714285715, 0.09523809523809523], + [0.0, 0.33333333333333337, 0.1111111111111111], + [0.0, 0.30952380952380953, 0.12698412698412698], + [0.0, 0.2857142857142857, 0.14285714285714285], + [0.0, 0.2619047619047619, 0.15873015873015872], + [0.0, 0.23809523809523814, 0.1746031746031746], + [0.0, 0.2142857142857143, 0.19047619047619047], + [0.0, 0.19047619047619047, 0.20634920634920634], + [0.0, 0.16666666666666669, 0.2222222222222222], + [0.0, 0.1428571428571429, 0.23809523809523808], + [0.0, 0.11904761904761907, 0.25396825396825395], + [0.0, 0.09523809523809523, 0.2698412698412698], + [0.0, 0.07142857142857145, 0.2857142857142857], + [0.0, 0.04761904761904767, 0.30158730158730157], + [0.0, 0.023809523809523836, 0.31746031746031744], + [0.0, 0.0, 0.3333333333333333], + [0.0, 0.023809523809523725, 0.3492063492063492], + [0.0, 0.04761904761904756, 0.36507936507936506], + [0.0, 0.0714285714285714, 0.38095238095238093], + [0.0, 0.09523809523809523, 0.3968253968253968], + [0.0, 0.11904761904761907, 0.4126984126984127], + [0.0, 0.1428571428571428, 0.42857142857142855], + [0.0, 0.16666666666666663, 0.4444444444444444], + [0.0, 0.19047619047619047, 0.4603174603174603], + [0.0, 0.2142857142857142, 0.47619047619047616], + [0.0, 0.23809523809523803, 0.49206349206349204], + [0.0, 0.26190476190476186, 0.5079365079365079], + [0.0, 0.2857142857142856, 0.5238095238095237], + [0.0, 0.30952380952380953, 0.5396825396825397], + [0.0, 0.33333333333333337, 0.5555555555555556], + [0.0, 0.3571428571428571, 0.5714285714285714], + [0.0, 0.3809523809523808, 0.5873015873015872], + [0.0, 0.40476190476190466, 0.6031746031746031], + [0.0, 0.4285714285714286, 0.6190476190476191], + [0.0, 0.45238095238095233, 0.6349206349206349], + [0.0, 0.47619047619047605, 0.6507936507936507], + [0.0, 0.5, 0.6666666666666666], + [0.04761904761904745, 0.5238095238095237, 0.6825396825396826], + [0.0952380952380949, 0.5476190476190474, 0.6984126984126984], + [0.14285714285714235, 0.5714285714285712, 0.7142857142857142], + [0.19047619047619024, 0.5952380952380951, 0.7301587301587301], + [0.23809523809523814, 0.6190476190476191, 0.746031746031746], + [0.2857142857142856, 0.6428571428571428, 0.7619047619047619], + [0.33333333333333304, 0.6666666666666665, 0.7777777777777777], + [0.38095238095238093, 0.6904761904761905, 0.7936507936507936], + [0.4285714285714288, 0.7142857142857144, 0.8095238095238095], + [0.4761904761904763, 0.7380952380952381, 0.8253968253968254], + [0.5238095238095237, 0.7619047619047619, 0.8412698412698412], + [0.5714285714285712, 0.7857142857142856, 0.8571428571428571], + [0.6190476190476191, 0.8095238095238095, 0.873015873015873], + [0.6666666666666665, 0.8333333333333333, 0.8888888888888888], + [0.714285714285714, 0.857142857142857, 0.9047619047619047], + [0.7619047619047619, 0.8809523809523809, 0.9206349206349206], + [0.8095238095238093, 0.9047619047619047, 0.9365079365079365], + [0.8571428571428568, 0.9285714285714284, 0.9523809523809523], + [0.9047619047619042, 0.9523809523809521, 0.9682539682539681], + [0.9523809523809521, 0.976190476190476, 0.9841269841269841], + [1.0, 1.0, 1.0], + ] + + +def get_summer_base() -> list[RGBColor]: + return [ + [0.0, 0.5, 0.4], + [0.015873015873015872, 0.5079365079365079, 0.4], + [0.031746031746031744, 0.5158730158730158, 0.4], + [0.047619047619047616, 0.5238095238095238, 0.4], + [0.06349206349206349, 0.5317460317460317, 0.4], + [0.07936507936507936, 0.5396825396825397, 0.4], + [0.09523809523809523, 0.5476190476190477, 0.4], + [0.1111111111111111, 0.5555555555555556, 0.4], + [0.12698412698412698, 0.5634920634920635, 0.4], + [0.14285714285714285, 0.5714285714285714, 0.4], + [0.15873015873015872, 0.5793650793650793, 0.4], + [0.1746031746031746, 0.5873015873015873, 0.4], + [0.19047619047619047, 0.5952380952380952, 0.4], + [0.20634920634920634, 0.6031746031746031, 0.4], + [0.2222222222222222, 0.6111111111111112, 0.4], + [0.23809523809523808, 0.6190476190476191, 0.4], + [0.25396825396825395, 0.626984126984127, 0.4], + [0.2698412698412698, 0.6349206349206349, 0.4], + [0.2857142857142857, 0.6428571428571428, 0.4], + [0.30158730158730157, 0.6507936507936508, 0.4], + [0.31746031746031744, 0.6587301587301587, 0.4], + [0.3333333333333333, 0.6666666666666666, 0.4], + [0.3492063492063492, 0.6746031746031746, 0.4], + [0.36507936507936506, 0.6825396825396826, 0.4], + [0.38095238095238093, 0.6904761904761905, 0.4], + [0.3968253968253968, 0.6984126984126984, 0.4], + [0.4126984126984127, 0.7063492063492063, 0.4], + [0.42857142857142855, 0.7142857142857143, 0.4], + [0.4444444444444444, 0.7222222222222222, 0.4], + [0.4603174603174603, 0.7301587301587301, 0.4], + [0.47619047619047616, 0.7380952380952381, 0.4], + [0.49206349206349204, 0.746031746031746, 0.4], + [0.5079365079365079, 0.753968253968254, 0.4], + [0.5238095238095237, 0.7619047619047619, 0.4], + [0.5396825396825397, 0.7698412698412698, 0.4], + [0.5555555555555556, 0.7777777777777778, 0.4], + [0.5714285714285714, 0.7857142857142857, 0.4], + [0.5873015873015872, 0.7936507936507936, 0.4], + [0.6031746031746031, 0.8015873015873016, 0.4], + [0.6190476190476191, 0.8095238095238095, 0.4], + [0.6349206349206349, 0.8174603174603174, 0.4], + [0.6507936507936507, 0.8253968253968254, 0.4], + [0.6666666666666666, 0.8333333333333333, 0.4], + [0.6825396825396826, 0.8412698412698413, 0.4], + [0.6984126984126984, 0.8492063492063492, 0.4], + [0.7142857142857142, 0.8571428571428571, 0.4], + [0.7301587301587301, 0.8650793650793651, 0.4], + [0.746031746031746, 0.873015873015873, 0.4], + [0.7619047619047619, 0.8809523809523809, 0.4], + [0.7777777777777777, 0.8888888888888888, 0.4], + [0.7936507936507936, 0.8968253968253967, 0.4], + [0.8095238095238095, 0.9047619047619048, 0.4], + [0.8253968253968254, 0.9126984126984127, 0.4], + [0.8412698412698412, 0.9206349206349206, 0.4], + [0.8571428571428571, 0.9285714285714286, 0.4], + [0.873015873015873, 0.9365079365079365, 0.4], + [0.8888888888888888, 0.9444444444444444, 0.4], + [0.9047619047619047, 0.9523809523809523, 0.4], + [0.9206349206349206, 0.9603174603174602, 0.4], + [0.9365079365079365, 0.9682539682539683, 0.4], + [0.9523809523809523, 0.9761904761904762, 0.4], + [0.9682539682539681, 0.9841269841269841, 0.4], + [0.9841269841269841, 0.9920634920634921, 0.4], + [1.0, 1.0, 0.4], + ] + + +def get_spring_base() -> list[RGBColor]: + return [ + [1.0, 0.0, 1.0], + [1.0, 0.015873015873015872, 0.9841269841269842], + [1.0, 0.031746031746031744, 0.9682539682539683], + [1.0, 0.047619047619047616, 0.9523809523809523], + [1.0, 0.06349206349206349, 0.9365079365079365], + [1.0, 0.07936507936507936, 0.9206349206349207], + [1.0, 0.09523809523809523, 0.9047619047619048], + [1.0, 0.1111111111111111, 0.8888888888888888], + [1.0, 0.12698412698412698, 0.873015873015873], + [1.0, 0.14285714285714285, 0.8571428571428572], + [1.0, 0.15873015873015872, 0.8412698412698413], + [1.0, 0.1746031746031746, 0.8253968253968254], + [1.0, 0.19047619047619047, 0.8095238095238095], + [1.0, 0.20634920634920634, 0.7936507936507937], + [1.0, 0.2222222222222222, 0.7777777777777778], + [1.0, 0.23809523809523808, 0.7619047619047619], + [1.0, 0.25396825396825395, 0.746031746031746], + [1.0, 0.2698412698412698, 0.7301587301587302], + [1.0, 0.2857142857142857, 0.7142857142857143], + [1.0, 0.30158730158730157, 0.6984126984126984], + [1.0, 0.31746031746031744, 0.6825396825396826], + [1.0, 0.3333333333333333, 0.6666666666666667], + [1.0, 0.3492063492063492, 0.6507936507936508], + [1.0, 0.36507936507936506, 0.6349206349206349], + [1.0, 0.38095238095238093, 0.6190476190476191], + [1.0, 0.3968253968253968, 0.6031746031746033], + [1.0, 0.4126984126984127, 0.5873015873015873], + [1.0, 0.42857142857142855, 0.5714285714285714], + [1.0, 0.4444444444444444, 0.5555555555555556], + [1.0, 0.4603174603174603, 0.5396825396825398], + [1.0, 0.47619047619047616, 0.5238095238095238], + [1.0, 0.49206349206349204, 0.5079365079365079], + [1.0, 0.5079365079365079, 0.4920634920634921], + [1.0, 0.5238095238095237, 0.4761904761904763], + [1.0, 0.5396825396825397, 0.46031746031746035], + [1.0, 0.5555555555555556, 0.4444444444444444], + [1.0, 0.5714285714285714, 0.4285714285714286], + [1.0, 0.5873015873015872, 0.4126984126984128], + [1.0, 0.6031746031746031, 0.39682539682539686], + [1.0, 0.6190476190476191, 0.38095238095238093], + [1.0, 0.6349206349206349, 0.3650793650793651], + [1.0, 0.6507936507936507, 0.3492063492063493], + [1.0, 0.6666666666666666, 0.33333333333333337], + [1.0, 0.6825396825396826, 0.31746031746031744], + [1.0, 0.6984126984126984, 0.3015873015873016], + [1.0, 0.7142857142857142, 0.2857142857142858], + [1.0, 0.7301587301587301, 0.2698412698412699], + [1.0, 0.746031746031746, 0.25396825396825395], + [1.0, 0.7619047619047619, 0.23809523809523814], + [1.0, 0.7777777777777777, 0.22222222222222232], + [1.0, 0.7936507936507936, 0.2063492063492064], + [1.0, 0.8095238095238095, 0.19047619047619047], + [1.0, 0.8253968253968254, 0.17460317460317465], + [1.0, 0.8412698412698412, 0.15873015873015883], + [1.0, 0.8571428571428571, 0.1428571428571429], + [1.0, 0.873015873015873, 0.12698412698412698], + [1.0, 0.8888888888888888, 0.11111111111111116], + [1.0, 0.9047619047619047, 0.09523809523809534], + [1.0, 0.9206349206349206, 0.07936507936507942], + [1.0, 0.9365079365079365, 0.06349206349206349], + [1.0, 0.9523809523809523, 0.04761904761904767], + [1.0, 0.9682539682539681, 0.031746031746031855], + [1.0, 0.9841269841269841, 0.015873015873015928], + [1.0, 1.0, 0.0], + ] + + +def get_cool_base() -> list[RGBColor]: + return [ + [0.0, 1.0, 1.0], + [0.015873015873015872, 0.9841269841269842, 1.0], + [0.031746031746031744, 0.9682539682539683, 1.0], + [0.047619047619047616, 0.9523809523809523, 1.0], + [0.06349206349206349, 0.9365079365079365, 1.0], + [0.07936507936507936, 0.9206349206349207, 1.0], + [0.09523809523809523, 0.9047619047619048, 1.0], + [0.1111111111111111, 0.8888888888888888, 1.0], + [0.12698412698412698, 0.873015873015873, 1.0], + [0.14285714285714285, 0.8571428571428572, 1.0], + [0.15873015873015872, 0.8412698412698413, 1.0], + [0.1746031746031746, 0.8253968253968254, 1.0], + [0.19047619047619047, 0.8095238095238095, 1.0], + [0.20634920634920634, 0.7936507936507937, 1.0], + [0.2222222222222222, 0.7777777777777778, 1.0], + [0.23809523809523808, 0.7619047619047619, 1.0], + [0.25396825396825395, 0.746031746031746, 1.0], + [0.2698412698412698, 0.7301587301587302, 1.0], + [0.2857142857142857, 0.7142857142857143, 1.0], + [0.30158730158730157, 0.6984126984126984, 1.0], + [0.31746031746031744, 0.6825396825396826, 1.0], + [0.3333333333333333, 0.6666666666666667, 1.0], + [0.3492063492063492, 0.6507936507936508, 1.0], + [0.36507936507936506, 0.6349206349206349, 1.0], + [0.38095238095238093, 0.6190476190476191, 1.0], + [0.3968253968253968, 0.6031746031746033, 1.0], + [0.4126984126984127, 0.5873015873015873, 1.0], + [0.42857142857142855, 0.5714285714285714, 1.0], + [0.4444444444444444, 0.5555555555555556, 1.0], + [0.4603174603174603, 0.5396825396825398, 1.0], + [0.47619047619047616, 0.5238095238095238, 1.0], + [0.49206349206349204, 0.5079365079365079, 1.0], + [0.5079365079365079, 0.4920634920634921, 1.0], + [0.5238095238095237, 0.4761904761904763, 1.0], + [0.5396825396825397, 0.46031746031746035, 1.0], + [0.5555555555555556, 0.4444444444444444, 1.0], + [0.5714285714285714, 0.4285714285714286, 1.0], + [0.5873015873015872, 0.4126984126984128, 1.0], + [0.6031746031746031, 0.39682539682539686, 1.0], + [0.6190476190476191, 0.38095238095238093, 1.0], + [0.6349206349206349, 0.3650793650793651, 1.0], + [0.6507936507936507, 0.3492063492063493, 1.0], + [0.6666666666666666, 0.33333333333333337, 1.0], + [0.6825396825396826, 0.31746031746031744, 1.0], + [0.6984126984126984, 0.3015873015873016, 1.0], + [0.7142857142857142, 0.2857142857142858, 1.0], + [0.7301587301587301, 0.2698412698412699, 1.0], + [0.746031746031746, 0.25396825396825395, 1.0], + [0.7619047619047619, 0.23809523809523814, 1.0], + [0.7777777777777777, 0.22222222222222232, 1.0], + [0.7936507936507936, 0.2063492063492064, 1.0], + [0.8095238095238095, 0.19047619047619047, 1.0], + [0.8253968253968254, 0.17460317460317465, 1.0], + [0.8412698412698412, 0.15873015873015883, 1.0], + [0.8571428571428571, 0.1428571428571429, 1.0], + [0.873015873015873, 0.12698412698412698, 1.0], + [0.8888888888888888, 0.11111111111111116, 1.0], + [0.9047619047619047, 0.09523809523809534, 1.0], + [0.9206349206349206, 0.07936507936507942, 1.0], + [0.9365079365079365, 0.06349206349206349, 1.0], + [0.9523809523809523, 0.04761904761904767, 1.0], + [0.9682539682539681, 0.031746031746031855, 1.0], + [0.9841269841269841, 0.015873015873015928, 1.0], + [1.0, 0.0, 1.0], + ] + + +def get_hsv_base() -> list[RGBColor]: + return [ + [1.0, 0.0, 0.0], + [1.0, 0.09375009375009374, 0.0], + [1.0, 0.1875001875001875, 0.0], + [1.0, 0.28125028125028123, 0.0], + [1.0, 0.375000375000375, 0.0], + [1.0, 0.4687504687504688, 0.0], + [1.0, 0.5625005625005625, 0.0], + [1.0, 0.6562506562506563, 0.0], + [1.0, 0.75000075000075, 0.0], + [1.0, 0.8437508437508436, 0.0], + [0.9999996874996875, 0.937500625000625, 0.0], + [0.9687489687489689, 1.0, 0.0], + [0.8749988749988751, 1.0, 0.0], + [0.7812487812487814, 1.0, 0.0], + [0.6874986874986876, 1.0, 0.0], + [0.5937485937485938, 1.0, 0.0], + [0.4999984999985, 1.0, 0.0], + [0.4062484062484063, 1.0, 0.0], + [0.3124983124983125, 1.0, 0.0], + [0.21874821874821881, 1.0, 0.0], + [0.12499812499812502, 1.0, 0.0], + [0.031249343749343742, 1.0, 1.3125013125182343e-06], + [0.0, 1.0, 0.0625020624890686], + [0.0, 1.0, 0.15625156561670206], + [0.0, 1.0, 0.2500010687443355], + [0.0, 1.0, 0.34375057187196895], + [0.0, 1.0, 0.43750007499960236], + [0.0, 1.0, 0.5312495781272358], + [0.0, 1.0, 0.6249990812548692], + [0.0, 1.0, 0.7187485843825027], + [0.0, 1.0, 0.8124980875101362], + [0.0, 1.0, 0.9062475906377696], + [0.0, 1.0, 0.999997093765403], + [0.0, 0.9062528125028132, 1.0], + [0.0, 0.8125027187527188, 1.0], + [0.0, 0.718752625002625, 1.0], + [0.0, 0.6250025312525314, 1.0], + [0.0, 0.5312524375024383, 1.0], + [0.0, 0.437502343752344, 1.0], + [0.0, 0.3437522500022503, 1.0], + [0.0, 0.2500021562521566, 1.0], + [0.0, 0.15625206250206347, 1.0], + [0.0, 0.06250196875196912, 1.0], + [0.031249374999375024, 1.2500012499527813e-06, 1.0], + [0.12499821874821886, 0.0, 1.0], + [0.21874831249831198, 0.0, 1.0], + [0.3124984062484064, 0.0, 1.0], + [0.4062484999985002, 0.0, 1.0], + [0.49999859374859396, 0.0, 1.0], + [0.593748687498687, 0.0, 1.0], + [0.6874987812487816, 0.0, 1.0], + [0.7812488749988753, 0.0, 1.0], + [0.8749989687489691, 0.0, 1.0], + [0.9687490624990622, 0.0, 1.0], + [0.9999997187497188, 0.0, 0.9375005625005625], + [1.0, 0.0, 0.8437507500007498], + [1.0, 0.0, 0.7500006562506562], + [1.0, 0.0, 0.656250562500563], + [1.0, 0.0, 0.5625004687504687], + [1.0, 0.0, 0.468750375000375], + [1.0, 0.0, 0.3750002812502812], + [1.0, 0.0, 0.28125018750018815], + [1.0, 0.0, 0.1875000937500937], + [1.0, 0.0, 0.09375], + ] + + +def get_bgr_base() -> list[RGBColor]: + return [ + [0.0, 0.0, 1.0], + [0.031746031746031744, 0.0, 0.9682539682539683], + [0.06349206349206349, 0.0, 0.9365079365079365], + [0.09523809523809523, 0.0, 0.9047619047619048], + [0.12698412698412698, 0.0, 0.873015873015873], + [0.15873015873015872, 0.0, 0.8412698412698413], + [0.19047619047619047, 0.0, 0.8095238095238095], + [0.2222222222222222, 0.0, 0.7777777777777778], + [0.25396825396825395, 0.0, 0.746031746031746], + [0.2857142857142857, 0.0, 0.7142857142857143], + [0.31746031746031744, 0.0, 0.6825396825396826], + [0.3492063492063492, 0.0, 0.6507936507936508], + [0.38095238095238093, 0.0, 0.6190476190476191], + [0.4126984126984127, 0.0, 0.5873015873015873], + [0.4444444444444444, 0.0, 0.5555555555555556], + [0.47619047619047616, 0.0, 0.5238095238095238], + [0.5079365079365079, 0.0, 0.4920634920634921], + [0.5396825396825397, 0.0, 0.46031746031746035], + [0.5714285714285714, 0.0, 0.4285714285714286], + [0.6031746031746031, 0.0, 0.39682539682539686], + [0.6349206349206349, 0.0, 0.3650793650793651], + [0.6666666666666666, 0.0, 0.33333333333333337], + [0.6984126984126984, 0.0, 0.3015873015873016], + [0.7301587301587301, 0.0, 0.2698412698412699], + [0.7619047619047619, 0.0, 0.23809523809523814], + [0.7936507936507936, 0.0, 0.2063492063492064], + [0.8253968253968254, 0.0, 0.17460317460317465], + [0.8571428571428571, 0.0, 0.1428571428571429], + [0.8888888888888888, 0.0, 0.11111111111111116], + [0.9206349206349206, 0.0, 0.07936507936507942], + [0.9523809523809523, 0.0, 0.04761904761904767], + [0.9841269841269841, 0.0, 0.015873015873015928], + [0.9841269841269842, 0.015873015873015872, 0.0], + [0.9523809523809526, 0.047619047619047394, 0.0], + [0.9206349206349207, 0.07936507936507936, 0.0], + [0.8888888888888888, 0.1111111111111111, 0.0], + [0.8571428571428572, 0.14285714285714285, 0.0], + [0.8253968253968256, 0.17460317460317437, 0.0], + [0.7936507936507937, 0.20634920634920634, 0.0], + [0.7619047619047619, 0.23809523809523808, 0.0], + [0.7301587301587302, 0.2698412698412698, 0.0], + [0.6984126984126986, 0.30158730158730135, 0.0], + [0.6666666666666667, 0.3333333333333333, 0.0], + [0.6349206349206349, 0.36507936507936506, 0.0], + [0.6031746031746033, 0.3968253968253968, 0.0], + [0.5714285714285716, 0.4285714285714283, 0.0], + [0.5396825396825398, 0.4603174603174603, 0.0], + [0.5079365079365079, 0.49206349206349204, 0.0], + [0.47619047619047616, 0.5238095238095238, 0.0], + [0.44444444444444464, 0.5555555555555554, 0.0], + [0.4126984126984127, 0.5873015873015873, 0.0], + [0.38095238095238093, 0.6190476190476191, 0.0], + [0.3492063492063492, 0.6507936507936508, 0.0], + [0.31746031746031766, 0.6825396825396823, 0.0], + [0.2857142857142857, 0.7142857142857143, 0.0], + [0.25396825396825395, 0.746031746031746, 0.0], + [0.2222222222222222, 0.7777777777777778, 0.0], + [0.1904761904761907, 0.8095238095238093, 0.0], + [0.15873015873015872, 0.8412698412698413, 0.0], + [0.12698412698412698, 0.873015873015873, 0.0], + [0.09523809523809523, 0.9047619047619048, 0.0], + [0.06349206349206371, 0.9365079365079363, 0.0], + [0.031746031746031744, 0.9682539682539683, 0.0], + [0.0, 1.0, 0.0], + ] + + +def get_pink_base() -> list[RGBColor]: + return [ + [0.1178, 0.0, 0.0], + [0.1958570548040548, 0.10286904261004261, 0.10286904261004261], + [0.2506610896140896, 0.1454790653900654, 0.1454790653900654], + [0.29546811656811656, 0.17817408269208268, 0.17817408269208268], + [0.33432413915213915, 0.20573809713609714, 0.20573809713609714], + [0.3691121589001589, 0.23002210977010978, 0.23002210977010978], + [0.40089217663417664, 0.25197612114012113, 0.25197612114012113], + [0.4303311928571929, 0.27216613153713154, 0.27216613153713154], + [0.4578822078802079, 0.2909571412001412, 0.2909571412001412], + [0.48386722192222187, 0.30860715023715024, 0.30860715023715024], + [0.5085252351702352, 0.3253001587801588, 0.3253001587801588], + [0.5320422477312478, 0.34117816687016683, 0.34117816687016683], + [0.5545632596922597, 0.3563481746121746, 0.3563481746121746], + [0.5762042711412712, 0.370899182013182, 0.370899182013182], + [0.5970612821282821, 0.38490018914018914, 0.38490018914018914], + [0.6172132927402928, 0.39841019599019595, 0.39841019599019595], + [0.6367293029443029, 0.4114762026082026, 0.4114762026082026], + [0.6556633128513129, 0.42413920904920904, 0.42413920904920904], + [0.6740663224523225, 0.4364362152622152, 0.4364362152622152], + [0.6919803317593318, 0.44839522133122134, 0.44839522133122134], + [0.7094413408403408, 0.4600442272202272, 0.4600442272202272], + [0.7264833496713496, 0.471405232953233, 0.471405232953233], + [0.7431343583143583, 0.48249823856823854, 0.48249823856823854], + [0.7594211595051595, 0.4933425567615568, 0.49334224405324406], + [0.766356164952165, 0.517549555000555, 0.5039532493842493], + [0.7732291703251704, 0.5406745543755543, 0.5143442546752547], + [0.7800421756041757, 0.5628495546845547, 0.5245312597662597], + [0.7867961807921808, 0.5841835557145558, 0.5345222648432649], + [0.7934921859201859, 0.6047655573125573, 0.5443312697802698], + [0.800132190994191, 0.6246695593815594, 0.5539662746302746], + [0.806718195960196, 0.6439585618705619, 0.5634362794202794], + [0.8132502008675463, 0.6626875645679968, 0.572750284066388], + [0.8197297991324537, 0.6808994354320032, 0.5819137159336122], + [0.8261598070998071, 0.6986374678594677, 0.5909367293097293], + [0.832538815008815, 0.7159364983284983, 0.5998237422767423], + [0.8388698227318228, 0.7328275270515271, 0.6085807548037548], + [0.8451538303318303, 0.7493375542295543, 0.617212766935767], + [0.8513918378118378, 0.7654925799695799, 0.6257267786357786], + [0.8575838451998452, 0.7813126044996045, 0.63412579002479], + [0.8637308524718524, 0.7968186278556278, 0.642415801039801], + [0.8698348596078597, 0.8120286501696502, 0.6505998117678118], + [0.8758968666358666, 0.8269596715176715, 0.6586818221958222], + [0.8819168735798735, 0.8416246920346919, 0.6666668323148323], + [0.8878958804198804, 0.8560397116997117, 0.6745558422198422], + [0.8938348871588873, 0.8702157306557308, 0.6823548518188519], + [0.8997348937998937, 0.8841637489357488, 0.6900658612018611], + [0.9055969003459003, 0.8978957665557666, 0.6976908703748703], + [0.9114209068159068, 0.9114207835997836, 0.7052338793118793], + [0.9172079131949132, 0.9172079131949132, 0.7271656710196709], + [0.9229579194999195, 0.9229579194999195, 0.7484547019537018], + [0.9286729257049257, 0.9286729257049257, 0.7691557308867307], + [0.9343529318399318, 0.9343529318399318, 0.7893137581037581], + [0.939998937893938, 0.939998937893938, 0.8089687837947839], + [0.9456109438799438, 0.9456109438799438, 0.828158808099808], + [0.9511899497889498, 0.9511899497889498, 0.8469128312138313], + [0.9567359556319557, 0.9567359556319557, 0.8652608532158531], + [0.9622499614019614, 0.9622499614019614, 0.8832288742238742], + [0.967732967101967, 0.967732967101967, 0.9008368943518943], + [0.9731849727399727, 0.9731849727399727, 0.9181089136399135], + [0.9786069783119783, 0.9786069783119783, 0.9350609321919323], + [0.9839989838239838, 0.9839989838239838, 0.95171095004995], + [0.9893609892759894, 0.9893609892759894, 0.9680749672719673], + [0.9946949946659946, 0.9946949946659946, 0.984166983907984], + [1.0, 1.0, 1.0], + ] + + +def get_hot_base() -> list[RGBColor]: + return [ + [0.0416, 0.0, 0.0], + [0.0832696068869982, 0.0, 0.0], + [0.12493921377399639, 0.0, 0.0], + [0.16660882066099458, 0.0, 0.0], + [0.20827842754799278, 0.0, 0.0], + [0.24994803443499097, 0.0, 0.0], + [0.2916176413219892, 0.0, 0.0], + [0.33328724820898736, 0.0, 0.0], + [0.37495685509598553, 0.0, 0.0], + [0.4166264619829838, 0.0, 0.0], + [0.458296068869982, 0.0, 0.0], + [0.49996567575698014, 0.0, 0.0], + [0.5416352826439783, 0.0, 0.0], + [0.5833048895309766, 0.0, 0.0], + [0.6249744964179746, 0.0, 0.0], + [0.6666441033049729, 0.0, 0.0], + [0.7083137101919711, 0.0, 0.0], + [0.7499833170789694, 0.0, 0.0], + [0.7916529239659675, 0.0, 0.0], + [0.8333225308529657, 0.0, 0.0], + [0.8749921377399639, 0.0, 0.0], + [0.916661744626962, 0.0, 0.0], + [0.9583313515139603, 0.0, 0.0], + [1.0, 9.583317761411433e-07, 0.0], + [1.0, 0.041667557290219495, 0.0], + [1.0, 0.08333415624866285, 0.0], + [1.0, 0.12500075520710618, 0.0], + [1.0, 0.16666735416554954, 0.0], + [1.0, 0.2083339531239929, 0.0], + [1.0, 0.25000055208243627, 0.0], + [1.0, 0.2916671510408796, 0.0], + [1.0, 0.33333374999932297, 0.0], + [1.0, 0.3750003489577663, 0.0], + [1.0, 0.41666694791620934, 0.0], + [1.0, 0.458333546874653, 0.0], + [1.0, 0.5000001458330964, 0.0], + [1.0, 0.5416667447915398, 0.0], + [1.0, 0.5833333437499828, 0.0], + [1.0, 0.6249999427084264, 0.0], + [1.0, 0.6666665416668698, 0.0], + [1.0, 0.7083331406253132, 0.0], + [1.0, 0.7499997395837562, 0.0], + [1.0, 0.7916663385421998, 0.0], + [1.0, 0.8333329375006432, 0.0], + [1.0, 0.8749995364590866, 0.0], + [1.0, 0.9166661354175296, 0.0], + [1.0, 0.9583327343759732, 0.0], + [1.0, 0.9999993333344166, 0.0], + [1.0, 1.0, 0.06249906249906237], + [1.0, 1.0, 0.12499912499912444], + [1.0, 1.0, 0.1874991874991874], + [1.0, 1.0, 0.24999924999924988], + [1.0, 1.0, 0.3124993124993124], + [1.0, 1.0, 0.37499937499937447], + [1.0, 1.0, 0.4374994374994374], + [1.0, 1.0, 0.49999949999949994], + [1.0, 1.0, 0.5624995624995625], + [1.0, 1.0, 0.6249996249996245], + [1.0, 1.0, 0.6874996874996875], + [1.0, 1.0, 0.7499997499997499], + [1.0, 1.0, 0.8124998124998125], + [1.0, 1.0, 0.8749998749998745], + [1.0, 1.0, 0.9374999374999375], + [1.0, 1.0, 1.0], + ] + + +def get_plasma_base() -> list[RGBColor]: + return [ + [0.050383, 0.029803, 0.527975], + [0.096379, 0.025165, 0.547103], + [0.132381, 0.022258, 0.56325], + [0.16407, 0.020171, 0.577478], + [0.193374, 0.018354, 0.59033], + [0.221197, 0.016497, 0.602083], + [0.248032, 0.014439, 0.612868], + [0.274191, 0.012109, 0.622722], + [0.299855, 0.009561, 0.631624], + [0.32515, 0.006915, 0.639512], + [0.35015, 0.004382, 0.646298], + [0.374897, 0.002245, 0.651876], + [0.399411, 0.000859, 0.656133], + [0.423689, 0.000646, 0.658956], + [0.447714, 0.00208, 0.66024], + [0.471457, 0.005678, 0.659897], + [0.500678, 0.014055, 0.657088], + [0.523633, 0.024532, 0.652901], + [0.546157, 0.038954, 0.64701], + [0.568201, 0.055778, 0.639477], + [0.589719, 0.072878, 0.630408], + [0.610667, 0.090204, 0.619951], + [0.631017, 0.107699, 0.608287], + [0.650746, 0.125309, 0.595617], + [0.669845, 0.142992, 0.582154], + [0.688318, 0.160709, 0.568103], + [0.706178, 0.178437, 0.553657], + [0.723444, 0.196158, 0.538981], + [0.740143, 0.213864, 0.524216], + [0.756304, 0.231555, 0.509468], + [0.771958, 0.249237, 0.494813], + [0.787133, 0.266922, 0.480307], + [0.805467, 0.289057, 0.462415], + [0.819651, 0.306812, 0.448306], + [0.833422, 0.324635, 0.434366], + [0.846788, 0.342551, 0.420579], + [0.85975, 0.360588, 0.406917], + [0.872303, 0.378774, 0.393355], + [0.884436, 0.397139, 0.37986], + [0.896131, 0.415712, 0.366407], + [0.907365, 0.434524, 0.35297], + [0.918109, 0.453603, 0.339529], + [0.928329, 0.472975, 0.326067], + [0.93799, 0.492667, 0.312575], + [0.947051, 0.512699, 0.299049], + [0.95547, 0.533093, 0.28549], + [0.963203, 0.553865, 0.271909], + [0.970205, 0.575028, 0.258325], + [0.977856, 0.602051, 0.241387], + [0.983041, 0.624131, 0.227937], + [0.987332, 0.646633, 0.214648], + [0.990681, 0.669558, 0.201642], + [0.993032, 0.692907, 0.189084], + [0.994324, 0.716681, 0.177208], + [0.994495, 0.74088, 0.166335], + [0.993482, 0.765499, 0.156891], + [0.991209, 0.790537, 0.149377], + [0.987621, 0.815978, 0.144363], + [0.982653, 0.841812, 0.142303], + [0.976265, 0.868016, 0.143351], + [0.968443, 0.894564, 0.147014], + [0.959276, 0.921407, 0.151566], + [0.949151, 0.948435, 0.152178], + [0.940015, 0.975158, 0.131326], + ] + + +def get_viridis_base() -> list[RGBColor]: + return [ + [0.267004, 0.004874, 0.329415], + [0.272594, 0.025563, 0.353093], + [0.277018, 0.050344, 0.375715], + [0.280267, 0.073417, 0.397163], + [0.282327, 0.094955, 0.417331], + [0.283197, 0.11568, 0.436115], + [0.282884, 0.13592, 0.453427], + [0.281412, 0.155834, 0.469201], + [0.278826, 0.17549, 0.483397], + [0.275191, 0.194905, 0.496005], + [0.270595, 0.214069, 0.507052], + [0.265145, 0.232956, 0.516599], + [0.258965, 0.251537, 0.524736], + [0.252194, 0.269783, 0.531579], + [0.244972, 0.287675, 0.53726], + [0.237441, 0.305202, 0.541921], + [0.227802, 0.326594, 0.546532], + [0.220057, 0.343307, 0.549413], + [0.212395, 0.359683, 0.55171], + [0.204903, 0.375746, 0.553533], + [0.197636, 0.391528, 0.554969], + [0.190631, 0.407061, 0.556089], + [0.183898, 0.422383, 0.556944], + [0.177423, 0.437527, 0.557565], + [0.171176, 0.45253, 0.557965], + [0.165117, 0.467423, 0.558141], + [0.159194, 0.482237, 0.558073], + [0.153364, 0.497, 0.557724], + [0.147607, 0.511733, 0.557049], + [0.141935, 0.526453, 0.555991], + [0.136408, 0.541173, 0.554483], + [0.131172, 0.555899, 0.552459], + [0.125394, 0.574318, 0.549086], + [0.121831, 0.589055, 0.545623], + [0.119738, 0.603785, 0.5414], + [0.119699, 0.61849, 0.536347], + [0.122312, 0.633153, 0.530398], + [0.128087, 0.647749, 0.523491], + [0.137339, 0.662252, 0.515571], + [0.150148, 0.676631, 0.506589], + [0.166383, 0.690856, 0.496502], + [0.185783, 0.704891, 0.485273], + [0.20803, 0.718701, 0.472873], + [0.232815, 0.732247, 0.459277], + [0.259857, 0.745492, 0.444467], + [0.288921, 0.758394, 0.428426], + [0.319809, 0.770914, 0.411152], + [0.35236, 0.783011, 0.392636], + [0.395174, 0.797475, 0.367757], + [0.430983, 0.808473, 0.346476], + [0.468053, 0.818921, 0.323998], + [0.506271, 0.828786, 0.300362], + [0.545524, 0.838039, 0.275626], + [0.585678, 0.846661, 0.249897], + [0.626579, 0.854645, 0.223353], + [0.668054, 0.861999, 0.196293], + [0.709898, 0.868751, 0.169257], + [0.751884, 0.874951, 0.143228], + [0.79376, 0.880678, 0.120005], + [0.83527, 0.886029, 0.102646], + [0.876168, 0.891125, 0.09525], + [0.916242, 0.896091, 0.100717], + [0.9553, 0.901065, 0.118128], + [0.993248, 0.906157, 0.143936], + ] + + +def get_cividis_base() -> list[RGBColor]: + return [ + [0.0, 0.135112, 0.304751], + [0.0, 0.146877, 0.330479], + [0.0, 0.157932, 0.357521], + [0.0, 0.168204, 0.385902], + [0.0, 0.178802, 0.414764], + [0.0, 0.188769, 0.439563], + [0.017852, 0.198528, 0.441248], + [0.068968, 0.209372, 0.438863], + [0.103401, 0.220406, 0.43579], + [0.130669, 0.231458, 0.43284], + [0.154261, 0.242475, 0.43012], + [0.17549, 0.253444, 0.42779], + [0.195057, 0.264372, 0.425924], + [0.213431, 0.275266, 0.42448], + [0.230871, 0.286134, 0.423498], + [0.247605, 0.296986, 0.422917], + [0.267693, 0.310542, 0.422821], + [0.28324, 0.32139, 0.423211], + [0.298421, 0.332247, 0.423973], + [0.313287, 0.34312, 0.42512], + [0.327875, 0.354016, 0.42667], + [0.342246, 0.364939, 0.428559], + [0.356418, 0.375896, 0.430823], + [0.37043, 0.38689, 0.433428], + [0.384268, 0.397928, 0.436475], + [0.397991, 0.409011, 0.439848], + [0.411607, 0.420145, 0.443577], + [0.42512, 0.431334, 0.447692], + [0.438504, 0.44258, 0.452341], + [0.451759, 0.453887, 0.457582], + [0.464947, 0.465241, 0.463395], + [0.478186, 0.476699, 0.468845], + [0.495913, 0.491076, 0.471751], + [0.51054, 0.502643, 0.47255], + [0.525348, 0.514285, 0.47266], + [0.540307, 0.526005, 0.472163], + [0.555393, 0.537807, 0.471147], + [0.570607, 0.549695, 0.469593], + [0.585916, 0.561674, 0.467618], + [0.601354, 0.573743, 0.465074], + [0.616852, 0.585913, 0.462237], + [0.632506, 0.59818, 0.458668], + [0.648222, 0.610553, 0.454801], + [0.664055, 0.623034, 0.450338], + [0.679979, 0.635626, 0.445424], + [0.695985, 0.648334, 0.440072], + [0.712105, 0.66116, 0.434117], + [0.728334, 0.674107, 0.427554], + [0.748772, 0.69047, 0.418448], + [0.765223, 0.703705, 0.410587], + [0.781795, 0.717074, 0.401966], + [0.79848, 0.73058, 0.392597], + [0.815274, 0.744226, 0.382504], + [0.832192, 0.758014, 0.371529], + [0.849223, 0.771947, 0.359729], + [0.866421, 0.786028, 0.346571], + [0.88372, 0.800258, 0.332599], + [0.901195, 0.814639, 0.317021], + [0.918828, 0.829168, 0.29996], + [0.93666, 0.843841, 0.280876], + [0.954725, 0.858646, 0.259365], + [0.973114, 0.87355, 0.234677], + [0.992218, 0.888385, 0.205468], + [0.995737, 0.909344, 0.217772], + ] + + +def get_twilight_base() -> list[RGBColor]: + return [ + [0.8857501584075443, 0.8500092494306783, 0.8879736506427196], + [0.8669601550533358, 0.8510896085314068, 0.8790976697717334], + [0.8403042080595778, 0.8425605950855084, 0.865250882410458], + [0.8046916442981458, 0.8270983878056066, 0.8484244929697402], + [0.7618690793798029, 0.8071194938764749, 0.830266486168872], + [0.7150040307625213, 0.7842648709158119, 0.8131111655994991], + [0.6672147980375281, 0.7595112803730375, 0.7986367465453776], + [0.6209919306481755, 0.733369347989232, 0.7871899462469658], + [0.5778116438998202, 0.7061310615715398, 0.7782534512102552], + [0.5383401557517628, 0.677970811290954, 0.7711273443905772], + [0.5028853540415561, 0.6489721673409526, 0.7652144671817491], + [0.46808490970531597, 0.6153702869579029, 0.7594078989109274], + [0.441912717666964, 0.5846144110017557, 0.7545183888441067], + [0.42037822361396326, 0.5529928715810817, 0.7494412559451894], + [0.40346600333905397, 0.5204784765384003, 0.7437421522356709], + [0.390920175719949, 0.4870552025122304, 0.7369797713388125], + [0.38222094988570376, 0.45272225034283325, 0.7287165614400378], + [0.37662448930806297, 0.41749553747893614, 0.7185245473617611], + [0.37324816143326384, 0.38140848555753937, 0.7059820097480604], + [0.37115856636209105, 0.3445191141023017, 0.6906525358646499], + [0.3694333459127623, 0.3069292355186234, 0.6720505284912062], + [0.3668108554010799, 0.26404857724525643, 0.6464799165290824], + [0.3628764356004103, 0.2258414929328703, 0.6188041741082302], + [0.35641381143126327, 0.18837119869242164, 0.5855320765920552], + [0.3463150717579309, 0.15312802296627787, 0.5457599924248665], + [0.33146154891145124, 0.12244245263391232, 0.4991827458843107], + [0.31129434479712365, 0.0986847719340522, 0.4471931371516162], + [0.28669151388283165, 0.08242987384848069, 0.39331182532243375], + [0.26003895187439957, 0.0722947810433622, 0.3417175669546984], + [0.23433055727563878, 0.0669355996616394, 0.295740099298676], + [0.21237411048541005, 0.06608502466175845, 0.2576516509356954], + [0.1960826032659409, 0.07032122724242362, 0.22874673279569585], + [0.19571853588267552, 0.07215778103960274, 0.21617499187076789], + [0.21625279838647882, 0.06761633027051639, 0.22324568672294431], + [0.2438114972024792, 0.06828985152901187, 0.23550427698321885], + [0.277471508091428, 0.07258296989925478, 0.2512349399594277], + [0.3153587000920581, 0.07942099731524319, 0.2681190407694196], + [0.35573889947341125, 0.08803897435024335, 0.2840695897279818], + [0.39719876876325577, 0.09830232096827862, 0.2974385647628578], + [0.4385637818793154, 0.11077667828375456, 0.30712600062348083], + [0.47877034239726296, 0.12642401401409453, 0.3127417273582196], + [0.5169084880054446, 0.14598463068714407, 0.3147540759228004], + [0.5566322903496934, 0.17269677158182117, 0.31423043195101424], + [0.5889486193554471, 0.19997020971775276, 0.31288922211590126], + [0.6185686525887719, 0.2297879924917992, 0.3120046383872893], + [0.6456734938264543, 0.2615520316161528, 0.31248673753935263], + [0.670399595476762, 0.29486126309253047, 0.3150381395687221], + [0.6928154484676493, 0.32945984647042675, 0.3202754315314667], + [0.7129346683977347, 0.36517570519856757, 0.3288027427038317], + [0.7307482075484517, 0.401868526884681, 0.3412449533046818], + [0.7462661578916344, 0.439392450449735, 0.3582343914230064], + [0.7595711110534006, 0.4775687122205708, 0.380360657784311], + [0.7708809196230247, 0.516168926434691, 0.40808667584648967], + [0.7817418047898184, 0.5597509805259486, 0.44624687186865436], + [0.7904577684772788, 0.5982813427706246, 0.48622257801969754], + [0.7991624518501963, 0.6362837937202919, 0.5313449594256143], + [0.8087321917008969, 0.6734621670219452, 0.5806983480557674], + [0.8198723065045529, 0.7095047497878748, 0.6330385704006711], + [0.8328327718577798, 0.7439727181745988, 0.6868223587464855], + [0.847111955079651, 0.7761188023604716, 0.7401227576280706], + [0.8610711702756552, 0.8047851790981223, 0.7903952966373629], + [0.8721533197845432, 0.8284805282370967, 0.8330486712880828], + [0.8811916987134195, 0.8442906671771735, 0.8635659516866988], + [0.8857115512284565, 0.8500218611585632, 0.8857253899008712], + ] + + +def get_turbo_base() -> list[RGBColor]: + return [ + [0.18995, 0.07176, 0.23217], + [0.2086, 0.11802, 0.34607], + [0.225, 0.16354, 0.45096], + [0.23915, 0.20833, 0.54686], + [0.25107, 0.25237, 0.63374], + [0.26074, 0.29568, 0.71162], + [0.26816, 0.33825, 0.7805], + [0.27334, 0.38008, 0.84037], + [0.27628, 0.42118, 0.89123], + [0.27698, 0.46153, 0.93309], + [0.27543, 0.50115, 0.96594], + [0.27106, 0.54015, 0.9893], + [0.25862, 0.57958, 0.99876], + [0.23874, 0.61931, 0.99485], + [0.21382, 0.65886, 0.97959], + [0.18625, 0.69775, 0.95498], + [0.15173, 0.74472, 0.91416], + [0.12698, 0.78037, 0.8759], + [0.10738, 0.81381, 0.83484], + [0.09532, 0.84455, 0.79299], + [0.0932, 0.87211, 0.75237], + [0.10342, 0.896, 0.715], + [0.12733, 0.91701, 0.67627], + [0.16319, 0.93609, 0.63137], + [0.20877, 0.95304, 0.58199], + [0.2618, 0.96765, 0.52981], + [0.32006, 0.97974, 0.47654], + [0.38127, 0.98909, 0.42386], + [0.44321, 0.99551, 0.37345], + [0.50362, 0.99879, 0.32701], + [0.56026, 0.99873, 0.28623], + [0.61088, 0.99514, 0.2528], + [0.66428, 0.98524, 0.2237], + [0.70553, 0.97255, 0.21032], + [0.74617, 0.95593, 0.20406], + [0.78563, 0.93579, 0.20336], + [0.82333, 0.91253, 0.20663], + [0.85868, 0.88655, 0.2123], + [0.89112, 0.85826, 0.2188], + [0.92004, 0.82806, 0.22456], + [0.94489, 0.79634, 0.228], + [0.96507, 0.76352, 0.22754], + [0.98, 0.73, 0.22161], + [0.98986, 0.69382, 0.21043], + [0.99535, 0.65341, 0.19577], + [0.99672, 0.60977, 0.17842], + [0.99419, 0.56386, 0.15918], + [0.98799, 0.51667, 0.13883], + [0.97545, 0.4574, 0.11305], + [0.96187, 0.41093, 0.0931], + [0.94538, 0.36638, 0.07461], + [0.92623, 0.32473, 0.05837], + [0.90463, 0.28696, 0.04516], + [0.88066, 0.25334, 0.03521], + [0.8538, 0.2217, 0.02677], + [0.82399, 0.19182, 0.01966], + [0.79125, 0.16368, 0.01387], + [0.75556, 0.13731, 0.00942], + [0.71692, 0.11268, 0.00629], + [0.67535, 0.0898, 0.00449], + [0.63082, 0.06868, 0.00401], + [0.58336, 0.04931, 0.00486], + [0.53295, 0.03169, 0.00705], + [0.4796, 0.01583, 0.01055], + ] + + +def get_seismic_base() -> list[RGBColor]: + return [ + [0.0, 0.0, 0.3], + [0.0, 0.0, 0.34444444444444444], + [0.0, 0.0, 0.38888888888888884], + [0.0, 0.0, 0.4333333333333333], + [0.0, 0.0, 0.47777777777777775], + [0.0, 0.0, 0.5222222222222221], + [0.0, 0.0, 0.5666666666666667], + [0.0, 0.0, 0.611111111111111], + [0.0, 0.0, 0.6555555555555554], + [0.0, 0.0, 0.7], + [0.0, 0.0, 0.7444444444444444], + [0.0, 0.0, 0.7888888888888888], + [0.0, 0.0, 0.8333333333333333], + [0.0, 0.0, 0.8777777777777778], + [0.0, 0.0, 0.922222222222222], + [0.0, 0.0, 0.9666666666666666], + [0.015873015873015872, 0.015873015873015872, 1.0], + [0.07936507936507936, 0.07936507936507936, 1.0], + [0.14285714285714285, 0.14285714285714285, 1.0], + [0.20634920634920634, 0.20634920634920634, 1.0], + [0.2698412698412698, 0.2698412698412698, 1.0], + [0.3333333333333333, 0.3333333333333333, 1.0], + [0.3968253968253968, 0.3968253968253968, 1.0], + [0.4603174603174603, 0.4603174603174603, 1.0], + [0.5238095238095238, 0.5238095238095238, 1.0], + [0.5873015873015873, 0.5873015873015873, 1.0], + [0.6507936507936508, 0.6507936507936508, 1.0], + [0.7142857142857143, 0.7142857142857143, 1.0], + [0.7777777777777778, 0.7777777777777778, 1.0], + [0.8412698412698413, 0.8412698412698413, 1.0], + [0.9047619047619048, 0.9047619047619048, 1.0], + [0.9682539682539683, 0.9682539682539683, 1.0], + [1.0, 0.9682539682539683, 0.9682539682539683], + [1.0, 0.9047619047619052, 0.9047619047619052], + [1.0, 0.8412698412698413, 0.8412698412698413], + [1.0, 0.7777777777777778, 0.7777777777777778], + [1.0, 0.7142857142857143, 0.7142857142857143], + [1.0, 0.6507936507936513, 0.6507936507936513], + [1.0, 0.5873015873015873, 0.5873015873015873], + [1.0, 0.5238095238095238, 0.5238095238095238], + [1.0, 0.46031746031746035, 0.46031746031746035], + [1.0, 0.3968253968253973, 0.3968253968253973], + [1.0, 0.33333333333333337, 0.33333333333333337], + [1.0, 0.2698412698412699, 0.2698412698412699], + [1.0, 0.2063492063492064, 0.2063492063492064], + [1.0, 0.14285714285714335, 0.14285714285714335], + [1.0, 0.07936507936507942, 0.07936507936507942], + [1.0, 0.015873015873015928, 0.015873015873015928], + [0.9761904761904762, 0.0, 0.0], + [0.9444444444444446, 0.0, 0.0], + [0.9126984126984127, 0.0, 0.0], + [0.8809523809523809, 0.0, 0.0], + [0.8492063492063492, 0.0, 0.0], + [0.8174603174603177, 0.0, 0.0], + [0.7857142857142857, 0.0, 0.0], + [0.753968253968254, 0.0, 0.0], + [0.7222222222222222, 0.0, 0.0], + [0.6904761904761907, 0.0, 0.0], + [0.6587301587301587, 0.0, 0.0], + [0.626984126984127, 0.0, 0.0], + [0.5952380952380952, 0.0, 0.0], + [0.5634920634920637, 0.0, 0.0], + [0.5317460317460317, 0.0, 0.0], + [0.5, 0.0, 0.0], + ] diff --git a/python_embeded/Lib/site-packages/kornia/color/colormap.py b/python_embeded/Lib/site-packages/kornia/color/colormap.py new file mode 100644 index 0000000000000000000000000000000000000000..b1635b601c9172d6c5c484e8bf6d93711de36861 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/colormap.py @@ -0,0 +1,322 @@ +# 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. +# + +from __future__ import annotations + +from enum import Enum +from typing import Optional, Union + +import torch +from torch.nn.functional import interpolate + +import kornia.color._colormap_data as cm_data +from kornia.color._colormap_data import RGBColor +from kornia.core import Module, Tensor, tensor +from kornia.core.check import KORNIA_CHECK +from kornia.utils.helpers import deprecated + + +class ColorMapType(Enum): + r"""An enumeration for available colormaps. + + List of available colormaps: + + .. image:: _static/img/ColorMapType.png + """ + + autumn = 1 + bone = 2 + jet = 3 + winter = 4 + rainbow = 5 + ocean = 6 + summer = 7 + spring = 8 + cool = 9 + hsv = 10 + brg = 11 + pink = 12 + hot = 13 + plasma = 14 + viridis = 15 + cividis = 16 + twilight = 17 + turbo = 18 + seismic = 19 + + def _load_base(self) -> list[RGBColor]: + r"""Load the base colormap corresponding to the enumeration member. + + Returns: + The base colormap. + + """ + return { + "autumn": cm_data.get_autumn_base, + "bone": cm_data.get_bone_base, + "jet": cm_data.get_jet_base, + "winter": cm_data.get_winter_base, + "rainbow": cm_data.get_rainbow_base, + "ocean": cm_data.get_ocean_base, + "summer": cm_data.get_summer_base, + "spring": cm_data.get_spring_base, + "cool": cm_data.get_cool_base, + "hsv": cm_data.get_hsv_base, + "brg": cm_data.get_bgr_base, + "pink": cm_data.get_pink_base, + "hot": cm_data.get_hot_base, + "plasma": cm_data.get_plasma_base, + "viridis": cm_data.get_viridis_base, + "cividis": cm_data.get_cividis_base, + "twilight": cm_data.get_twilight_base, + "turbo": cm_data.get_turbo_base, + "seismic": cm_data.get_seismic_base, + }[self.name]() + + @classmethod + def list(cls) -> list[str]: + r"""Return a list of names of enumeration members. + + Returns: + A list containing the names of enumeration members. + + """ + return [c.name for c in cls] + + +class ColorMap: + r"""Class to represent a colour map. + + It can be created or selected from the built-in colour map. Please refer to + the `ColorMapType` enum class to view all available colormaps. + + Args: + base: A list of RGB colors to define a new custom colormap or the name of a built-in colormap as str or + using `ColorMapType` class. + num_colors: Number of colors in the colormap. + device: The device to put the generated colormap on. + dtype: The data type of the generated colormap. + + Returns: + An object of the colormap with the num_colors length. + + Examples: + >>> ColorMap(base='viridis', num_colors=8).colors + tensor([[0.2813, 0.2621, 0.2013, 0.1505, 0.1210, 0.2463, 0.5259, 0.8557], + [0.0842, 0.2422, 0.3836, 0.5044, 0.6258, 0.7389, 0.8334, 0.8886], + [0.4072, 0.5207, 0.5543, 0.5574, 0.5334, 0.4519, 0.2880, 0.0989]]) + + Create a color map from the first color (RGB with range[0-1]) to the last one with num_colors length. + >>> ColorMap(base=[[0., 0.5 , 1.0], [1., 0.5, 0.]], num_colors=8).colors + tensor([[0.0000, 0.0000, 0.1250, 0.3750, 0.6250, 0.8750, 1.0000, 1.0000], + [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000], + [1.0000, 1.0000, 0.8750, 0.6250, 0.3750, 0.1250, 0.0000, 0.0000]]) + + """ + + def __init__( + self, + base: Union[list[RGBColor], str, ColorMapType], + num_colors: int = 64, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ) -> None: + super().__init__() + self._dtype = dtype + self._device = device + + if isinstance(base, str): + base = base.lower() + if base not in ColorMapType.list(): + raise ValueError(f"Unsupported colormap: {base}. Available colormaps are {ColorMapType.list()}") + base_colormap_data = ColorMapType[base]._load_base() + self.name = base + elif isinstance(base, ColorMapType): + base_colormap_data = base._load_base() + self.name = base.name + elif isinstance(base, list): + base_colormap_data = base + self.name = "CustomColorMapType" + else: + raise ValueError( + "Base should be one of the available `ColorMapType` or a base colormap data (list[RGBColor])" + ) + + self.colors = self._generate_color_map(base_colormap_data, num_colors) + + def _generate_color_map(self, base_colormap: list[RGBColor], num_colors: int) -> Tensor: + r"""Generate a colormap tensor using interpolation. + + Args: + base_colormap: A list of RGB colors defining the colormap. + num_colors: Number of colors in the colormap. + + Returns: + A tensor representing the colormap. + + """ + tensor_colors = tensor(list(base_colormap), dtype=self._dtype, device=self._device).T + return interpolate(tensor_colors[None, ...], size=num_colors, mode="linear")[0, ...] + + def __len__(self) -> int: + r"""Return the number of colors in the colormap. + + Returns: + Number of colors in the colormap. + + """ + return self.colors.shape[-1] + + +def apply_colormap(input_tensor: Tensor, colormap: ColorMap) -> Tensor: + r"""Apply to a gray tensor a colormap. + + .. image:: _static/img/apply_colormap.png + + Args: + input_tensor: the input tensor of image. + colormap: the colormap desired to be applied to the input tensor. + + Returns: + A RGB tensor with the applied color map into the input_tensor. + + Raises: + ValueError: If `colormap` is not a ColorMap object. + + .. note:: + The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1]. + + Example: + >>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]]) + >>> colormap = ColorMap(base=ColorMapType.autumn) + >>> apply_colormap(input_tensor, colormap) + tensor([[[[1.0000, 1.0000, 1.0000], + [1.0000, 1.0000, 1.0000], + [1.0000, 1.0000, 1.0000]], + + [[0.0000, 0.0159, 0.0159], + [0.0635, 0.1111, 0.1429], + [0.5079, 0.6190, 0.7302]], + + [[0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000]]]]) + + """ + KORNIA_CHECK(isinstance(input_tensor, Tensor), f"`input_tensor` must be a Tensor. Got: {type(input_tensor)}") + valid_types = [torch.half, torch.float, torch.double, torch.uint8, torch.int, torch.long, torch.short] + KORNIA_CHECK( + input_tensor.dtype in valid_types, f"`input_tensor` must be a {valid_types}. Got: {input_tensor.dtype}" + ) + KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input tensor dimension.") + if len(input_tensor.shape) == 3: + input_tensor = input_tensor.unsqueeze_(0) + + B, C, H, W = input_tensor.shape + input_tensor = input_tensor.reshape(B, C, -1) + max_value = 1.0 if input_tensor.max() <= 1.0 else 255.0 + input_tensor = input_tensor.float().div_(max_value) + + colors = colormap.colors.permute(1, 0) + num_colors, channels_cmap = colors.shape + keys = torch.linspace(0.0, 1.0, num_colors - 1, device=input_tensor.device, dtype=input_tensor.dtype) + indices = torch.bucketize(input_tensor, keys).unsqueeze(-1).expand(-1, -1, -1, 3) + + output = torch.gather(colors.expand(B, C, -1, -1), 2, indices) + # (B, C, H*W, channels_cmap) -> (B, C*channels_cmap, H, W) + output = output.permute(0, 1, 3, 2).reshape(B, C * channels_cmap, H, W) + + return output + + +class ApplyColorMap(Module): + r"""Class for applying a colormap to images. + + .. image:: _static/img/ApplyColorMap.png + + Args: + colormap: Either the name of a built-in colormap or a ColorMap object. + num_colors: Number of colors in the colormap. Default is 256. + device: The device to put the generated colormap on. + dtype: The data type of the generated colormap. + + Returns: + A RGB tensor with the applied color map into the input_tensor + + Raises: + ValueError: If `colormap` is not a ColorMap object. + + .. note:: + The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1]. + + Example: + >>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]]) + >>> colormap = ColorMap(base=ColorMapType.autumn) + >>> ApplyColorMap(colormap=colormap)(input_tensor) + tensor([[[[1.0000, 1.0000, 1.0000], + [1.0000, 1.0000, 1.0000], + [1.0000, 1.0000, 1.0000]], + + [[0.0000, 0.0159, 0.0159], + [0.0635, 0.1111, 0.1429], + [0.5079, 0.6190, 0.7302]], + + [[0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 0.0000]]]]) + + """ + + def __init__( + self, + colormap: ColorMap, + ) -> None: + super().__init__() + self.colormap = colormap + + def forward(self, input_tensor: Tensor) -> Tensor: + r"""Apply the colormap to the input tensor. + + Args: + input_tensor: The input tensor representing the grayscale image. + + .. note:: + The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1]. + + Returns: + The output tensor representing the image with the applied colormap. + + """ + return apply_colormap(input_tensor, self.colormap) + + +# Generate complete color map +@deprecated( + "0.7.2", + extra_reason="The `AUTUMN()` class is deprecated and will be removed in next kornia versions (0.8.0 - dec 2024).\ + In favor of using `ColorMap(base='autumn')` instead.", +) +class AUTUMN(ColorMap): + r"""The GNU Octave colormap `autumn`. + + .. image:: _static/img/AUTUMN.png + """ + + def __init__( + self, num_colors: int = 64, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None + ) -> None: + super().__init__(base=ColorMapType.autumn, num_colors=num_colors, device=device, dtype=dtype) diff --git a/python_embeded/Lib/site-packages/kornia/color/gray.py b/python_embeded/Lib/site-packages/kornia/color/gray.py new file mode 100644 index 0000000000000000000000000000000000000000..7974120ff0d3026db78211c48714e8dbc4d65403 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/gray.py @@ -0,0 +1,212 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar, Optional + +import torch + +from kornia.color.rgb import bgr_to_rgb +from kornia.core import ImageModule as Module +from kornia.core import Tensor, concatenate +from kornia.core.check import KORNIA_CHECK_IS_TENSOR + + +def grayscale_to_rgb(image: Tensor) -> Tensor: + r"""Convert a grayscale image to RGB version of image. + + .. image:: _static/img/grayscale_to_rgb.png + + The image data is assumed to be in the range of (0, 1). + + Args: + image: grayscale image tensor to be converted to RGB with shape :math:`(*,1,H,W)`. + + Returns: + RGB version of the image with shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.randn(2, 1, 4, 5) + >>> gray = grayscale_to_rgb(input) # 2x3x4x5 + + """ + KORNIA_CHECK_IS_TENSOR(image) + + if len(image.shape) < 3 or image.shape[-3] != 1: + raise ValueError(f"Input size must have a shape of (*, 1, H, W). Got {image.shape}.") + + return concatenate([image, image, image], -3) + + +def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Tensor: + r"""Convert a RGB image to grayscale version of image. + + .. image:: _static/img/rgb_to_grayscale.png + + The image data is assumed to be in the range of (0, 1). + + Args: + image: RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`. + rgb_weights: Weights that will be applied on each channel (RGB). + The sum of the weights should add up to one. + + Returns: + grayscale version of the image with shape :math:`(*,1,H,W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> gray = rgb_to_grayscale(input) # 2x1x4x5 + + """ + KORNIA_CHECK_IS_TENSOR(image) + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + if rgb_weights is None: + # 8 bit images + if image.dtype == torch.uint8: + rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8) + # floating point images + elif image.dtype in (torch.float16, torch.float32, torch.float64): + rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype) + else: + raise TypeError(f"Unknown data type: {image.dtype}") + else: + # is tensor that we make sure is in the same device/dtype + rgb_weights = rgb_weights.to(image) + + # unpack the color image channels with RGB order + r: Tensor = image[..., 0:1, :, :] + g: Tensor = image[..., 1:2, :, :] + b: Tensor = image[..., 2:3, :, :] + + w_r, w_g, w_b = rgb_weights.unbind() + return w_r * r + w_g * g + w_b * b + + +def bgr_to_grayscale(image: Tensor) -> Tensor: + r"""Convert a BGR image to grayscale. + + The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts. + + Args: + image: BGR image to be converted to grayscale with shape :math:`(*,3,H,W)`. + + Returns: + grayscale version of the image with shape :math:`(*,1,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> gray = bgr_to_grayscale(input) # 2x1x4x5 + + """ + KORNIA_CHECK_IS_TENSOR(image) + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + image_rgb: Tensor = bgr_to_rgb(image) + return rgb_to_grayscale(image_rgb) + + +class GrayscaleToRgb(Module): + r"""Module to convert a grayscale image to RGB version of image. + + The image data is assumed to be in the range of (0, 1). + + Shape: + - image: :math:`(*, 1, H, W)` + - output: :math:`(*, 3, H, W)` + + reference: + https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + Example: + >>> input = torch.rand(2, 1, 4, 5) + >>> rgb = GrayscaleToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return grayscale_to_rgb(image) + + +class RgbToGrayscale(Module): + r"""Module to convert a RGB image to grayscale version of image. + + The image data is assumed to be in the range of (0, 1). + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 1, H, W)` + + reference: + https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> gray = RgbToGrayscale() + >>> output = gray(input) # 2x1x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1] + + def __init__(self, rgb_weights: Optional[Tensor] = None) -> None: + super().__init__() + if rgb_weights is None: + rgb_weights = Tensor([0.299, 0.587, 0.114]) + self.rgb_weights = rgb_weights + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_grayscale(image, rgb_weights=self.rgb_weights) + + +class BgrToGrayscale(Module): + r"""Module to convert a BGR image to grayscale version of image. + + The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 1, H, W)` + + reference: + https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> gray = BgrToGrayscale() + >>> output = gray(input) # 2x1x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return bgr_to_grayscale(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/hls.py b/python_embeded/Lib/site-packages/kornia/color/hls.py new file mode 100644 index 0000000000000000000000000000000000000000..8e9f449cb0e7e61b32bb8cb36d2349a46ebc02f5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/hls.py @@ -0,0 +1,204 @@ +# 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. +# + +from __future__ import annotations + +import math +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, stack, tensor, where + + +def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor: + r"""Convert an RGB image to HLS. + + .. image:: _static/img/rgb_to_hls.png + + The image data is assumed to be in the range of (0, 1). + + NOTE: this method cannot be compiled with JIT in pytohrch < 1.7.0 + + Args: + image: RGB image to be converted to HLS with shape :math:`(*, 3, H, W)`. + eps: epsilon value to avoid div by zero. + + Returns: + HLS version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_hls(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + _RGB2HSL_IDX = tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1 + + _img_max: tuple[Tensor, Tensor] = image.max(-3) + maxc = _img_max[0] + imax = _img_max[1] + minc: Tensor = image.min(-3)[0] + + if image.requires_grad: + l_ = maxc + minc + s = maxc - minc + # weird behaviour with undefined vars in JIT... + # scripting requires image_hls be defined even if it is not used :S + h = l_ # assign to any tensor... + image_hls = l_ # assign to any tensor... + else: + # define the resulting image to avoid the torch.stack([h, l, s]) + # so, h, l and s require inplace operations + # NOTE: stack() increases in a 10% the cost in colab + image_hls = torch.empty_like(image) + h, l_, s = ( + image_hls[..., 0, :, :], + image_hls[..., 1, :, :], + image_hls[..., 2, :, :], + ) + torch.add(maxc, minc, out=l_) # l = max + min + torch.sub(maxc, minc, out=s) # s = max - min + + # precompute image / (max - min) + im = image / (s + eps).unsqueeze(-3) + + # epsilon cannot be inside the torch.where to avoid precision issues + s /= where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation + l_ /= 2 # luminance + + # note that r,g and b were previously div by (max - min) + r, g, b = im[..., 0, :, :], im[..., 1, :, :], im[..., 2, :, :] + # h[imax == 0] = (((g - b) / (max - min)) % 6)[imax == 0] + # h[imax == 1] = (((b - r) / (max - min)) + 2)[imax == 1] + # h[imax == 2] = (((r - g) / (max - min)) + 4)[imax == 2] + cond = imax[..., None, :, :] == _RGB2HSL_IDX + if image.requires_grad: + h = ((g - b) % 6) * cond[..., 0, :, :] + else: + # replacing `torch.mul` with `out=h` with python * operator gives wrong results + torch.mul((g - b) % 6, cond[..., 0, :, :], out=h) + h += (b - r + 2) * cond[..., 1, :, :] + h += (r - g + 4) * cond[..., 2, :, :] + # h = 2.0 * math.pi * (60.0 * h) / 360.0 + h *= math.pi / 3.0 # hue [0, 2*pi] + + if image.requires_grad: + return stack([h, l_, s], -3) + return image_hls + + +def hls_to_rgb(image: Tensor) -> Tensor: + r"""Convert a HLS image to RGB. + + The image data is assumed to be in the range of (0, 1). + + Args: + image: HLS image to be converted to RGB with shape :math:`(*, 3, H, W)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = hls_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + _HLS2RGB = tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1 + + im: Tensor = image.unsqueeze(-4) + h_ch: Tensor = im[..., 0, :, :] + l_ch: Tensor = im[..., 1, :, :] + s_ch: Tensor = im[..., 2, :, :] + h_ch = h_ch * (6 / math.pi) # h * 360 / (2 * math.pi) / 30 + a = s_ch * torch.min(l_ch, 1.0 - l_ch) + + # kr = (0 + h) % 12 + # kg = (8 + h) % 12 + # kb = (4 + h) % 12 + k: Tensor = (h_ch + _HLS2RGB) % 12 + + # l - a * max(min(min(k - 3.0, 9.0 - k), 1), -1) + mink = torch.min(k - 3.0, 9.0 - k) + return torch.addcmul(l_ch, a, mink.clamp_(min=-1.0, max=1.0), value=-1) + + +class RgbToHls(Module): + r"""Convert an image from RGB to HLS. + + The image data is assumed to be in the range of (0, 1). + + Returns: + HLS version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> hls = RgbToHls() + >>> output = hls(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_hls(image) + + +class HlsToRgb(Module): + r"""Convert an image from HLS to RGB. + + The image data is assumed to be in the range of (0, 1). + + Returns: + RGB version of the image. + + Shape: + - input: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Reference: + https://en.wikipedia.org/wiki/HSL_and_HSV + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = HlsToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return hls_to_rgb(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/hsv.py b/python_embeded/Lib/site-packages/kornia/color/hsv.py new file mode 100644 index 0000000000000000000000000000000000000000..6bca3dacbbeca3dc17b6cb3a7c70ab41e865add0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/hsv.py @@ -0,0 +1,176 @@ +# 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. +# + +from __future__ import annotations + +import math +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module + + +def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: + r"""Convert an image from RGB to HSV. + + .. image:: _static/img/rgb_to_hsv.png + + The image data is assumed to be in the range of (0, 1). + + Args: + image: RGB Image to be converted to HSV with shape of :math:`(*, 3, H, W)`. + eps: scalar to enforce numarical stability. + + Returns: + HSV version of the image with shape of :math:`(*, 3, H, W)`. + The H channel values are in the range 0..2pi. S and V are in the range 0..1. + + .. note:: + See a working example `here `__. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_hsv(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + max_rgb, argmax_rgb = image.max(-3) + min_rgb, argmin_rgb = image.min(-3) + deltac = max_rgb - min_rgb + + v = max_rgb + s = deltac / (max_rgb + eps) + + deltac = torch.where(deltac == 0, torch.ones_like(deltac), deltac) + rc, gc, bc = torch.unbind((max_rgb.unsqueeze(-3) - image), dim=-3) + + h1 = bc - gc + h2 = (rc - bc) + 2.0 * deltac + h3 = (gc - rc) + 4.0 * deltac + + h = torch.stack((h1, h2, h3), dim=-3) / deltac.unsqueeze(-3) + h = torch.gather(h, dim=-3, index=argmax_rgb.unsqueeze(-3)).squeeze(-3) + h = (h / 6.0) % 1.0 + h = 2.0 * math.pi * h # we return 0/2pi output + + return torch.stack((h, s, v), dim=-3) + + +def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor: + r"""Convert an image from HSV to RGB. + + The H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1. + + Args: + image: HSV Image to be converted to HSV with shape of :math:`(*, 3, H, W)`. + + Returns: + RGB version of the image with shape of :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = hsv_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + h: torch.Tensor = image[..., 0, :, :] / (2 * math.pi) + s: torch.Tensor = image[..., 1, :, :] + v: torch.Tensor = image[..., 2, :, :] + + hi: torch.Tensor = torch.floor(h * 6) % 6 + f: torch.Tensor = ((h * 6) % 6) - hi + one: torch.Tensor = torch.tensor(1.0, device=image.device, dtype=image.dtype) + p: torch.Tensor = v * (one - s) + q: torch.Tensor = v * (one - f * s) + t: torch.Tensor = v * (one - (one - f) * s) + + hi = hi.long() + indices: torch.Tensor = torch.stack([hi, hi + 6, hi + 12], dim=-3) + out = torch.stack((v, q, p, p, t, v, t, v, v, q, p, p, p, p, t, v, v, q), dim=-3) + out = torch.gather(out, -3, indices) + + return out + + +class RgbToHsv(Module): + r"""Convert an image from RGB to HSV. + + The image data is assumed to be in the range of (0, 1). + + Args: + eps: scalar to enforce numarical stability. + + Returns: + HSV version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> hsv = RgbToHsv() + >>> output = hsv(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def __init__(self, eps: float = 1e-6) -> None: + super().__init__() + self.eps = eps + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return rgb_to_hsv(image, self.eps) + + +class HsvToRgb(Module): + r"""Convert an image from HSV to RGB. + + H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = HsvToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return hsv_to_rgb(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/lab.py b/python_embeded/Lib/site-packages/kornia/color/lab.py new file mode 100644 index 0000000000000000000000000000000000000000..7f66c2f95256812eb1099ab0f04c460d0fd229f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/lab.py @@ -0,0 +1,212 @@ +# 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. +# + +"""The RGB to Lab color transformations were translated from scikit image's rgb2lab and lab2rgb. + +https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16065b595ca9/skimage/color/colorconv.py +""" + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module + +from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb +from .xyz import rgb_to_xyz, xyz_to_rgb + + +def rgb_to_lab(image: torch.Tensor) -> torch.Tensor: + r"""Convert a RGB image to Lab. + + .. image:: _static/img/rgb_to_lab.png + + The input RGB image is assumed to be in the range of :math:`[0, 1]`. Lab + color is computed using the D65 illuminant and Observer 2. + + Args: + image: RGB Image to be converted to Lab with shape :math:`(*, 3, H, W)`. + + Returns: + Lab version of the image with shape :math:`(*, 3, H, W)`. + The L channel values are in the range 0..100. a and b are in the range -128..127. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_lab(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + # Convert from sRGB to Linear RGB + lin_rgb = rgb_to_linear_rgb(image) + + xyz_im: torch.Tensor = rgb_to_xyz(lin_rgb) + + # normalize for D65 white point + xyz_ref_white = torch.tensor([0.95047, 1.0, 1.08883], device=xyz_im.device, dtype=xyz_im.dtype)[..., :, None, None] + xyz_normalized = torch.div(xyz_im, xyz_ref_white) + + threshold = 0.008856 + power = torch.pow(xyz_normalized.clamp(min=threshold), 1 / 3.0) + scale = 7.787 * xyz_normalized + 4.0 / 29.0 + xyz_int = torch.where(xyz_normalized > threshold, power, scale) + + x: torch.Tensor = xyz_int[..., 0, :, :] + y: torch.Tensor = xyz_int[..., 1, :, :] + z: torch.Tensor = xyz_int[..., 2, :, :] + + L: torch.Tensor = (116.0 * y) - 16.0 + a: torch.Tensor = 500.0 * (x - y) + _b: torch.Tensor = 200.0 * (y - z) + + out: torch.Tensor = torch.stack([L, a, _b], dim=-3) + + return out + + +def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor: + r"""Convert a Lab image to RGB. + + The L channel is assumed to be in the range of :math:`[0, 100]`. + a and b channels are in the range of :math:`[-128, 127]`. + + Args: + image: Lab image to be converted to RGB with shape :math:`(*, 3, H, W)`. + clip: Whether to apply clipping to insure output RGB values in range :math:`[0, 1]`. + + Returns: + Lab version of the image with shape :math:`(*, 3, H, W)`. + The output RGB image are in the range of :math:`[0, 1]`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = lab_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + L: torch.Tensor = image[..., 0, :, :] + a: torch.Tensor = image[..., 1, :, :] + _b: torch.Tensor = image[..., 2, :, :] + + fy = (L + 16.0) / 116.0 + fx = (a / 500.0) + fy + fz = fy - (_b / 200.0) + + # if color data out of range: Z < 0 + fz = fz.clamp(min=0.0) + + fxyz = torch.stack([fx, fy, fz], dim=-3) + + # Convert from Lab to XYZ + power = torch.pow(fxyz, 3.0) + scale = (fxyz - 4.0 / 29.0) / 7.787 + xyz = torch.where(fxyz > 0.2068966, power, scale) + + # For D65 white point + xyz_ref_white = torch.tensor([0.95047, 1.0, 1.08883], device=xyz.device, dtype=xyz.dtype)[..., :, None, None] + xyz_im = xyz * xyz_ref_white + + rgbs_im: torch.Tensor = xyz_to_rgb(xyz_im) + + # https://github.com/richzhang/colorization-pytorch/blob/66a1cb2e5258f7c8f374f582acc8b1ef99c13c27/util/util.py#L107 + # rgbs_im = torch.where(rgbs_im < 0, torch.zeros_like(rgbs_im), rgbs_im) + + # Convert from RGB Linear to sRGB + rgb_im = linear_rgb_to_rgb(rgbs_im) + + # Clip to 0,1 https://www.w3.org/Graphics/Color/srgb + if clip: + rgb_im = torch.clamp(rgb_im, min=0.0, max=1.0) + + return rgb_im + + +class RgbToLab(Module): + r"""Convert an image from RGB to Lab. + + The image data is assumed to be in the range of :math:`[0, 1]`. Lab + color is computed using the D65 illuminant and Observer 2. + + Returns: + Lab version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> lab = RgbToLab() + >>> output = lab(input) # 2x3x4x5 + + Reference: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + [2] https://www.easyrgb.com/en/math.php + + [3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1467 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return rgb_to_lab(image) + + +class LabToRgb(Module): + r"""Convert an image from Lab to RGB. + + Returns: + RGB version of the image. Range may not be in :math:`[0, 1]`. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = LabToRgb() + >>> output = rgb(input) # 2x3x4x5 + + References: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + [2] https://www.easyrgb.com/en/math.php + + [3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1518 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: torch.Tensor, clip: bool = True) -> torch.Tensor: + return lab_to_rgb(image, clip) diff --git a/python_embeded/Lib/site-packages/kornia/color/luv.py b/python_embeded/Lib/site-packages/kornia/color/luv.py new file mode 100644 index 0000000000000000000000000000000000000000..79d120d3b59f2dfcdcb1aba3b4378c9b81b2b8d7 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/luv.py @@ -0,0 +1,205 @@ +# 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. +# + +"""The RGB to Luv color transformations were translated from scikit image's rgb2luv and luv2rgb. + +https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16065b595ca9/skimage/color/colorconv.py +""" + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module + +from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb +from .xyz import rgb_to_xyz, xyz_to_rgb + + +def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: + r"""Convert a RGB image to Luv. + + .. image:: _static/img/rgb_to_luv.png + + The image data is assumed to be in the range of :math:`[0, 1]`. Luv + color is computed using the D65 illuminant and Observer 2. + + Args: + image: RGB Image to be converted to Luv with shape :math:`(*, 3, H, W)`. + eps: for numerically stability when dividing. + + Returns: + Luv version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_luv(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + # Convert from sRGB to Linear RGB + lin_rgb = rgb_to_linear_rgb(image) + + xyz_im: torch.Tensor = rgb_to_xyz(lin_rgb) + + x: torch.Tensor = xyz_im[..., 0, :, :] + y: torch.Tensor = xyz_im[..., 1, :, :] + z: torch.Tensor = xyz_im[..., 2, :, :] + + threshold = 0.008856 + L: torch.Tensor = torch.where( + y > threshold, + 116.0 * torch.pow(y.clamp(min=threshold), 1.0 / 3.0) - 16.0, + 903.3 * y, + ) + + # Compute reference white point + xyz_ref_white: tuple[float, float, float] = (0.95047, 1.0, 1.08883) + u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2]) + v_w: float = (9 * xyz_ref_white[1]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2]) + + u_p: torch.Tensor = (4 * x) / (x + 15 * y + 3 * z + eps) + v_p: torch.Tensor = (9 * y) / (x + 15 * y + 3 * z + eps) + + u: torch.Tensor = 13 * L * (u_p - u_w) + v: torch.Tensor = 13 * L * (v_p - v_w) + + out = torch.stack([L, u, v], dim=-3) + + return out + + +def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: + r"""Convert a Luv image to RGB. + + Args: + image: Luv image to be converted to RGB with shape :math:`(*, 3, H, W)`. + eps: for numerically stability when dividing. + + Returns: + Luv version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = luv_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + L: torch.Tensor = image[..., 0, :, :] + u: torch.Tensor = image[..., 1, :, :] + v: torch.Tensor = image[..., 2, :, :] + + # Convert from Luv to XYZ + y: torch.Tensor = torch.where(L > 7.999625, torch.pow((L + 16) / 116, 3.0), L / 903.3) + + # Compute white point + xyz_ref_white: tuple[float, float, float] = (0.95047, 1.0, 1.08883) + u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2]) + v_w: float = (9 * xyz_ref_white[1]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2]) + + a: torch.Tensor = u_w + u / (13 * L + eps) + d: torch.Tensor = v_w + v / (13 * L + eps) + c: torch.Tensor = 3 * y * (5 * d - 3) + + z: torch.Tensor = ((a - 4) * c - 15 * a * d * y) / (12 * d + eps) + x: torch.Tensor = -(c / (d + eps) + 3.0 * z) + + xyz_im: torch.Tensor = torch.stack([x, y, z], -3) + + rgbs_im: torch.Tensor = xyz_to_rgb(xyz_im) + + # Convert from RGB Linear to sRGB + rgb_im = linear_rgb_to_rgb(rgbs_im) + + return rgb_im + + +class RgbToLuv(Module): + r"""Convert an image from RGB to Luv. + + The image data is assumed to be in the range of :math:`[0, 1]`. Luv + color is computed using the D65 illuminant and Observer 2. + + Returns: + Luv version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> luv = RgbToLuv() + >>> output = luv(input) # 2x3x4x5 + + Reference: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + [2] https://www.easyrgb.com/en/math.php + + [3] http://www.poynton.com/ColorFAQ.html + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return rgb_to_luv(image) + + +class LuvToRgb(Module): + r"""Convert an image from Luv to RGB. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = LuvToRgb() + >>> output = rgb(input) # 2x3x4x5 + + References: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + [2] https://www.easyrgb.com/en/math.php + + [3] http://www.poynton.com/ColorFAQ.html + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return luv_to_rgb(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/raw.py b/python_embeded/Lib/site-packages/kornia/color/raw.py new file mode 100644 index 0000000000000000000000000000000000000000..a38ee1f3dd4b274a81ddfcb2377f2f2a62029079 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/raw.py @@ -0,0 +1,379 @@ +# 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. +# + +from __future__ import annotations + +from enum import Enum +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, concatenate +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE + + +class CFA(Enum): + r"""Define the configuration of the color filter array. + + So far only bayer images is supported and the enum sets the pixel order for bayer. Note that this can change due + to things like rotations and cropping of images. Take care if including the translations in pipeline. + This implementations is optimized to be reasonably fast, look better than simple nearest neighbour. + On top of this care is taken to make it reversible going raw -> rgb -> raw. the raw samples remain intact + during conversion and only unknown samples are interpolated. + + The names are based on the OpenCV convention where the BG indicates pixel 1,1 (counting from 0,0) is + blue and its neighbour to the right is green. In that case the top left pixel is red. Other options are GB, RG and + GR + + reference: + https://en.wikipedia.org/wiki/Color_filter_array + """ + + BG = 0 + GB = 1 + RG = 2 + GR = 3 + + +def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor: + r"""Convert a raw bayer image to RGB version of image. + + We are assuming a CFA with 2 green, 1 red, 1 blue. A bilinear interpolation is used for R/G and a fix convolution + for the green pixels. To simplify calculations we expect the Height Width to be evenly divisible by 2. + + The image data is assumed to be in the range of (0, 1). Image H/W is assumed to be evenly divisible by 2. + for simplicity reasons + + Args: + image: raw image to be converted to RGB with shape :math:`(*,1,H,W)`. + cfa: The configuration of the color filter. + + Returns: + RGB version of the image with shape :math:`(*,3,H,W)`. + + Example: + >>> rawinput = torch.randn(2, 1, 4, 6) + >>> rgb = raw_to_rgb(rawinput, CFA.RG) # 2x3x4x6 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if image.dim() < 3 or image.size(-3) != 1: + raise ValueError(f"Input size must have a shape of (*, 1, H, W). Got {image.shape}.") + + if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1: + raise ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}") + + imagesize = image.size() + + image = image.view(-1, 1, image.shape[-2], image.shape[-1]) + + # BG is defined as pel 1,1 being blue, that is the top left is actually green. This matches + # opencv naming so makes sense to keep + if cfa == CFA.BG: + r = image[..., :, ::2, ::2] + b = image[..., :, 1::2, 1::2] + rpad = (0, 1, 0, 1) + bpad = (1, 0, 1, 0) + elif cfa == CFA.GB: + r = image[..., :, ::2, 1::2] + b = image[..., :, 1::2, ::2] + rpad = (1, 0, 0, 1) + bpad = (0, 1, 1, 0) + elif cfa == CFA.RG: + r = image[..., :, 1::2, 1::2] + b = image[..., :, ::2, ::2] + rpad = (1, 0, 1, 0) + bpad = (0, 1, 0, 1) + elif cfa == CFA.GR: + r = image[..., :, 1::2, ::2] + b = image[..., :, ::2, 1::2] + rpad = (0, 1, 1, 0) + bpad = (1, 0, 0, 1) + else: + raise ValueError(f"Unsupported CFA Got {cfa}.") + + # upscaling r and b with bi-linear gives reasonable quality + # Note that depending on where these are sampled we need to pad appropriately + # the bilinear filter will pretty much be based on for example this layout (RG) + # (which needs to be padded bottom right) + # +-+-+ + # |B| | + # | | | + # +-+-+ + # While in this layout we need to pad with additional B samples top left to + # make sure we interpolate from the correct position + # +-+-+ + # | | | + # | |B| + # +-+-+ + # For an image like this (3x2 blue pixels) + # +------+ + # |B B B | + # | | + # |B B B | + # | | + # +------+ + # It needs to be expanded to this (4x3 pixels scaled to 7x5 for correct interpolation) + # +-------+ + # |B B B b| + # | | + # |B B B b| + # | | + # |b b b b| + # +-------+ + # and we crop the area afterwards. This is since the interpolation will be between first and last pixel + # evenly spaced between them while the B/R samples will be missing in the corners were they are assumed to exist + # Further we need to do align_corners to start the interpolation from the middle of the samples in the corners, that + # way we get to keep the known blue samples across the whole image + rpadded = torch.nn.functional.pad(r, list(rpad), "replicate") + bpadded = torch.nn.functional.pad(b, list(bpad), "replicate") + # use explicit padding instead of conv2d padding to be able to use reflect which mirror the correct colors + # for a 2x2 bayer filter + gpadded = torch.nn.functional.pad(image, [1, 1, 1, 1], "reflect") + + r_up = torch.nn.functional.interpolate( + rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True + ) + b_up = torch.nn.functional.interpolate( + bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True + ) + + # remove the extra padding + r_up = torch.nn.functional.pad(r_up, [-x for x in rpad]) + b_up = torch.nn.functional.pad(b_up, [-x for x in bpad]) + + # all unknown pixels are the average of the nearby green samples + kernel = torch.tensor( + [[[[0.0, 0.25, 0.0], [0.25, 0.0, 0.25], [0.0, 0.25, 0.0]]]], dtype=image.dtype, device=image.device + ) + + # This is done on all samples but result for the known green samples is then overwritten by the input + g_up = torch.nn.functional.conv2d(gpadded, kernel) + + # overwrite the already known samples which otherwise have values from r/b + # this depends on the CFA configuration + if cfa == CFA.BG: + g_up[:, :, ::2, 1::2] = image[:, :, ::2, 1::2] + g_up[:, :, 1::2, ::2] = image[:, :, 1::2, ::2] + elif cfa == CFA.GB: + g_up[:, :, ::2, ::2] = image[:, :, ::2, ::2] + g_up[:, :, 1::2, 1::2] = image[:, :, 1::2, 1::2] + elif cfa == CFA.RG: + g_up[:, :, 1::2, ::2] = image[:, :, 1::2, ::2] + g_up[:, :, ::2, 1::2] = image[:, :, ::2, 1::2] + elif cfa == CFA.GR: + g_up[:, :, 1::2, 1::2] = image[:, :, 1::2, 1::2] + g_up[:, :, ::2, ::2] = image[:, :, ::2, ::2] + else: + raise ValueError(f"Unsupported CFA Got {cfa}.") + + r_up = r_up.view(imagesize) + g_up = g_up.view(imagesize) + b_up = b_up.view(imagesize) + + rgb: torch.Tensor = torch.cat([r_up, g_up, b_up], dim=-3) + + return rgb + + +def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor: + r"""Convert a RGB image to RAW version of image with the specified color filter array. + + The image data is assumed to be in the range of (0, 1). + + Args: + image: RGB image to be converted to bayer raw with shape :math:`(*,3,H,W)`. + cfa: Which color filter array do we want the output to mimic. I.e. which pixels are red/green/blue. + + Returns: + raw version of the image with shape :math:`(*,1,H,W)`. + + Example: + >>> rgbinput = torch.rand(2, 3, 4, 6) + >>> raw = rgb_to_raw(rgbinput, CFA.BG) # 2x1x4x6 + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + # pick the tensor with green pixels + # clone to make sure grad works + output: torch.Tensor = image[..., 1:2, :, :].clone() + + # overwrite the r/b positions (depending on the cfa configuration) with blue/red pixels + if cfa == CFA.BG: + output[..., :, ::2, ::2] = image[..., 0:1, ::2, ::2] # red + output[..., :, 1::2, 1::2] = image[..., 2:3, 1::2, 1::2] # blue + elif cfa == CFA.GB: + output[..., :, ::2, 1::2] = image[..., 0:1, ::2, 1::2] # red + output[..., :, 1::2, ::2] = image[..., 2:3, 1::2, ::2] # blue + elif cfa == CFA.RG: + output[..., :, 1::2, 1::2] = image[..., 0:1, 1::2, 1::2] # red + output[..., :, ::2, ::2] = image[..., 2:3, ::2, ::2] # blue + elif cfa == CFA.GR: + output[..., :, 1::2, ::2] = image[..., 0:1, 1::2, ::2] # red + output[..., :, ::2, 1::2] = image[..., 2:3, ::2, 1::2] # blue + + return output + + +def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor: + r"""Convert the raw bayer image to RGB version of it and resize width and height by half. + + This is done efficiently by converting each superpixel of bayer image to the corresponding rgb triplet. + R and B channels of the raw image are left as are, while two G channels of raw image are averaged to obtain the + output G channel. + + We are assuming a CFA with 2 green, 1 red, 1 blue. + The image data is assumed to be in the range of (0, 1). Image H/W is assumed to be evenly divisible by 2 + for simplicity reasons. + + Args: + image: raw image to be converted to RGB and downscaled with shape :math:`(*,1,H,W)`. + cfa: The configuration of the color filter. + + Returns: + downscaled RGB version of the image with shape :math:`(*,3,\frac{H}{2},\frac{W}{2})`. + + Example: + >>> rawinput = torch.randn(2, 1, 4, 6) + >>> rgb = raw_to_rgb_2x2_downscaled(rawinput, CFA.RG) # 2x3x2x3 + + """ + KORNIA_CHECK(isinstance(image, Tensor), "Input type is not a torch.Tensor") + + KORNIA_CHECK_SHAPE(image, ["*", "1", "H", "W"]) + + KORNIA_CHECK( + image.shape[-2] % 2 == 0 and image.shape[-1] % 2 == 0, + f"Input H&W must be evenly disible by 2. Got {image.shape}", + ) + + if cfa == CFA.BG: + r = image[..., :, ::2, ::2] + b = image[..., :, 1::2, 1::2] + g1 = image[..., :, ::2, 1::2] + g2 = image[..., :, 1::2, ::2] + elif cfa == CFA.GB: + r = image[..., :, ::2, 1::2] + b = image[..., :, 1::2, ::2] + g1 = image[..., :, ::2, ::2] + g2 = image[..., :, 1::2, 1::2] + elif cfa == CFA.RG: + r = image[..., :, 1::2, 1::2] + b = image[..., :, ::2, ::2] + g1 = image[..., :, 1::2, ::2] + g2 = image[..., :, ::2, 1::2] + elif cfa == CFA.GR: + r = image[..., :, 1::2, ::2] + b = image[..., :, ::2, 1::2] + g1 = image[..., :, 1::2, 1::2] + g2 = image[..., :, ::2, ::2] + else: + raise ValueError(f"Unsupported CFA Got {cfa}.") + + rgb: Tensor = concatenate([r, (g1 + g2) / 2, b], dim=-3) + + return rgb + + +class RawToRgb(Module): + r"""Module to convert a bayer raw image to RGB version of image. + + The image data is assumed to be in the range of (0, 1). + + Shape: + - image: :math:`(*, 1, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> rawinput = torch.rand(2, 1, 4, 6) + >>> rgb = RawToRgb(CFA.RG) + >>> output = rgb(rawinput) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def __init__(self, cfa: CFA) -> None: + super().__init__() + self.cfa = cfa + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return raw_to_rgb(image, cfa=self.cfa) + + +class RgbToRaw(Module): + r"""Module to convert a RGB image to bayer raw version of image. + + The image data is assumed to be in the range of (0, 1). + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 1, H, W)` + + reference: + https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + Example: + >>> rgbinput = torch.rand(2, 3, 4, 6) + >>> raw = RgbToRaw(CFA.GB) + >>> output = raw(rgbinput) # 2x1x4x6 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1] + + def __init__(self, cfa: CFA) -> None: + super().__init__() + self.cfa = cfa + + def forward(self, image: torch.Tensor) -> torch.Tensor: + return rgb_to_raw(image, cfa=self.cfa) + + +class RawToRgb2x2Downscaled(Module): + r"""Module version of the :func:`raw_to_rgb_2x2_downscaled()` function. + + The image width and height have to be divisible by two. The image + data is assumed to be in the range of (0, 1). + + Shape: + - image: :math:`(*, 1, H, W)` + - output: :math:`(*, 3, \frac{H}{2}, \frac{W}{2})` + + Example: + >>> rawinput = torch.rand(2, 1, 4, 6) + >>> rgb_downscale = RawToRgb2x2Downscaled(CFA.RG) + >>> output = rgb_downscale(rawinput) # 2x3x2x3 + + """ + + def __init__(self, cfa: CFA) -> None: + super().__init__() + self.cfa = cfa + + def forward(self, image: Tensor) -> Tensor: + return raw_to_rgb_2x2_downscaled(image, cfa=self.cfa) diff --git a/python_embeded/Lib/site-packages/kornia/color/rgb.py b/python_embeded/Lib/site-packages/kornia/color/rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c27177af033a646824431732cb6fdc9a072db7 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/rgb.py @@ -0,0 +1,661 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar, Union, cast + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, normalize +from kornia.core.check import KORNIA_CHECK_IS_COLOR + + +def rgb_to_bgr(image: Tensor) -> Tensor: + r"""Convert a RGB image to BGR. + + .. image:: _static/img/rgb_to_bgr.png + + Args: + image: RGB Image to be converted to BGRof of shape :math:`(*,3,H,W)`. + + Returns: + BGR version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_bgr(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + return bgr_to_rgb(image) + + +def bgr_to_rgb(image: Tensor) -> Tensor: + r"""Convert a BGR image to RGB. + + Args: + image: BGR Image to be converted to BGR of shape :math:`(*,3,H,W)`. + + Returns: + RGB version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = bgr_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + # flip image channels + out: Tensor = image.flip(-3) + return out + + +def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor: + r"""Convert an image from RGB to RGBA. + + Args: + image: RGB Image to be converted to RGBA of shape :math:`(*,3,H,W)`. + alpha_val (float, Tensor): A float number for the alpha value or a tensor + of shape :math:`(*,1,H,W)`. + + Returns: + RGBA version of the image with shape :math:`(*,4,H,W)`. + + .. note:: The current functionality is NOT supported by Torchscript. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_rgba(input, 1.) # 2x4x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + if not isinstance(alpha_val, (float, Tensor)): + raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}") + + # add one channel + r, g, b = torch.chunk(image, image.shape[-3], dim=-3) + + a: Tensor = cast(Tensor, alpha_val) + + if isinstance(alpha_val, float): + a = torch.full_like(r, fill_value=float(alpha_val)) + + return torch.cat([r, g, b, a], dim=-3) + + +def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor: + r"""Convert an image from BGR to RGBA. + + Args: + image: BGR Image to be converted to RGBA of shape :math:`(*,3,H,W)`. + alpha_val: A float number for the alpha value or a tensor + of shape :math:`(*,1,H,W)`. + + Returns: + RGBA version of the image with shape :math:`(*,4,H,W)`. + + .. note:: The current functionality is NOT supported by Torchscript. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = bgr_to_rgba(input, 1.) # 2x4x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + if not isinstance(alpha_val, (float, Tensor)): + raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}") + + # convert first to RGB, then add alpha channel + x_rgb: Tensor = bgr_to_rgb(image) + return rgb_to_rgba(x_rgb, alpha_val) + + +def rgba_to_rgb(image: Tensor) -> Tensor: + r"""Convert an image from RGBA to RGB. + + Args: + image: RGBA Image to be converted to RGB of shape :math:`(*,4,H,W)`. + + Returns: + RGB version of the image with shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 4, 4, 5) + >>> output = rgba_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 4: + raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}") + + # unpack channels + r, g, b, a = torch.chunk(image, image.shape[-3], dim=-3) + + # compute new channels + a_one = torch.tensor(1.0) - a + r_new: Tensor = a_one * r + a * r + g_new: Tensor = a_one * g + a * g + b_new: Tensor = a_one * b + a * b + + return torch.cat([r_new, g_new, b_new], dim=-3) + + +def rgba_to_bgr(image: Tensor) -> Tensor: + r"""Convert an image from RGBA to BGR. + + Args: + image: RGBA Image to be converted to BGR of shape :math:`(*,4,H,W)`. + + Returns: + RGB version of the image with shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 4, 4, 5) + >>> output = rgba_to_bgr(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 4: + raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}") + + # convert to RGB first, then to BGR + x_rgb: Tensor = rgba_to_rgb(image) + return rgb_to_bgr(x_rgb) + + +def rgb_to_linear_rgb(image: Tensor) -> Tensor: + r"""Convert an sRGB image to linear RGB. Used in colorspace conversions. + + .. image:: _static/img/rgb_to_linear_rgb.png + + Args: + image: sRGB Image to be converted to linear RGB of shape :math:`(*,3,H,W)`. + + Returns: + linear RGB version of the image with shape of :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_linear_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + lin_rgb: Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92) + + return lin_rgb + + +def linear_rgb_to_rgb(image: Tensor) -> Tensor: + r"""Convert a linear RGB image to sRGB. Used in colorspace conversions. + + Args: + image: linear RGB Image to be converted to sRGB of shape :math:`(*,3,H,W)`. + + Returns: + sRGB version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = linear_rgb_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}") + + threshold = 0.0031308 + rgb: Tensor = torch.where( + image > threshold, 1.055 * torch.pow(image.clamp(min=threshold), 1 / 2.4) - 0.055, 12.92 * image + ) + + return rgb + + +def normals_to_rgb255(image: Tensor) -> Tensor: + r"""Convert surface normals to RGB [0, 255] for visualization purposes. + + Args: + image: surface normals to be converted to RGB with quantization of shape :math:`(*,3,H,W)`. + + Returns: + RGB version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = normals_to_rgb255(input) # 2x3x4x5 + + """ + KORNIA_CHECK_IS_COLOR(image) + rgb255 = (0.5 * (image + 1.0)).clip(0.0, 1.0) * 255 + return rgb255 + + +def rgb_to_rgb255(image: Tensor) -> Tensor: + r"""Convert an image from RGB to RGB [0, 255] for visualization purposes. + + Args: + image: RGB Image to be converted to RGB [0, 255] of shape :math:`(*,3,H,W)`. + + Returns: + RGB version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_rgb255(input) # 2x3x4x5 + + """ + KORNIA_CHECK_IS_COLOR(image) + rgb255 = (image * 255).clip(0.0, 255.0) + return rgb255 + + +def rgb255_to_rgb(image: Tensor) -> Tensor: + r"""Convert an image from RGB [0, 255] to RGB for visualization purposes. + + Args: + image: RGB Image to be converted to RGB of shape :math:`(*,3,H,W)`. + + Returns: + RGB version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb255_to_rgb(input) # 2x3x4x5 + + """ + KORNIA_CHECK_IS_COLOR(image) + rgb = image / 255.0 + return rgb + + +def rgb255_to_normals(image: Tensor) -> Tensor: + r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes. + + Args: + image: RGB Image to be converted to surface normals of shape :math:`(*,3,H,W)`. + + Returns: + surface normals version of the image with shape of shape :math:`(*,3,H,W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb255_to_normals(input) # 2x3x4x5 + + """ + KORNIA_CHECK_IS_COLOR(image) + normals = normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0) + return normals + + +class BgrToRgb(Module): + r"""Convert image from BGR to RGB. + + The image data is assumed to be in the range of (0, 1). + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = BgrToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return bgr_to_rgb(image) + + +class RgbToBgr(Module): + r"""Convert an image from RGB to BGR. + + The image data is assumed to be in the range of (0, 1). + + Returns: + BGR version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> bgr = RgbToBgr() + >>> output = bgr(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_bgr(image) + + +class RgbToRgba(Module): + r"""Convert an image from RGB to RGBA. + + Add an alpha channel to existing RGB image. + + Args: + alpha_val: A float number for the alpha value or a tensor + of shape :math:`(*,1,H,W)`. + + Returns: + Tensor: RGBA version of the image with shape :math:`(*,4,H,W)`. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 4, H, W)` + + .. note:: The current functionality is NOT supported by Torchscript. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgba = RgbToRgba(1.) + >>> output = rgba(input) # 2x4x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1] + + def __init__(self, alpha_val: Union[float, Tensor]) -> None: + super().__init__() + self.alpha_val = alpha_val + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_rgba(image, self.alpha_val) + + +class BgrToRgba(Module): + r"""Convert an image from BGR to RGBA. + + Add an alpha channel to existing RGB image. + + Args: + alpha_val: A float number for the alpha value or a tensor + of shape :math:`(*,1,H,W)`. + + Returns: + RGBA version of the image with shape :math:`(*,4,H,W)`. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 4, H, W)` + + .. note:: The current functionality is NOT supported by Torchscript. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgba = BgrToRgba(1.) + >>> output = rgba(input) # 2x4x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1] + + def __init__(self, alpha_val: Union[float, Tensor]) -> None: + super().__init__() + self.alpha_val = alpha_val + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_rgba(image, self.alpha_val) + + +class RgbaToRgb(Module): + r"""Convert an image from RGBA to RGB. + + Remove an alpha channel from RGB image. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 4, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 4, 4, 5) + >>> rgba = RgbaToRgb() + >>> output = rgba(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgba_to_rgb(image) + + +class RgbaToBgr(Module): + r"""Convert an image from RGBA to BGR. + + Remove an alpha channel from BGR image. + + Returns: + BGR version of the image. + + Shape: + - image: :math:`(*, 4, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 4, 4, 5) + >>> rgba = RgbaToBgr() + >>> output = rgba(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgba_to_bgr(image) + + +class RgbToLinearRgb(Module): + r"""Convert an image from sRGB to linear RGB. + + Reverses the gamma correction of sRGB to get linear RGB values for colorspace conversions. + The image data is assumed to be in the range of :math:`[0, 1]` + + Returns: + Linear RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb_lin = RgbToLinearRgb() + >>> output = rgb_lin(input) # 2x3x4x5 + + References: + [1] https://stackoverflow.com/questions/35952564/convert-rgb-to-srgb + + [2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm + + [3] https://en.wikipedia.org/wiki/SRGB + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_linear_rgb(image) + + +class LinearRgbToRgb(Module): + r"""Convert a linear RGB image to sRGB. + + Applies gamma correction to linear RGB values, at the end of colorspace conversions, to get sRGB. + + Returns: + sRGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> srgb = LinearRgbToRgb() + >>> output = srgb(input) # 2x3x4x5 + + References: + [1] https://stackoverflow.com/questions/35952564/convert-rgb-to-srgb + + [2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm + + [3] https://en.wikipedia.org/wiki/SRGB + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return linear_rgb_to_rgb(image) + + +class NormalsToRgb255(Module): + r"""Convert surface normals to RGB [0, 255] for visualization purposes. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = NormalsToRgb255() + >>> output = rgb(input) # 2x3x4x5 + + """ + + def forward(self, image: Tensor) -> Tensor: + return normals_to_rgb255(image) + + +class RgbToRgb255(Module): + r"""Convert an image from RGB to RGB [0, 255] for visualization purposes. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = RgbToRgb255() + >>> output = rgb(input) # 2x3x4x5 + + """ + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_rgb255(image) + + +class Rgb255ToRgb(Module): + r"""Convert an image from RGB [0, 255] to RGB for visualization purposes. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = Rgb255ToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + def forward(self, image: Tensor) -> Tensor: + return rgb255_to_rgb(image) + + +class Rgb255ToNormals(Module): + r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes. + + Returns: + surface normals version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> normals = Rgb255ToNormals() + >>> output = normals(input) # 2x3x4x5 + + """ + + def forward(self, image: Tensor) -> Tensor: + return rgb255_to_normals(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/sepia.py b/python_embeded/Lib/site-packages/kornia/color/sepia.py new file mode 100644 index 0000000000000000000000000000000000000000..2919afe5a8d638c8a03fcd86953b9cb07c138d2c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/sepia.py @@ -0,0 +1,99 @@ +# 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. +# + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor + + +def sepia_from_rgb(input: Tensor, rescale: bool = True, eps: float = 1e-6) -> Tensor: + r"""Apply to a tensor the sepia filter. + + Args: + input: the input tensor with shape of :math:`(*, C, H, W)`. + rescale: If True, the output tensor will be rescaled (max values be 1. or 255). + eps: scalar to enforce numerical stability. + + Returns: + Tensor: The sepia tensor of same size and numbers of channels + as the input with shape :math:`(*, C, H, W)`. + + Example: + >>> input = torch.ones(3, 1, 1) + >>> sepia_from_rgb(input, rescale=False) + tensor([[[1.3510]], + + [[1.2030]], + + [[0.9370]]]) + + """ + if len(input.shape) < 3 or input.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}") + + r = input[..., 0, :, :] + g = input[..., 1, :, :] + b = input[..., 2, :, :] + + r_out = 0.393 * r + 0.769 * g + 0.189 * b + g_out = 0.349 * r + 0.686 * g + 0.168 * b + b_out = 0.272 * r + 0.534 * g + 0.131 * b + + sepia_out = torch.stack([r_out, g_out, b_out], dim=-3) + + if rescale: + max_values = sepia_out.amax(dim=-1).amax(dim=-1) + sepia_out = sepia_out / (max_values[..., None, None] + eps) + + return sepia_out + + +class Sepia(Module): + r"""Module that apply the sepia filter to tensors. + + Args: + input: the input tensor with shape of :math:`(*, C, H, W)`. + rescale: If True, the output tensor will be rescaled (max values be 1. or 255). + eps: scalar to enforce numerical stability. + + Returns: + Tensor: The sepia tensor of same size and numbers of channels + as the input with shape :math:`(*, C, H, W)`. + + Example: + >>> + >>> input = torch.ones(3, 1, 1) + >>> Sepia(rescale=False)(input) + tensor([[[1.3510]], + + [[1.2030]], + + [[0.9370]]]) + + """ + + def __init__(self, rescale: bool = True, eps: float = 1e-6) -> None: + self.rescale = rescale + self.eps = eps + super().__init__() + + def __repr__(self) -> str: + return self.__class__.__name__ + f"(rescale={self.rescale}, eps={self.eps})" + + def forward(self, input: Tensor) -> Tensor: + return sepia_from_rgb(input, rescale=self.rescale, eps=self.eps) diff --git a/python_embeded/Lib/site-packages/kornia/color/xyz.py b/python_embeded/Lib/site-packages/kornia/color/xyz.py new file mode 100644 index 0000000000000000000000000000000000000000..33821cd311975c6718a54c0d39268aba47b83639 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/xyz.py @@ -0,0 +1,149 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor + + +def rgb_to_xyz(image: Tensor) -> Tensor: + r"""Convert a RGB image to XYZ. + + .. image:: _static/img/rgb_to_xyz.png + + Args: + image: RGB Image to be converted to XYZ with shape :math:`(*, 3, H, W)`. + + Returns: + XYZ version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_xyz(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + r: Tensor = image[..., 0, :, :] + g: Tensor = image[..., 1, :, :] + b: Tensor = image[..., 2, :, :] + + x: Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b + y: Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b + z: Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b + + out: Tensor = torch.stack([x, y, z], -3) + + return out + + +def xyz_to_rgb(image: Tensor) -> Tensor: + r"""Convert a XYZ image to RGB. + + Args: + image: XYZ Image to be converted to RGB with shape :math:`(*, 3, H, W)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = xyz_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + x: Tensor = image[..., 0, :, :] + y: Tensor = image[..., 1, :, :] + z: Tensor = image[..., 2, :, :] + + r: Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z + g: Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z + b: Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z + + out: Tensor = torch.stack([r, g, b], dim=-3) + + return out + + +class RgbToXyz(Module): + r"""Convert an image from RGB to XYZ. + + The image data is assumed to be in the range of (0, 1). + + Returns: + XYZ version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> xyz = RgbToXyz() + >>> output = xyz(input) # 2x3x4x5 + + Reference: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_xyz(image) + + +class XyzToRgb(Module): + r"""Converts an image from XYZ to RGB. + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = XyzToRgb() + >>> output = rgb(input) # 2x3x4x5 + + Reference: + [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return xyz_to_rgb(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/ycbcr.py b/python_embeded/Lib/site-packages/kornia/color/ycbcr.py new file mode 100644 index 0000000000000000000000000000000000000000..7c25c713f873c7b6fabd26d9d1eb301a2cbe19bb --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/ycbcr.py @@ -0,0 +1,179 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor + + +def _rgb_to_y(r: Tensor, g: Tensor, b: Tensor) -> Tensor: + y: Tensor = 0.299 * r + 0.587 * g + 0.114 * b + return y + + +def rgb_to_ycbcr(image: Tensor) -> Tensor: + r"""Convert an RGB image to YCbCr. + + .. image:: _static/img/rgb_to_ycbcr.png + + Args: + image: RGB Image to be converted to YCbCr with shape :math:`(*, 3, H, W)`. + + Returns: + YCbCr version of the image with shape :math:`(*, 3, H, W)`. + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_ycbcr(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + r: Tensor = image[..., 0, :, :] + g: Tensor = image[..., 1, :, :] + b: Tensor = image[..., 2, :, :] + + delta: float = 0.5 + y: Tensor = _rgb_to_y(r, g, b) + cb: Tensor = (b - y) * 0.564 + delta + cr: Tensor = (r - y) * 0.713 + delta + return torch.stack([y, cb, cr], -3) + + +def rgb_to_y(image: Tensor) -> Tensor: + r"""Convert an RGB image to Y. + + Args: + image: RGB Image to be converted to Y with shape :math:`(*, 3, H, W)`. + + Returns: + Y version of the image with shape :math:`(*, 1, H, W)`. + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_y(input) # 2x1x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + r: Tensor = image[..., 0:1, :, :] + g: Tensor = image[..., 1:2, :, :] + b: Tensor = image[..., 2:3, :, :] + + y: Tensor = _rgb_to_y(r, g, b) + return y + + +def ycbcr_to_rgb(image: Tensor) -> Tensor: + r"""Convert an YCbCr image to RGB. + + The image data is assumed to be in the range of (0, 1). + + Args: + image: YCbCr Image to be converted to RGB with shape :math:`(*, 3, H, W)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = ycbcr_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + y: Tensor = image[..., 0, :, :] + cb: Tensor = image[..., 1, :, :] + cr: Tensor = image[..., 2, :, :] + + delta: float = 0.5 + cb_shifted: Tensor = cb - delta + cr_shifted: Tensor = cr - delta + + r: Tensor = y + 1.403 * cr_shifted + g: Tensor = y - 0.714 * cr_shifted - 0.344 * cb_shifted + b: Tensor = y + 1.773 * cb_shifted + return torch.stack([r, g, b], -3).clamp(0, 1) + + +class RgbToYcbcr(Module): + r"""Convert an image from RGB to YCbCr. + + The image data is assumed to be in the range of (0, 1). + + Returns: + YCbCr version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> ycbcr = RgbToYcbcr() + >>> output = ycbcr(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return rgb_to_ycbcr(image) + + +class YcbcrToRgb(Module): + r"""Convert an image from YCbCr to Rgb. + + The image data is assumed to be in the range of (0, 1). + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = YcbcrToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, image: Tensor) -> Tensor: + return ycbcr_to_rgb(image) diff --git a/python_embeded/Lib/site-packages/kornia/color/yuv.py b/python_embeded/Lib/site-packages/kornia/color/yuv.py new file mode 100644 index 0000000000000000000000000000000000000000..ca7d4ed914d5231c131b86e75e1a1d57640037a7 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/color/yuv.py @@ -0,0 +1,503 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor + + +def rgb_to_yuv(image: Tensor) -> Tensor: + r"""Convert an RGB image to YUV. + + .. image:: _static/img/rgb_to_yuv.png + + The image data is assumed to be in the range of :math:`(0, 1)`. The range of the output is of + :math:`(0, 1)` to luma and the ranges of U and V are :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, + respectively. + + The YUV model adopted here follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`. + + Returns: + YUV version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = rgb_to_yuv(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + r: Tensor = image[..., 0, :, :] + g: Tensor = image[..., 1, :, :] + b: Tensor = image[..., 2, :, :] + + y: Tensor = 0.299 * r + 0.587 * g + 0.114 * b + u: Tensor = -0.147 * r - 0.289 * g + 0.436 * b + v: Tensor = 0.615 * r - 0.515 * g - 0.100 * b + + out: Tensor = torch.stack([y, u, v], -3) + + return out + + +def rgb_to_yuv420(image: Tensor) -> tuple[Tensor, Tensor]: + r"""Convert an RGB image to YUV 420 (subsampled). + + Input need to be padded to be evenly divisible by 2 horizontal and vertical. + + The image data is assumed to be in the range of :math:`(0, 1)`. The range of the output is of :math:`(0, 1)` to + luma and the ranges of U and V are :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + The YUV model adopted here follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`. + + Returns: + A Tensor containing the Y plane with shape :math:`(*, 1, H, W)` + A Tensor containing the UV planes with shape :math:`(*, 2, H/2, W/2)` + + Example: + >>> input = torch.rand(2, 3, 4, 6) + >>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3) + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1: + raise ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}") + + yuvimage = rgb_to_yuv(image) + + return ( + yuvimage[..., :1, :, :], + yuvimage[..., 1:3, :, :].unfold(-2, 2, 2).unfold(-2, 2, 2).mean((-1, -2)), + ) + + +def rgb_to_yuv422(image: Tensor) -> tuple[Tensor, Tensor]: + r"""Convert an RGB image to YUV 422 (subsampled). + + Input need to be padded to be evenly divisible by 2 vertical. + + The image data is assumed to be in the range of :math:`(0, 1)`. The range of the output is of + :math:`(0, 1)` to luma and the ranges of U and V are :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, + respectively. + + The YUV model adopted here follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`. + + Returns: + A Tensor containing the Y plane with shape :math:`(*, 1, H, W)` + A Tensor containing the UV planes with shape :math:`(*, 2, H, W/2)` + + Example: + >>> input = torch.rand(2, 3, 4, 6) + >>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3) + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if len(image.shape) < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1: + raise ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}") + + yuvimage = rgb_to_yuv(image) + + return (yuvimage[..., :1, :, :], yuvimage[..., 1:3, :, :].unfold(-1, 2, 2).mean(-1)) + + +def yuv_to_rgb(image: Tensor) -> Tensor: + r"""Convert an YUV image to RGB. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + image: YUV Image to be converted to RGB with shape :math:`(*, 3, H, W)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> output = yuv_to_rgb(input) # 2x3x4x5 + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(image)}") + + if image.dim() < 3 or image.shape[-3] != 3: + raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") + + y: Tensor = image[..., 0, :, :] + u: Tensor = image[..., 1, :, :] + v: Tensor = image[..., 2, :, :] + + r: Tensor = y + 1.14 * v # coefficient for g is 0 + g: Tensor = y + -0.396 * u - 0.581 * v + b: Tensor = y + 2.029 * u # coefficient for b is 0 + + out: Tensor = torch.stack([r, g, b], -3) + + return out + + +def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor: + r"""Convert an YUV420 image to RGB. + + Input need to be padded to be evenly divisible by 2 horizontal and vertical. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + imagey: Y (luma) Image plane to be converted to RGB with shape :math:`(*, 1, H, W)`. + imageuv: UV (chroma) Image planes to be converted to RGB with shape :math:`(*, 2, H/2, W/2)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> inputy = torch.rand(2, 1, 4, 6) + >>> inputuv = torch.rand(2, 2, 2, 3) + >>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6 + + """ + if not isinstance(imagey, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}") + + if not isinstance(imageuv, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}") + + if len(imagey.shape) < 3 or imagey.shape[-3] != 1: + raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}") + + if len(imageuv.shape) < 3 or imageuv.shape[-3] != 2: + raise ValueError(f"Input imageuv size must have a shape of (*, 2, H/2, W/2). Got {imageuv.shape}") + + if len(imagey.shape) < 2 or imagey.shape[-2] % 2 == 1 or imagey.shape[-1] % 2 == 1: + raise ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}") + + if ( + len(imageuv.shape) < 2 + or len(imagey.shape) < 2 + or imagey.shape[-2] / imageuv.shape[-2] != 2 + or imagey.shape[-1] / imageuv.shape[-1] != 2 + ): + raise ValueError( + f"Input imageuv H&W must be half the size of the luma plane. Got {imagey.shape} and {imageuv.shape}" + ) + + # first upsample + yuv444image = torch.cat( + [imagey, imageuv.repeat_interleave(2, dim=-1).repeat_interleave(2, dim=-2)], + dim=-3, + ) + # then convert the yuv444 tensor + + return yuv_to_rgb(yuv444image) + + +def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor: + r"""Convert an YUV422 image to RGB. + + Input need to be padded to be evenly divisible by 2 vertical. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Args: + imagey: Y (luma) Image plane to be converted to RGB with shape :math:`(*, 1, H, W)`. + imageuv: UV (luma) Image planes to be converted to RGB with shape :math:`(*, 2, H, W/2)`. + + Returns: + RGB version of the image with shape :math:`(*, 3, H, W)`. + + Example: + >>> inputy = torch.rand(2, 1, 4, 6) + >>> inputuv = torch.rand(2, 2, 2, 3) + >>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5 + + """ + if not isinstance(imagey, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}") + + if not isinstance(imageuv, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}") + + if len(imagey.shape) < 3 or imagey.shape[-3] != 1: + raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}") + + if len(imageuv.shape) < 3 or imageuv.shape[-3] != 2: + raise ValueError(f"Input imageuv size must have a shape of (*, 2, H, W/2). Got {imageuv.shape}") + + if len(imagey.shape) < 2 or imagey.shape[-2] % 2 == 1 or imagey.shape[-1] % 2 == 1: + raise ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}") + + if len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-1] / imageuv.shape[-1] != 2: + raise ValueError( + f"Input imageuv W must be half the size of the luma plane. Got {imagey.shape} and {imageuv.shape}" + ) + + # first upsample + yuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1)], dim=-3) + # then convert the yuv444 tensor + return yuv_to_rgb(yuv444image) + + +class RgbToYuv(Module): + r"""Convert an image from RGB to YUV. + + The image data is assumed to be in the range of :math:`(0, 1)`. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + YUV version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> yuv = RgbToYuv() + >>> output = yuv(input) # 2x3x4x5 + + Reference:: + [1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, input: Tensor) -> Tensor: + return rgb_to_yuv(input) + + +class RgbToYuv420(Module): + r"""Convert an image from RGB to YUV420. + + Width and Height evenly divisible by 2. + + The image data is assumed to be in the range of :math:`(0, 1)`. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + YUV420 version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 1, H, W)` and :math:`(*, 2, H/2, W/2)` + + Examples: + >>> yuvinput = torch.rand(2, 3, 4, 6) + >>> yuv = RgbToYuv420() + >>> output = yuv(yuvinput) # # (2x1x4x6, 2x1x2x3) + + Reference:: + [1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV + + """ + + # TODO: Handle multiple inputs and outputs models later + ONNX_EXPORTABLE = False + + def forward(self, yuvinput: Tensor) -> tuple[Tensor, Tensor]: # skipcq: PYL-R0201 + return rgb_to_yuv420(yuvinput) + + +class RgbToYuv422(Module): + r"""Convert an image from RGB to YUV422. + + Width must be evenly disvisible by 2. + + The image data is assumed to be in the range of :math:`(0, 1)`. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + YUV422 version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 1, H, W)` and :math:`(*, 2, H, W/2)` + + Examples: + >>> yuvinput = torch.rand(2, 3, 4, 6) + >>> yuv = RgbToYuv422() + >>> output = yuv(yuvinput) # # (2x1x4x6, 2x2x4x3) + + Reference:: + [1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV + + """ + + # TODO: Handle multiple inputs and outputs models later + ONNX_EXPORTABLE = False + + def forward(self, yuvinput: Tensor) -> tuple[Tensor, Tensor]: # skipcq: PYL-R0201 + return rgb_to_yuv422(yuvinput) + + +class YuvToRgb(Module): + r"""Convert an image from YUV to RGB. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + RGB version of the image. + + Shape: + - image: :math:`(*, 3, H, W)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> input = torch.rand(2, 3, 4, 5) + >>> rgb = YuvToRgb() + >>> output = rgb(input) # 2x3x4x5 + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def forward(self, input: Tensor) -> Tensor: + return yuv_to_rgb(input) + + +class Yuv420ToRgb(Module): + r"""Convert an image from YUV to RGB. + + Width and Height must be evenly divisible by 2. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + RGB version of the image. + + Shape: + - imagey: :math:`(*, 1, H, W)` + - imageuv: :math:`(*, 2, H/2, W/2)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> inputy = torch.rand(2, 1, 4, 6) + >>> inputuv = torch.rand(2, 2, 2, 3) + >>> rgb = Yuv420ToRgb() + >>> output = rgb(inputy, inputuv) # 2x3x4x6 + + """ + + # TODO: Handle multiple inputs and outputs models later + ONNX_EXPORTABLE = False + + def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201 + return yuv420_to_rgb(inputy, inputuv) + + +class Yuv422ToRgb(Module): + r"""Convert an image from YUV to RGB. + + Width must be evenly divisible by 2. + + The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are + :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively. + + YUV formula follows M/PAL values (see + `BT.470-5 `_, Table 2, + items 2.5 and 2.6). + + Returns: + RGB version of the image. + + Shape: + - imagey: :math:`(*, 1, H, W)` + - imageuv: :math:`(*, 2, H, W/2)` + - output: :math:`(*, 3, H, W)` + + Examples: + >>> inputy = torch.rand(2, 1, 4, 6) + >>> inputuv = torch.rand(2, 2, 4, 3) + >>> rgb = Yuv422ToRgb() + >>> output = rgb(inputy, inputuv) # 2x3x4x6 + + """ + + # TODO: Handle multiple inputs and outputs models later + ONNX_EXPORTABLE = False + + def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201 + return yuv422_to_rgb(inputy, inputuv) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..550344855c9d602cbc65911a2ad84da7053e1a73 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/__init__.py @@ -0,0 +1,61 @@ +# 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. +# + +from .classification import ClassificationHead +from .connected_components import connected_components +from .diamond_square import diamond_square +from .distance_transform import DistanceTransform, distance_transform +from .edge_detection import EdgeDetector +from .extract_patches import ( + CombineTensorPatches, + ExtractTensorPatches, + combine_tensor_patches, + compute_padding, + extract_tensor_patches, +) +from .face_detection import * +from .histogram_matching import histogram_matching, interp +from .image_stitching import ImageStitcher +from .kmeans import KMeans +from .lambda_module import Lambda +from .models.tiny_vit import TinyViT +from .object_detection import ObjectDetector +from .vit import VisionTransformer +from .vit_mobile import MobileViT + +__all__ = [ + "ClassificationHead", + "CombineTensorPatches", + "DistanceTransform", + "EdgeDetector", + "ExtractTensorPatches", + "ImageStitcher", + "KMeans", + "Lambda", + "MobileViT", + "ObjectDetector", + "TinyViT", + "VisionTransformer", + "combine_tensor_patches", + "compute_padding", + "connected_components", + "diamond_square", + "distance_transform", + "extract_tensor_patches", + "histogram_matching", + "interp", +] diff --git a/python_embeded/Lib/site-packages/kornia/contrib/classification.py b/python_embeded/Lib/site-packages/kornia/contrib/classification.py new file mode 100644 index 0000000000000000000000000000000000000000..14d9155b2d163495fd65559bdb93bcde72b12cbe --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/classification.py @@ -0,0 +1,46 @@ +# 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. +# + +"""Module containing utilities for classification.""" + +import torch +from torch import nn + + +class ClassificationHead(nn.Module): + """Module to be used as a classification head. + + Args: + embed_size: the logits tensor coming from the networks. + num_classes: an integer representing the numbers of classes to classify. + + Example: + >>> feat = torch.rand(1, 256, 256) + >>> head = ClassificationHead(256, 10) + >>> head(feat).shape + torch.Size([1, 10]) + + """ + + def __init__(self, embed_size: int = 768, num_classes: int = 10) -> None: + super().__init__() + self.norm = nn.LayerNorm(embed_size) + self.linear = nn.Linear(embed_size, num_classes) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + out = x.mean(-2) + return self.linear(self.norm(out)) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/connected_components.py b/python_embeded/Lib/site-packages/kornia/contrib/connected_components.py new file mode 100644 index 0000000000000000000000000000000000000000..374dc8ff7f62f5627c734c28b57145c4e162f3b7 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/connected_components.py @@ -0,0 +1,76 @@ +# 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. +# + +import torch +import torch.nn.functional as F + +from kornia.core import Tensor + + +def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor: + r"""Compute the Connected-component labelling (CCL) algorithm. + + .. image:: https://github.com/kornia/data/raw/main/cells_segmented.png + + The implementation is an adaptation of the following repository: + + https://gist.github.com/efirdc/5d8bd66859e574c683a504a4690ae8bc + + .. warning:: + This is an experimental API subject to changes and optimization improvements. + + .. note:: + See a working example `here `__. + + Args: + image: the binarized input image with shape :math:`(*, 1, H, W)`. + The image must be in floating point with range [0, 1]. + num_iterations: the number of iterations to make the algorithm to converge. + + Return: + The labels image with the same shape of the input image. + + Example: + >>> img = torch.rand(2, 1, 4, 5) + >>> img_labels = connected_components(img, num_iterations=100) + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Input imagetype is not a Tensor. Got: {type(image)}") + + if not isinstance(num_iterations, int) or num_iterations < 1: + raise TypeError("Input num_iterations must be a positive integer.") + + if len(image.shape) < 3 or image.shape[-3] != 1: + raise ValueError(f"Input image shape must be (*,1,H,W). Got: {image.shape}") + + H, W = image.shape[-2:] + image_view = image.view(-1, 1, H, W) + + # precompute a mask with the valid values + mask = image_view == 1 + + # allocate the output tensors for labels + B, _, _, _ = image_view.shape + out = torch.arange(B * H * W, device=image.device, dtype=image.dtype).view((-1, 1, H, W)) + out[~mask] = 0 + + for _ in range(num_iterations): + out = F.max_pool2d(out, kernel_size=3, stride=1, padding=1) + out = torch.mul(out, mask) # mask using element-wise multiplication + + return out.view_as(image) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/diamond_square.py b/python_embeded/Lib/site-packages/kornia/contrib/diamond_square.py new file mode 100644 index 0000000000000000000000000000000000000000..aaae8e5107a326536fd38ac9c55a06f7fb8046a0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/diamond_square.py @@ -0,0 +1,231 @@ +# 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. +# + +# based on: https://github.com/anguelos/tormentor/blob/e8050ac235b0c7ad3c7d931cfa47c308a305c486/diamond_square/diamond_square.py # noqa: E501 +import math +from typing import Callable, List, Optional, Tuple, Union + +import torch + +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE +from kornia.enhance import normalize_min_max +from kornia.filters import filter2d + +# the default kernels for the diamond square +default_diamond_kernel: List[List[float]] = [[0.25, 0.0, 0.25], [0.0, 0.0, 0.0], [0.25, 0.0, 0.25]] +default_square_kernel: List[List[float]] = [[0.0, 0.25, 0.0], [0.25, 0.0, 0.25], [0.0, 0.25, 0.0]] + + +def _diamond_square_seed( + replicates: int, + width: int, + height: int, + random_fn: Callable[..., Tensor], + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +) -> Tensor: + """Generate the diamond square image seee. + + Args: + replicates: the num of batched replicas for the image. + width: the expected image width. + height: the expected image height. + random_fn: the random function to generate the image seed. + device: the torch device where to create the image seed. + dtype: the torch dtype where to create the image seed. + + Return: + the generated image seed of size Bx1xHxW. + + """ + KORNIA_CHECK(width == 3 or height == 3, "Height or Width must be equal to 3.") + # TODO(anguelos): can we avoid transposing and passing always fixed size. This will cause issues with onnx/jit + transpose: bool = False + if height == 3: + transpose = True + width, height = height, width + + # width is always 3 + KORNIA_CHECK(height % 2 == 1 and height > 2, "Height must be odd and height bigger than 2") + + res: Tensor = random_fn([replicates, 1, width, height], device=device, dtype=dtype) + res[..., ::2, ::2] = random_fn([replicates, 1, 2, (height + 1) // 2], device=device, dtype=dtype) + + # Diamond step + res[..., 1, 1::2] = (res[..., ::2, :-2:2] + res[..., ::2, 2::2]).sum(dim=2) / 4.0 + + # Square step + if width > 3: + res[..., 1, 2:-3:2] = ( + res[..., 0, 2:-3:2] + res[..., 2, 2:-3:2] + res[..., 1, 0:-4:2] + res[..., 1, 2:-3:2] + ) / 4.0 + + tmp1 = res[..., 2, 0] + res[..., 1, 0] = res[..., 0, 0] + res[..., 1, 1] + tmp1 + res[..., 1, -1] = res[..., -1, -1] + res[..., 1, -2] + tmp1 + tmp2 = res[..., 1, 1::2] + res[..., 0, 1::2] = res[..., 0, 0:-2:2] + res[..., 0, 2::2] + tmp2 + res[..., 2, 1::2] = res[..., 2, 0:-2:2] + res[..., 2, 2::2] + tmp2 + res = res / 3.0 + + if transpose: + res = res.transpose(2, 3) + return res + + +def _one_diamond_one_square( + img: Tensor, + random_scale: Union[float, Tensor], + random_fn: Callable[..., Tensor] = torch.rand, + diamond_kernel: Optional[Tensor] = None, + square_kernel: Optional[Tensor] = None, +) -> Tensor: + """Doubles the image resolution by applying a single diamond square steps. + + Recursive application of this method creates plasma fractals. + + Attention! The function is differentiable and gradients are computed as well. + + If this function is run in the usual sense, it is more efficient if it is run in a no_grad() + + Args: + img: a 4D tensor where dimensions are Batch, Channel, Width, Height. Width and Height must both be 2^N+1 and + Batch and Channels should in the usual case be 1. + random_scale: a float number in [0,1] controlling the randomness created pixels get. I the usual case, it is + halved at every application of this function. + random_fn: the random function to generate the image seed. + diamond_kernel: the 3x3 kernel to perform the diamond step. + square_kernel: the 3x3 kernel to perform the square step. + + Return: + A tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1. + + """ + KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"]) + # TODO (anguelos) test multi channel and batch size > 1 + + if diamond_kernel is None: + diamond_kernel = Tensor([default_diamond_kernel]).to(img) # 1x3x3 + if square_kernel is None: + square_kernel = Tensor([default_square_kernel]).to(img) # 1x3x3 + + batch_sz, _, height, width = img.shape + new_img: Tensor = torch.zeros( + [batch_sz, 1, 2 * (height - 1) + 1, 2 * (width - 1) + 1], device=img.device, dtype=img.dtype + ) + new_img[:, :, ::2, ::2] = img + + factor: float = 1.0 / 0.75 + pad_compencate = torch.ones_like(new_img) + pad_compencate[:, :, :, 0] = factor + pad_compencate[:, :, :, -1] = factor + pad_compencate[:, :, 0, :] = factor + pad_compencate[:, :, -1, :] = factor + + random_img: Tensor = random_fn(new_img.size(), device=img.device, dtype=img.dtype) * random_scale + + # TODO(edgar): use kornia.filter2d + # diamond + diamond_regions = filter2d(new_img, diamond_kernel) + diamond_centers = (diamond_regions > 0).to(img.dtype) + # TODO (anguelos) make sure diamond_regions*diamond_centers is needed + new_img = new_img + (1 - random_scale) * diamond_regions * diamond_centers + diamond_centers * random_img + + # square + square_regions = filter2d(new_img, square_kernel) * pad_compencate + square_centers = (square_regions > 0).to(img.dtype) + + # TODO (anguelos) make sure square_centers*square_regions is needed + new_img = new_img + square_centers * random_img + (1 - random_scale) * square_centers * square_regions + + return new_img + + +def diamond_square( + output_size: Tuple[int, int, int, int], + roughness: Union[float, Tensor] = 0.5, + random_scale: Union[float, Tensor] = 1.0, + random_fn: Callable[..., Tensor] = torch.rand, + normalize_range: Optional[Tuple[float, float]] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +) -> Tensor: + """Generate Plasma Fractal Images using the diamond square algorithm. + + See: https://en.wikipedia.org/wiki/Diamond-square_algorithm + + Args: + output_size: a tuple of integers with the BxCxHxW of the image to be generated. + roughness: the scale value to apply at each recursion step. + random_scale: the initial value of the scale for recursion. + random_fn: the callable function to use to sample a random tensor. + normalize_range: whether to normalize using min-max the output map. In case of a + range is specified, min-max norm is applied between the provided range. + device: the torch device to place the output map. + dtype: the torch dtype to place the output map. + + Returns: + A tensor with shape :math:`(B,C,H,W)` containing the fractal image. + + """ + KORNIA_CHECK(len(output_size) == 4, "output_size must be (B,C,H,W)") + if not isinstance(random_scale, Tensor): + random_scale = Tensor([[[[random_scale]]]]).to(device, dtype) + random_scale = random_scale.expand([output_size[0] * output_size[1], 1, 1, 1]) + else: + KORNIA_CHECK_IS_TENSOR(random_scale) + random_scale = random_scale.view(-1, 1, 1, 1) + random_scale = random_scale.expand([output_size[0], output_size[1], 1, 1]) + random_scale = random_scale.reshape([-1, 1, 1, 1]) + + if not isinstance(roughness, Tensor): + roughness = Tensor([[[[roughness]]]]).to(device, dtype) + roughness = roughness.expand([output_size[0] * output_size[1], 1, 1, 1]) + else: + roughness = roughness.view(-1, 1, 1, 1) + roughness = roughness.expand([output_size[0], output_size[1], 1, 1]) + roughness = roughness.reshape([-1, 1, 1, 1]) + + width, height = output_size[-2:] + num_samples: int = 1 + for x in output_size[:-2]: + num_samples *= x + + # compute the image seed + p2_width: float = 2 ** math.ceil(math.log2(width - 1)) + 1 + p2_height: float = 2 ** math.ceil(math.log2(height - 1)) + 1 + recursion_depth: int = int(min(math.log2(p2_width - 1) - 1, math.log2(p2_height - 1) - 1)) + seed_width: int = (p2_width - 1) // 2**recursion_depth + 1 + seed_height: int = (p2_height - 1) // 2**recursion_depth + 1 + img: Tensor = random_scale * _diamond_square_seed(num_samples, seed_width, seed_height, random_fn, device, dtype) + + # perform recursion + scale = random_scale + for _ in range(recursion_depth): + scale = scale * roughness + img = _one_diamond_one_square(img, scale, random_fn) + + # slice to match with the output size + img = img[..., :width, :height] + img = img.view(output_size) + + # normalize the output in the range using min-max + if normalize_range is not None: + min_val, max_val = normalize_range + img = normalize_min_max(img.contiguous(), min_val, max_val) + return img diff --git a/python_embeded/Lib/site-packages/kornia/contrib/distance_transform.py b/python_embeded/Lib/site-packages/kornia/contrib/distance_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..33f246b33f5813c14c9afe6ec6d71fd0832e7b95 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/distance_transform.py @@ -0,0 +1,113 @@ +# 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. +# + +import math + +import torch +from torch import nn + +from kornia.filters import filter2d +from kornia.utils import create_meshgrid + + +def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor: + r"""Approximates the Manhattan distance transform of images using cascaded convolution operations. + + The value at each pixel in the output represents the distance to the nearest non-zero pixel in the image image. + It uses the method described in :cite:`pham2021dtlayer`. + The transformation is applied independently across the channel dimension of the images. + + Args: + image: Image with shape :math:`(B,C,H,W)`. + kernel_size: size of the convolution kernel. + h: value that influence the approximation of the min function. + + Returns: + tensor with shape :math:`(B,C,H,W)`. + + Example: + >>> tensor = torch.zeros(1, 1, 5, 5) + >>> tensor[:,:, 1, 2] = 1 + >>> dt = kornia.contrib.distance_transform(tensor) + + """ + if not isinstance(image, torch.Tensor): + raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}") + + if not len(image.shape) == 4: + raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}") + + if kernel_size % 2 == 0: + raise ValueError("Kernel size must be an odd number.") + + # n_iters is set such that the DT will be able to propagate from any corner of the image to its far, + # diagonally opposite corner + n_iters: int = math.ceil(max(image.shape[2], image.shape[3]) / math.floor(kernel_size / 2)) + grid = create_meshgrid( + kernel_size, kernel_size, normalized_coordinates=False, device=image.device, dtype=image.dtype + ) + + grid -= math.floor(kernel_size / 2) + kernel = torch.hypot(grid[0, :, :, 0], grid[0, :, :, 1]) + kernel = torch.exp(kernel / -h).unsqueeze(0) + + out = torch.zeros_like(image) + + # It is possible to avoid cloning the image if boundary = image, but this would require modifying the image tensor. + boundary = image.clone() + signal_ones = torch.ones_like(boundary) + + for i in range(n_iters): + cdt = filter2d(boundary, kernel, border_type="replicate") + cdt = -h * torch.log(cdt) + + # We are calculating log(0) above. + cdt = torch.nan_to_num(cdt, posinf=0.0) + + mask = torch.where(cdt > 0, 1.0, 0.0) + if mask.sum() == 0: + break + + offset: int = i * kernel_size // 2 + out += (offset + cdt) * mask + boundary = torch.where(mask == 1, signal_ones, boundary) + + return out + + +class DistanceTransform(nn.Module): + r"""Module that approximates the Manhattan (city block) distance transform of images using convolutions. + + Args: + kernel_size: size of the convolution kernel. + h: value that influence the approximation of the min function. + + """ + + def __init__(self, kernel_size: int = 3, h: float = 0.35) -> None: + super().__init__() + self.kernel_size = kernel_size + self.h = h + + def forward(self, image: torch.Tensor) -> torch.Tensor: + # If images have multiple channels, view the channels in the batch dimension to match kernel shape. + if image.shape[1] > 1: + image_in = image.view(-1, 1, image.shape[-2], image.shape[-1]) + else: + image_in = image + + return distance_transform(image_in, self.kernel_size, self.h).view_as(image) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/edge_detection.py b/python_embeded/Lib/site-packages/kornia/contrib/edge_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..f86d49e955c368c6d99460c7d423645e5b958e38 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/edge_detection.py @@ -0,0 +1,57 @@ +# 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. +# + +from kornia.core import Module, Tensor +from kornia.core.check import KORNIA_CHECK_SHAPE +from kornia.filters.dexined import DexiNed + + +class EdgeDetector(Module): + r"""Detect edges in a given image using a CNN. + + By default, it uses the method described in :cite:`xsoria2020dexined`. + + Return: + A tensor of shape :math:`(B,1,H,W)`. + + Example: + >>> img = torch.rand(1, 3, 320, 320) + >>> detect = EdgeDetector() + >>> out = detect(img) + >>> out.shape + torch.Size([1, 1, 320, 320]) + + """ + + def __init__(self) -> None: + super().__init__() + self.model = DexiNed(pretrained=True) + + def load(self, path_file: str) -> None: + self.model.load_from_file(path_file) + + def preprocess(self, image: Tensor) -> Tensor: + return image + + def postprocess(self, data: Tensor) -> Tensor: + return data + + def forward(self, image: Tensor) -> Tensor: + KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"]) + img = self.preprocess(image) + out = self.model(img) + return self.postprocess(out) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/extract_patches.py b/python_embeded/Lib/site-packages/kornia/contrib/extract_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa411ae06434ac92ef507b7a475428105e14e76 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/extract_patches.py @@ -0,0 +1,499 @@ +# 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. +# + +from math import ceil +from typing import Optional, Tuple, Union, cast +from warnings import warn + +import torch +import torch.nn.functional as F +from torch.nn.modules.utils import _pair + +from kornia.core import Module, Tensor, pad + +FullPadType = Tuple[int, int, int, int] +TuplePadType = Union[Tuple[int, int], FullPadType] +PadType = Union[int, TuplePadType] + + +def create_padding_tuple(padding: PadType, unpadding: bool = False) -> FullPadType: + """Create argument for padding op.""" + padding = cast(TuplePadType, _pair(padding)) + + if len(padding) not in [2, 4]: + raise AssertionError( + f"{'Unpadding' if unpadding else 'Padding'} must be either an int, tuple of two ints or tuple of four ints" + ) + + if len(padding) == 2: + pad_vert = _pair(padding[0]) + pad_horz = _pair(padding[1]) + else: + pad_vert = padding[:2] + pad_horz = padding[2:] + padding = cast(FullPadType, pad_horz + pad_vert) + + return padding + + +def compute_padding( + original_size: Union[int, Tuple[int, int]], + window_size: Union[int, Tuple[int, int]], + stride: Optional[Union[int, Tuple[int, int]]] = None, +) -> FullPadType: + r"""Compute required padding to ensure chaining of :func:`extract_tensor_patches` and + :func:`combine_tensor_patches` produces expected result. + + Args: + original_size: the size of the original tensor. + window_size: the size of the sliding window used while extracting patches. + stride: The stride of the sliding window. Optional: if not specified, window_size will be used. + + Return: + The required padding as a tuple of four ints: (top, bottom, left, right) + + Example: + >>> image = torch.arange(12).view(1, 1, 4, 3) + >>> padding = compute_padding((4,3), (3,3)) + >>> out = extract_tensor_patches(image, window_size=(3, 3), stride=(3, 3), padding=padding) + >>> combine_tensor_patches(out, original_size=(4, 3), window_size=(3, 3), stride=(3, 3), unpadding=padding) + tensor([[[[ 0, 1, 2], + [ 3, 4, 5], + [ 6, 7, 8], + [ 9, 10, 11]]]]) + + .. note:: + This function will be implicitly used in :func:`extract_tensor_patches` and :func:`combine_tensor_patches` if + `allow_auto_(un)padding` is set to True. + + """ # noqa: D205 + original_size = cast(Tuple[int, int], _pair(original_size)) + window_size = cast(Tuple[int, int], _pair(window_size)) + if stride is None: + stride = window_size + stride = cast(Tuple[int, int], _pair(stride)) + + remainder_vertical = (original_size[0] - window_size[0]) % stride[0] + remainder_horizontal = (original_size[1] - window_size[1]) % stride[1] + # it might be best to apply padding only to the far edges (right, bottom), so + # that fewer patches are affected by the padding. + # For now, just use the default padding + if remainder_vertical != 0: + vertical_padding = stride[0] - remainder_vertical + else: + vertical_padding = 0 + + if remainder_horizontal != 0: + horizontal_padding = stride[1] - remainder_horizontal + else: + horizontal_padding = 0 + + if vertical_padding % 2 == 0: + top_padding = bottom_padding = vertical_padding // 2 + else: + top_padding = vertical_padding // 2 + bottom_padding = ceil(vertical_padding / 2) + + if horizontal_padding % 2 == 0: + left_padding = right_padding = horizontal_padding // 2 + else: + left_padding = horizontal_padding // 2 + right_padding = ceil(horizontal_padding / 2) + # the new implementation with unfolding requires symmetric padding + padding = int(top_padding), int(bottom_padding), int(left_padding), int(right_padding) + return cast(FullPadType, padding) + + +class ExtractTensorPatches(Module): + r"""Module that extract patches from tensors and stack them. + + In the simplest case, the output value of the operator with input size + :math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`. + + where + - :math:`B` is the batch size. + - :math:`N` denotes the total number of extracted patches stacked in + - :math:`C` denotes the number of input channels. + - :math:`H`, :math:`W` the input height and width of the input in pixels. + - :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size + defined in the function signature. + left-right and top-bottom order. + + * :attr:`window_size` is the size of the sliding window and controls the + shape of the output tensor and defines the shape of the output patch. + * :attr:`stride` controls the stride to apply to the sliding window and + regulates the overlapping between the extracted patches. + * :attr:`padding` controls the amount of implicit zeros-paddings on both + sizes at each dimension. + * :attr:`allow_auto_padding` allows automatic calculation of the padding required + to fit the window and stride into the image. + + The parameters :attr:`window_size`, :attr:`stride` and :attr:`padding` can + be either: + + - a single ``int`` -- in which case the same value is used for the + height and width dimension. + - a ``tuple`` of two ints -- in which case, the first `int` is used for + the height dimension, and the second `int` for the width dimension. + + :attr:`padding` can also be a ``tuple`` of four ints -- in which case, the + first two ints are for the height dimension while the last two ints are for + the width dimension. + + Args: + input: tensor image where to extract the patches with shape :math:`(B, C, H, W)`. + window_size: the size of the sliding window and the output patch size. + stride: stride of the sliding window. + padding: Zero-padding added to both side of the input. + allow_auto_adding: whether to allow automatic padding if the window and stride do not fit into the image. + + Shape: + - Input: :math:`(B, C, H, W)` + - Output: :math:`(B, N, C, H_{out}, W_{out})` + + Returns: + the tensor with the extracted patches. + + Examples: + >>> input = torch.arange(9.).view(1, 1, 3, 3) + >>> patches = extract_tensor_patches(input, (2, 3)) + >>> input + tensor([[[[0., 1., 2.], + [3., 4., 5.], + [6., 7., 8.]]]]) + >>> patches[:, -1] + tensor([[[[3., 4., 5.], + [6., 7., 8.]]]]) + + """ + + def __init__( + self, + window_size: Union[int, Tuple[int, int]], + stride: Union[int, Tuple[int, int]] = 1, + padding: PadType = 0, + allow_auto_padding: bool = False, + ) -> None: + super().__init__() + self.window_size: Union[int, Tuple[int, int]] = window_size + self.stride: Union[int, Tuple[int, int]] = stride + self.padding: PadType = padding + self.allow_auto_padding: bool = allow_auto_padding + + def forward(self, input: Tensor) -> Tensor: + return extract_tensor_patches( + input, + self.window_size, + stride=self.stride, + padding=self.padding, + allow_auto_padding=self.allow_auto_padding, + ) + + +class CombineTensorPatches(Module): + r"""Module that combines patches back into full tensors. + + In the simplest case, the output value of the operator with input size + :math:`(B, N, C, H_{out}, W_{out})` is :math:`(B, C, H, W)`. + + where + - :math:`B` is the batch size. + - :math:`N` denotes the total number of extracted patches stacked in + - :math:`C` denotes the number of input channels. + - :math:`H`, :math:`W` the input height and width of the input in pixels. + - :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size + defined in the function signature. + left-right and top-bottom order. + + + * :attr:`original_size` is the size of the original image prior to + extracting tensor patches and defines the shape of the output patch. + * :attr:`window_size` is the size of the sliding window used while + extracting tensor patches. + * :attr:`stride` controls the stride to apply to the sliding window and + regulates the overlapping between the extracted patches. + * :attr:`unpadding` is the amount of padding to be removed. If specified, + this value must be the same as padding used while extracting tensor patches. + * :attr:`allow_auto_unpadding` allows automatic calculation of the padding required + to fit the window and stride into the image. This must be used if the + `allow_auto_padding` flag was used for extracting the patches. + + + The parameters :attr:`original_size`, :attr:`window_size`, :attr:`stride`, and :attr:`unpadding` can + be either: + + - a single ``int`` -- in which case the same value is used for the + height and width dimension. + - a ``tuple`` of two ints -- in which case, the first `int` is used for + the height dimension, and the second `int` for the width dimension. + + :attr:`unpadding` can also be a ``tuple`` of four ints -- in which case, the + first two ints are for the height dimension while the last two ints are for + the width dimension. + + Args: + patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`. + original_size: the size of the original tensor and the output size. + window_size: the size of the sliding window used while extracting patches. + stride: stride of the sliding window. + unpadding: remove the padding added to both side of the input. + allow_auto_unpadding: whether to allow automatic unpadding of the input + if the window and stride do not fit into the original_size. + eps: small value used to prevent division by zero. + + Shape: + - Input: :math:`(B, N, C, H_{out}, W_{out})` + - Output: :math:`(B, C, H, W)` + + Example: + >>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)) + >>> combine_tensor_patches(out, original_size=(4, 4), window_size=(2, 2), stride=(2, 2)) + tensor([[[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]]]) + + .. note:: + This function is supposed to be used in conjunction with :class:`ExtractTensorPatches`. + + """ + + def __init__( + self, + original_size: Tuple[int, int], + window_size: Union[int, Tuple[int, int]], + stride: Optional[Union[int, Tuple[int, int]]] = None, + unpadding: PadType = 0, + allow_auto_unpadding: bool = False, + ) -> None: + super().__init__() + self.original_size: Tuple[int, int] = original_size + self.window_size: Union[int, Tuple[int, int]] = window_size + self.stride: Union[int, Tuple[int, int]] = stride if stride is not None else window_size + self.unpadding: PadType = unpadding + self.allow_auto_unpadding: bool = allow_auto_unpadding + + def forward(self, input: Tensor) -> Tensor: + return combine_tensor_patches( + input, + self.original_size, + self.window_size, + stride=self.stride, + unpadding=self.unpadding, + allow_auto_unpadding=self.allow_auto_unpadding, + ) + + +def _check_patch_fit(original_size: Tuple[int, int], window_size: Tuple[int, int], stride: Tuple[int, int]) -> bool: + remainder_vertical = (original_size[0] - window_size[0]) % stride[0] + remainder_horizontal = (original_size[1] - window_size[1]) % stride[1] + # the remainder takes into account half a window on each side, + # the rest of the image is divided based on the stride, not the window + # size + if (remainder_horizontal != 0) or (remainder_vertical != 0): + # needs padding to fit + return False + # we can fit a full number of patches in, based on the stride + return True + + +def combine_tensor_patches( + patches: Tensor, + original_size: Union[int, Tuple[int, int]], + window_size: Union[int, Tuple[int, int]], + stride: Union[int, Tuple[int, int]], + allow_auto_unpadding: bool = False, + unpadding: PadType = 0, + eps: float = 1e-8, +) -> Tensor: + r"""Restore input from patches. + + See :class:`~kornia.contrib.CombineTensorPatches` for details. + + Args: + patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`. + original_size: the size of the original tensor and the output size. + window_size: the size of the sliding window used while extracting patches. + stride: stride of the sliding window. + unpadding: remove the padding added to both side of the input. + allow_auto_unpadding: whether to allow automatic unpadding of the input + if the window and stride do not fit into the original_size. + eps: small value used to prevent division by zero. + + Return: + The combined patches in an image tensor with shape :math:`(B, C, H, W)`. + + Example: + >>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)) + >>> combine_tensor_patches(out, original_size=(4, 4), window_size=(2, 2), stride=(2, 2)) + tensor([[[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]]]) + + .. note:: + This function is supposed to be used in conjunction with :func:`extract_tensor_patches`. + + """ + if patches.ndim != 5: + raise ValueError(f"Invalid input shape, we expect BxNxCxHxW. Got: {patches.shape}") + + original_size = cast(Tuple[int, int], _pair(original_size)) + window_size = cast(Tuple[int, int], _pair(window_size)) + stride = cast(Tuple[int, int], _pair(stride)) + + if (stride[0] > window_size[0]) | (stride[1] > window_size[1]): + raise AssertionError( + f"Stride={stride} should be less than or equal to Window size={window_size}, information is missing" + ) + + if not unpadding: + # if padding is specified, we leave it up to the user to ensure it fits + # otherwise we check here if it will fit and offer to calculate padding + if not _check_patch_fit(original_size, window_size, stride): + if not allow_auto_unpadding: + warn( + f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n" + f"Image size: {original_size}\n" + "This means we probably cannot correctly recombine patches. By enabling `allow_auto_unpadding`, " + "the input will be unpadded to fit the window and stride.\n" + "If the patches have been obtained through `extract_tensor_patches` with the correct padding or " + "the argument `allow_auto_padding`, this will result in a correct reconstruction.", + stacklevel=1, + ) + else: + unpadding = compute_padding(original_size=original_size, window_size=window_size, stride=stride) + # TODO: Can't we just do actual size minus original size to get padding? + + if unpadding: + unpadding = create_padding_tuple(unpadding) + unpadding = cast(FullPadType, unpadding) + + ones = torch.ones( + patches.shape[0], + patches.shape[2], + original_size[0], + original_size[1], + device=patches.device, + dtype=patches.dtype, + ) + + if unpadding: + ones = pad(ones, pad=unpadding) + restored_size = ones.shape[2:] + + patches = patches.permute(0, 2, 3, 4, 1) + patches = patches.reshape(patches.shape[0], -1, patches.shape[-1]) + int_flag = 0 + if not torch.is_floating_point(patches): + int_flag = 1 + dtype = patches.dtype + patches = patches.float() + ones = ones.float() + + # Calculate normalization map + unfold_ones = F.unfold(ones, kernel_size=window_size, stride=stride) + norm_map = F.fold(input=unfold_ones, output_size=restored_size, kernel_size=window_size, stride=stride) + if unpadding: + norm_map = pad(norm_map, [-i for i in unpadding]) + + # Restored tensor + saturated_restored_tensor = F.fold(input=patches, output_size=restored_size, kernel_size=window_size, stride=stride) + if unpadding: + saturated_restored_tensor = pad(saturated_restored_tensor, [-i for i in unpadding]) + + # Remove satuation effect due to multiple summations + restored_tensor = saturated_restored_tensor / (norm_map + eps) + if int_flag: + restored_tensor = restored_tensor.to(dtype) + return restored_tensor + + +def _extract_tensor_patchesnd(input: Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]) -> Tensor: + batch_size, num_channels = input.size()[:2] + dims = range(2, input.dim()) + for dim, patch_size, stride in zip(dims, window_sizes, strides): + input = input.unfold(dim, patch_size, stride) + input = input.permute(0, *dims, 1, *(dim + len(dims) for dim in dims)).contiguous() + return input.view(batch_size, -1, num_channels, *window_sizes) + + +def extract_tensor_patches( + input: Tensor, + window_size: Union[int, Tuple[int, int]], + stride: Union[int, Tuple[int, int]] = 1, + padding: PadType = 0, + allow_auto_padding: bool = False, +) -> Tensor: + r"""Extract patches from tensors and stacks them. + + See :class:`~kornia.contrib.ExtractTensorPatches` for details. + + Args: + input: tensor image where to extract the patches with shape :math:`(B, C, H, W)`. + window_size: the size of the sliding window and the output patch size. + stride: stride of the sliding window. + padding: Zero-padding added to both side of the input. + allow_auto_padding: whether to allow automatic padding if the window and stride do not fit into the image. + + Returns: + the tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`. + + Examples: + >>> input = torch.arange(9.).view(1, 1, 3, 3) + >>> patches = extract_tensor_patches(input, (2, 3)) + >>> input + tensor([[[[0., 1., 2.], + [3., 4., 5.], + [6., 7., 8.]]]]) + >>> patches[:, -1] + tensor([[[[3., 4., 5.], + [6., 7., 8.]]]]) + + """ + if not torch.is_tensor(input): + raise TypeError(f"Input input type is not a Tensor. Got {type(input)}") + + if len(input.shape) != 4: + raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}") + + # check if the window sliding over the image will fit into the image + # torch's unfold drops the final patches that don't fit + window_size = cast(Tuple[int, int], _pair(window_size)) + stride = cast(Tuple[int, int], _pair(stride)) + original_size = (input.shape[-2], input.shape[-1]) + + if not padding: + # if padding is specified, we leave it up to the user to ensure it fits + # otherwise we check here if it will fit and offer to calculate padding + if not _check_patch_fit(original_size, window_size, stride): + if not allow_auto_padding: + warn( + f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n" + f"Image size: {original_size}\n" + "This means that the final incomplete patches will be dropped. By enabling `allow_auto_padding`, " + "the input will be padded to fit the window and stride.", + stacklevel=1, + ) + else: + padding = compute_padding(original_size=original_size, window_size=window_size, stride=stride) + + if padding: + padding = create_padding_tuple(padding) + input = pad(input, padding) + + return _extract_tensor_patchesnd(input, window_size, stride) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/face_detection.py b/python_embeded/Lib/site-packages/kornia/contrib/face_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..5acc9f66c506a196bcf0ffef4511c1703c9f45c6 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/face_detection.py @@ -0,0 +1,436 @@ +# 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. +# + +# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa +import math +from enum import Enum +from typing import Dict, List, Optional, Tuple + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.geometry.bbox import nms as nms_kornia + +__all__ = ["FaceDetector", "FaceDetectorResult", "FaceKeypoint"] + + +url: str = "https://github.com/kornia/data/raw/main/yunet_final.pth" + + +class FaceKeypoint(Enum): + r"""Define the keypoints detected in a face. + + The left/right convention is based on the screen viewer. + """ + + EYE_LEFT = 0 + EYE_RIGHT = 1 + NOSE = 2 + MOUTH_LEFT = 3 + MOUTH_RIGHT = 4 + + +class FaceDetectorResult: + r"""Encapsulate the results obtained by the :py:class:`kornia.contrib.FaceDetector`. + + Args: + data: the encoded results coming from the feature detector with shape :math:`(14,)`. + + """ + + def __init__(self, data: torch.Tensor) -> None: + if len(data) < 15: + raise ValueError(f"Result must comes as vector of size(14). Got: {data.shape}.") + self._data = data + + def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "FaceDetectorResult": + """Like :func:`torch.nn.Module.to()` method.""" + self._data = self._data.to(device=device, dtype=dtype) + return self + + @property + def xmin(self) -> torch.Tensor: + """The bounding box top-left x-coordinate.""" + return self._data[..., 0] + + @property + def ymin(self) -> torch.Tensor: + """The bounding box top-left y-coordinate.""" + return self._data[..., 1] + + @property + def xmax(self) -> torch.Tensor: + """The bounding box bottom-right x-coordinate.""" + return self._data[..., 2] + + @property + def ymax(self) -> torch.Tensor: + """The bounding box bottom-right y-coordinate.""" + return self._data[..., 3] + + def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor: + """Get the [x y] position of a given facial keypoint. + + Args: + keypoint: the keypoint type to return the position. + + """ + if keypoint == FaceKeypoint.EYE_LEFT: + out = self._data[..., (4, 5)] + elif keypoint == FaceKeypoint.EYE_RIGHT: + out = self._data[..., (6, 7)] + elif keypoint == FaceKeypoint.NOSE: + out = self._data[..., (8, 9)] + elif keypoint == FaceKeypoint.MOUTH_LEFT: + out = self._data[..., (10, 11)] + elif keypoint == FaceKeypoint.MOUTH_RIGHT: + out = self._data[..., (12, 13)] + else: + raise ValueError(f"Not valid keypoint type. Got: {keypoint}.") + return out + + @property + def score(self) -> torch.Tensor: + """The detection score.""" + return self._data[..., 14] + + @property + def width(self) -> torch.Tensor: + """The bounding box width.""" + return self.xmax - self.xmin + + @property + def height(self) -> torch.Tensor: + """The bounding box height.""" + return self.ymax - self.ymin + + @property + def top_left(self) -> torch.Tensor: + """The [x y] position of the top-left coordinate of the bounding box.""" + return self._data[..., (0, 1)] + + @property + def top_right(self) -> torch.Tensor: + """The [x y] position of the top-left coordinate of the bounding box.""" + out = self.top_left + out[..., 0] += self.width + return out + + @property + def bottom_right(self) -> torch.Tensor: + """The [x y] position of the bottom-right coordinate of the bounding box.""" + return self._data[..., (2, 3)] + + @property + def bottom_left(self) -> torch.Tensor: + """The [x y] position of the top-left coordinate of the bounding box.""" + out = self.top_left + out[..., 1] += self.height + return out + + +class FaceDetector(nn.Module): + r"""Detect faces in a given image using a CNN. + + By default, it uses the method described in :cite:`facedetect-yu`. + + Args: + top_k: the maximum number of detections to return before the nms. + confidence_threshold: the threshold used to discard detections. + nms_threshold: the threshold used by the nms for iou. + keep_top_k: the maximum number of detections to return after the nms. + + Return: + A list of B tensors with shape :math:`(N,15)` to be used with :py:class:`kornia.contrib.FaceDetectorResult`. + + Example: + >>> img = torch.rand(1, 3, 320, 320) + >>> detect = FaceDetector() + >>> res = detect(img) + + """ + + def __init__( + self, top_k: int = 5000, confidence_threshold: float = 0.3, nms_threshold: float = 0.3, keep_top_k: int = 750 + ) -> None: + super().__init__() + self.top_k = top_k + self.confidence_threshold = confidence_threshold + self.nms_threshold = nms_threshold + self.keep_top_k = keep_top_k + self.config = { + "name": "YuFaceDetectNet", + "min_sizes": [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]], + "steps": [8, 16, 32, 64], + "variance": [0.1, 0.2], + "clip": False, + } + self.min_sizes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]] + self.steps = [8, 16, 32, 64] + self.variance = [0.1, 0.2] + self.clip = False + self.model = YuFaceDetectNet("test", pretrained=True) + self.nms = nms_kornia + + def preprocess(self, image: torch.Tensor) -> torch.Tensor: + return image + + def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> List[torch.Tensor]: + loc, conf, iou = data["loc"], data["conf"], data["iou"] + + scale = torch.tensor( + [width, height, width, height, width, height, width, height, width, height, width, height, width, height], + device=loc.device, + dtype=loc.dtype, + ) # 14 + + priors = _PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width)) + priors = priors.to(loc.device, loc.dtype) + + batched_dets: List[torch.Tensor] = [] + for batch_elem in range(loc.shape[0]): + boxes = _decode(loc[batch_elem], priors(), self.variance) # Nx14 + boxes = boxes * scale + + # clamp here for the compatibility for ONNX + cls_scores, iou_scores = conf[batch_elem, :, 1], iou[batch_elem, :, 0] + scores = (cls_scores * iou_scores.clamp(0.0, 1.0)).sqrt() + + # ignore low scores + inds = scores > self.confidence_threshold + boxes, scores = boxes[inds], scores[inds] + + # keep top-K before NMS + order = scores.sort(descending=True)[1][: self.top_k] + boxes, scores = boxes[order], scores[order] + + # performd NMS + # NOTE: nms need to be revise since does not export well to onnx + dets = torch.cat((boxes, scores[:, None]), dim=-1) # Nx15 + keep = self.nms(boxes[:, :4], scores, self.nms_threshold) + if len(keep) > 0: + dets = dets[keep, :] + + # keep top-K faster NMS + batched_dets.append(dets[: self.keep_top_k]) + return batched_dets + + def forward(self, image: torch.Tensor) -> List[torch.Tensor]: + r"""Detect faces in a given batch of images. + + Args: + image: batch of images :math:`(B,3,H,W)` + + Return: + List[torch.Tensor]: list with the boxes found on each image. :math:`Bx(N,15)`. + + """ + img = self.preprocess(image) + out = self.model(img) + return self.postprocess(out, img.shape[-2], img.shape[-1]) + + +# utils for the network + + +class ConvDPUnit(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None: + super().__init__() + self.add_module("conv1", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1)) + self.add_module("conv2", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels)) + if withBNRelu: + self.add_module("bn", nn.BatchNorm2d(out_channels)) + self.add_module("relu", nn.ReLU(inplace=True)) + + +class Conv_head(nn.Sequential): + def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None: + super().__init__() + self.add_module("conv1", nn.Conv2d(in_channels, mid_channels, 3, 2, 1, bias=True, groups=1)) + self.add_module("bn1", nn.BatchNorm2d(mid_channels)) + self.add_module("relu", nn.ReLU(inplace=True)) + self.add_module("conv2", ConvDPUnit(mid_channels, out_channels)) + + +class Conv4layerBlock(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None: + super().__init__() + self.add_module("conv1", ConvDPUnit(in_channels, in_channels, True)) + self.add_module("conv2", ConvDPUnit(in_channels, out_channels, withBNRelu)) + + +class YuFaceDetectNet(nn.Module): + def __init__(self, phase: str, pretrained: bool) -> None: + super().__init__() + self.phase = phase + self.num_classes = 2 + + self.model0 = Conv_head(3, 16, 16) + self.model1 = Conv4layerBlock(16, 64) + self.model2 = Conv4layerBlock(64, 64) + self.model3 = Conv4layerBlock(64, 64) + self.model4 = Conv4layerBlock(64, 64) + self.model5 = Conv4layerBlock(64, 64) + self.model6 = Conv4layerBlock(64, 64) + + self.head = nn.Sequential( + Conv4layerBlock(64, 3 * (14 + 2 + 1), False), + Conv4layerBlock(64, 2 * (14 + 2 + 1), False), + Conv4layerBlock(64, 2 * (14 + 2 + 1), False), + Conv4layerBlock(64, 3 * (14 + 2 + 1), False), + ) + + if self.phase == "train": + for m in self.modules(): + if isinstance(m, nn.Conv2d): + if m.bias is not None: + nn.init.xavier_normal_(m.weight.data) + m.bias.data.fill_(0.02) + else: + m.weight.data.normal_(0, 0.01) + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict, strict=True) + self.eval() + + def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: + detection_sources, head_list = [], [] + + x = self.model0(x) + x = F.max_pool2d(x, 2) + x = self.model1(x) + x = self.model2(x) + x = F.max_pool2d(x, 2) + x = self.model3(x) + detection_sources.append(x) + + x = F.max_pool2d(x, 2) + x = self.model4(x) + detection_sources.append(x) + + x = F.max_pool2d(x, 2) + x = self.model5(x) + detection_sources.append(x) + + x = F.max_pool2d(x, 2) + x = self.model6(x) + detection_sources.append(x) + + for i, h in enumerate(self.head): + x_tmp = h(detection_sources[i]) + head_list.append(x_tmp.permute(0, 2, 3, 1).contiguous()) + + head_data = torch.cat([o.view(o.size(0), -1) for o in head_list], 1) + head_data = head_data.view(head_data.size(0), -1, 17) + + loc_data, conf_data, iou_data = head_data.split((14, 2, 1), dim=-1) + + if self.phase == "test": + conf_data = torch.softmax(conf_data, dim=-1) + else: + loc_data = loc_data.view(loc_data.size(0), -1, 14) + conf_data = conf_data.view(conf_data.size(0), -1, self.num_classes) + iou_data = iou_data.view(iou_data.size(0), -1, 1) + + return {"loc": loc_data, "conf": conf_data, "iou": iou_data} + + +# utils for post-processing + + +# Adapted from https://github.com/Hakuyume/chainer-ssd +def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor: + """Decode locations from predictions using priors to undo the encoding for offset regression at train time. + + Args: + loc:location predictions for loc layers. Shape: [num_priors,4]. + priors: Prior boxes in center-offset form. Shape: [num_priors,4]. + variances: (list[float]) Variances of priorboxes. + + Return: + Tensor containing decoded bounding box predictions. + + """ + boxes = torch.cat( + ( + priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4], + priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]), + priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4], + priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4], + priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4], + priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4], + priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4], + ), + 1, + ) + # prepare final output + tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2 + return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1) + + +class _PriorBox: + def __init__(self, min_sizes: List[List[int]], steps: List[int], clip: bool, image_size: Tuple[int, int]) -> None: + self.min_sizes = min_sizes + self.steps = steps + self.clip = clip + self.image_size = image_size + + self.device: torch.device = torch.device("cpu") + self.dtype: torch.dtype = torch.float32 + + for i in range(4): + if self.steps[i] != math.pow(2, (i + 3)): + raise ValueError("steps must be [8,16,32,64]") + + self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2), int(int((self.image_size[1] + 1) / 2) / 2)] + self.feature_map_3th = [int(self.feature_map_2th[0] / 2), int(self.feature_map_2th[1] / 2)] + self.feature_map_4th = [int(self.feature_map_3th[0] / 2), int(self.feature_map_3th[1] / 2)] + self.feature_map_5th = [int(self.feature_map_4th[0] / 2), int(self.feature_map_4th[1] / 2)] + self.feature_map_6th = [int(self.feature_map_5th[0] / 2), int(self.feature_map_5th[1] / 2)] + + self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th] + + def to(self, device: torch.device, dtype: torch.dtype) -> "_PriorBox": + self.device = device + self.dtype = dtype + return self + + def __call__(self) -> torch.Tensor: + anchors: List[float] = [] + for k, f in enumerate(self.feature_maps): + min_sizes: List[int] = self.min_sizes[k] + # NOTE: the nested loop it's to make torchscript happy + for i in range(f[0]): + for j in range(f[1]): + for min_size in min_sizes: + s_kx = min_size / self.image_size[1] + s_ky = min_size / self.image_size[0] + + cx = (j + 0.5) * self.steps[k] / self.image_size[1] + cy = (i + 0.5) * self.steps[k] / self.image_size[0] + anchors += [cx, cy, s_kx, s_ky] + # back to torch land + output = torch.tensor(anchors, device=self.device, dtype=self.dtype).view(-1, 4) + if self.clip: + output = output.clamp(max=1, min=0) + return output diff --git a/python_embeded/Lib/site-packages/kornia/contrib/histogram_matching.py b/python_embeded/Lib/site-packages/kornia/contrib/histogram_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..af4cd406b423da22ed034bbd8cdb2bee44ae07d3 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/histogram_matching.py @@ -0,0 +1,85 @@ +# 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. +# + +import torch + + +def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Tensor: + """Adjust the pixel values of an image to match its histogram towards a target image. + + `Histogram matching `_ is the transformation + of an image so that its histogram matches a specified histogram. In this implementation, the + histogram is computed over the flattened image array. Code referred to + `here `_. + + Args: + source: Image to transform. + template: Template image. It can have different dimensions to source. + + Returns: + The transformed output image as the same shape as the source image. + + Note: + This function does not matches histograms element-wisely if input a batched tensor. + + """ + oldshape = source.shape + source = source.ravel() + template = template.ravel() + + # get the set of unique pixel values and their corresponding indices and counts. + _, bin_idx, s_counts = torch.unique(source, return_inverse=True, return_counts=True) + t_values, t_counts = torch.unique(template, return_counts=True) + + # take the cumsum of the counts and normalize by the number of pixels to + # get the empirical cumulative distribution functions for the source and + # template images (maps pixel value --> quantile) + + s_quantiles = torch.cumsum(s_counts, dim=0, dtype=source.dtype) + s_quantiles = s_quantiles / s_quantiles[-1] + t_quantiles = torch.cumsum(t_counts, dim=0, dtype=source.dtype) + t_quantiles = t_quantiles / t_quantiles[-1] + + # interpolate linearly to find the pixel values in the template image + # that correspond most closely to the quantiles in the source image + interp_t_values = interp(s_quantiles, t_quantiles, t_values) + + return interp_t_values[bin_idx].reshape(oldshape) + + +def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor: + """One-dimensional linear interpolation for monotonically increasing sample points. + + Returns the one-dimensional piecewise linear interpolant to a function with + given discrete data points :math:`(xp, fp)`, evaluated at :math:`x`. + + This is confirmed to be a correct implementation. + See https://github.com/pytorch/pytorch/issues/1552#issuecomment-979998307 + + Args: + x: the :math:`x`-coordinates at which to evaluate the interpolated + values. + xp: the :math:`x`-coordinates of the data points, must be increasing. + fp: the :math:`y`-coordinates of the data points, same length as `xp`. + + Returns: + the interpolated values, same size as `x`. + + """ + i = torch.clip(torch.searchsorted(xp, x, right=True), 1, len(xp) - 1) + + return (fp[i - 1] * (xp[i] - x) + fp[i] * (x - xp[i - 1])) / (xp[i] - xp[i - 1]) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/image_stitching.py b/python_embeded/Lib/site-packages/kornia/contrib/image_stitching.py new file mode 100644 index 0000000000000000000000000000000000000000..539f82ebcb5d9206bfbf175509a9f9562beee7bf --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/image_stitching.py @@ -0,0 +1,155 @@ +# 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. +# + +from typing import Dict, Optional, Tuple + +import torch + +from kornia.color import rgb_to_grayscale +from kornia.core import Module, Tensor, concatenate, where, zeros_like +from kornia.feature import LocalFeatureMatcher, LoFTR +from kornia.geometry.homography import find_homography_dlt_iterated +from kornia.geometry.ransac import RANSAC +from kornia.geometry.transform import warp_perspective + + +class ImageStitcher(Module): + """Stitch two images with overlapping fields of view. + + Args: + matcher: image feature matching module. + estimator: method to compute homography, either "vanilla" or "ransac". + "ransac" is slower with a better accuracy. + blending_method: method to blend two images together. + Only "naive" is currently supported. + + Note: + Current implementation requires strict image ordering from left to right. + + .. code-block:: python + + IS = ImageStitcher(KF.LoFTR(pretrained='outdoor'), estimator='ransac').cuda() + # Compute the stitched result with less GPU memory cost. + with torch.inference_mode(): + out = IS(img_left, img_right) + # Show the result + plt.imshow(K.tensor_to_image(out)) + + """ + + def __init__(self, matcher: Module, estimator: str = "ransac", blending_method: str = "naive") -> None: + super().__init__() + self.matcher = matcher + self.estimator = estimator + self.blending_method = blending_method + if estimator not in ["ransac", "vanilla"]: + raise NotImplementedError(f"Unsupported estimator {estimator}. Use `ransac` or `vanilla` instead.") + if estimator == "ransac": + self.ransac = RANSAC("homography") + + def _estimate_homography(self, keypoints1: Tensor, keypoints2: Tensor) -> Tensor: + """Estimate homography by the matched keypoints. + + Args: + keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`. + keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`. + + """ + if self.estimator == "vanilla": + homo = find_homography_dlt_iterated( + keypoints2[None], keypoints1[None], torch.ones_like(keypoints1[None, :, 0]) + ) + elif self.estimator == "ransac": + homo, _ = self.ransac(keypoints2, keypoints1) + homo = homo[None] + else: + raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use `ransac` or `vanilla` instead.") + return homo + + def estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor: + """Compute the corresponding homography.""" + kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"] + homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))] + + if len(homos) == 0: + raise RuntimeError("Compute homography failed. No matched keypoints found.") + + return concatenate(homos) + + def blend_image(self, src_img: Tensor, dst_img: Tensor, mask: Tensor) -> Tensor: + """Blend two images together.""" + out: Tensor + if self.blending_method == "naive": + out = where(mask == 1, src_img, dst_img) + else: + raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use `naive`.") + return out + + def preprocess(self, image_1: Tensor, image_2: Tensor) -> Dict[str, Tensor]: + """Preprocess input to the required format.""" + # TODO: probably perform histogram matching here. + if isinstance(self.matcher, (LoFTR, LocalFeatureMatcher)): + input_dict = { # LofTR works on grayscale images only + "image0": rgb_to_grayscale(image_1), + "image1": rgb_to_grayscale(image_2), + } + else: + raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.") + return input_dict + + def postprocess(self, image: Tensor, mask: Tensor) -> Tensor: + # NOTE: assumes no batch mode. This method keeps all valid regions after stitching. + mask_ = mask.sum((0, 1)) + index = int(mask_.bool().any(0).long().argmin().item()) + if index == 0: # If no redundant space + return image + return image[..., :index] + + def on_matcher(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]: + return self.matcher(data) + + def stitch_pair( + self, + images_left: Tensor, + images_right: Tensor, + mask_left: Optional[Tensor] = None, + mask_right: Optional[Tensor] = None, + ) -> Tuple[Tensor, Tensor]: + # Compute the transformed images + input_dict = self.preprocess(images_left, images_right) + out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1]) + correspondences = self.on_matcher(input_dict) + homo = self.estimate_transform(**correspondences) + src_img = warp_perspective(images_right, homo, out_shape) + dst_img = concatenate([images_left, zeros_like(images_right)], -1) + + # Compute the transformed masks + if mask_left is None: + mask_left = torch.ones_like(images_left) + if mask_right is None: + mask_right = torch.ones_like(images_right) + # 'nearest' to ensure no floating points in the mask + src_mask = warp_perspective(mask_right, homo, out_shape, mode="nearest") + dst_mask = concatenate([mask_left, zeros_like(mask_right)], -1) + return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype) + + def forward(self, *imgs: Tensor) -> Tensor: + img_out = imgs[0] + mask_left = torch.ones_like(img_out) + for i in range(len(imgs) - 1): + img_out, mask_left = self.stitch_pair(img_out, imgs[i + 1], mask_left) + return self.postprocess(img_out, mask_left) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/kmeans.py b/python_embeded/Lib/site-packages/kornia/contrib/kmeans.py new file mode 100644 index 0000000000000000000000000000000000000000..bbf8009a187040b3643347e6fb44a57012ab9cd2 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/kmeans.py @@ -0,0 +1,199 @@ +# 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. +# + +# based on https://github.com/subhadarship/kmeans_pytorch + +from __future__ import annotations + +import torch + +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE +from kornia.geometry.linalg import euclidean_distance + + +class KMeans: + """Implements the kmeans clustering algorithm with euclidean distance as similarity measure. + + Args: + num_clusters: number of clusters the data has to be assigned to + cluster_centers: tensor of starting cluster centres can be passed instead of num_clusters + tolerance: float value. the algorithm terminates if the shift in centers is less than tolerance + max_iterations: number of iterations to run the algorithm for + seed: number to set torch manual seed for reproducibility + + Example: + >>> kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0) + >>> kmeans.fit(torch.rand((1000, 5))) + >>> predictions = kmeans.predict(torch.rand((10, 5))) + + """ + + def __init__( + self, + num_clusters: int, + cluster_centers: Tensor | None, + tolerance: float = 10e-4, + max_iterations: int = 0, + seed: int | None = None, + ) -> None: + KORNIA_CHECK(num_clusters != 0, "num_clusters can't be 0") + + # cluster_centers should have only 2 dimensions + if cluster_centers is not None: + KORNIA_CHECK_SHAPE(cluster_centers, ["C", "D"]) + + self.num_clusters = num_clusters + self._cluster_centers = cluster_centers + self.tolerance = tolerance + self.max_iterations = max_iterations + + self._final_cluster_assignments: None | Tensor = None + self._final_cluster_centers: None | Tensor = None + + if seed is not None: + torch.manual_seed(seed) + + @property + def cluster_centers(self) -> Tensor: + if isinstance(self._final_cluster_centers, Tensor): + return self._final_cluster_centers + if isinstance(self._cluster_centers, Tensor): + return self._cluster_centers + else: + raise TypeError("Model has not been fit to a dataset") + + @property + def cluster_assignments(self) -> Tensor: + if isinstance(self._final_cluster_assignments, Tensor): + return self._final_cluster_assignments + else: + raise TypeError("Model has not been fit to a dataset") + + def _initialise_cluster_centers(self, X: Tensor, num_clusters: int) -> Tensor: + """Chooses num_cluster points from X as the initial cluster centers. + + Args: + X: 2D input tensor to be clustered + num_clusters: number of desired cluster centers + + Returns: + 2D Tensor with num_cluster rows + + """ + num_samples: int = len(X) + perm = torch.randperm(num_samples, device=X.device) + idx = perm[:num_clusters] + initial_state = X[idx] + return initial_state + + def _pairwise_euclidean_distance(self, data1: Tensor, data2: Tensor) -> Tensor: + """Compute pairwise squared distance between 2 sets of vectors. + + Args: + data1: 2D tensor of shape N, D + data2: 2D tensor of shape C, D + + Returns: + 2D tensor of shape N, C + + """ + # N*1*D + A = data1[:, None, ...] + # 1*C*D + B = data2[None, ...] + distance = euclidean_distance(A, B) + return distance + + def fit(self, X: Tensor) -> None: + """Fit iterative KMeans clustering till a threshold for shift in cluster centers or a maximum no of iterations + have reached. + + Args: + X: 2D input tensor to be clustered + + """ # noqa: D205 + # X should have only 2 dimensions + KORNIA_CHECK_SHAPE(X, ["N", "D"]) + + if self._cluster_centers is None: + self._cluster_centers = self._initialise_cluster_centers(X, self.num_clusters) + else: + # X and cluster_centers should have same number of columns + KORNIA_CHECK( + X.shape[1] == self._cluster_centers.shape[1], + f"Dimensions at position 1 of X and cluster_centers do not match. \ + {X.shape[1]} != {self._cluster_centers.shape[1]}", + ) + + # X = X.to(self.device) + current_centers = self._cluster_centers + + previous_centers: Tensor | None = None + iteration: int = 0 + + while True: + # find distance between X and current_centers + distance: Tensor = self._pairwise_euclidean_distance(X, current_centers) + + cluster_assignment = distance.argmin(-1) + + previous_centers = current_centers.clone() + + for index in range(self.num_clusters): + selected = torch.nonzero(cluster_assignment == index).squeeze() + selected = torch.index_select(X, 0, selected) + # edge case when a certain cluster centre has no points assigned to it + # just choose a random point as it's update + if selected.shape[0] == 0: + selected = X[torch.randint(len(X), (1,), device=X.device)] + current_centers[index] = selected.mean(dim=0) + + # sum of distance of how much the newly computed clusters have moved from their previous positions + center_shift = torch.sum(torch.sqrt(torch.sum((current_centers - previous_centers) ** 2, dim=1))) + + iteration = iteration + 1 + + if self.tolerance is not None and center_shift**2 < self.tolerance: + break + + if self.max_iterations != 0 and iteration >= self.max_iterations: + break + + self._final_cluster_assignments = cluster_assignment + self._final_cluster_centers = current_centers + + def predict(self, x: Tensor) -> Tensor: + """Find the cluster center closest to each point in x. + + Args: + x: 2D tensor + + Returns: + 1D tensor containing cluster id assigned to each data point in x + + """ + # x and cluster_centers should have same number of columns + KORNIA_CHECK( + x.shape[1] == self.cluster_centers.shape[1], + f"Dimensions at position 1 of x and cluster_centers do not match. \ + {x.shape[1]} != {self.cluster_centers.shape[1]}", + ) + + distance = self._pairwise_euclidean_distance(x, self.cluster_centers) + cluster_assignment = distance.argmin(-1) + return cluster_assignment diff --git a/python_embeded/Lib/site-packages/kornia/contrib/lambda_module.py b/python_embeded/Lib/site-packages/kornia/contrib/lambda_module.py new file mode 100644 index 0000000000000000000000000000000000000000..69e4d7a4bd3d6633ba4cd0f2aeedf2ae4d548e73 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/lambda_module.py @@ -0,0 +1,49 @@ +# 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. +# + +from typing import Any, Callable + +from kornia.core import Module, Tensor + + +class Lambda(Module): + """Applies user-defined lambda as a transform. + + Args: + func: Callable function. + + Returns: + The output of the user-defined lambda. + + Example: + >>> import kornia + >>> x = torch.rand(1, 3, 5, 5) + >>> f = Lambda(lambda x: kornia.color.rgb_to_grayscale(x)) + >>> f(x).shape + torch.Size([1, 1, 5, 5]) + + """ + + def __init__(self, func: Callable[..., Tensor]) -> None: + super().__init__() + if not callable(func): + raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}") + + self.func = func + + def forward(self, img: Tensor, *args: Any, **kwargs: Any) -> Tensor: + return self.func(img, *args, **kwargs) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f941c7d1552cae784515c6442d728aa76655df26 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/__init__.py @@ -0,0 +1,18 @@ +# 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. +# + +from kornia.contrib.models.structures import Prompts, SegmentationResults diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/base.py b/python_embeded/Lib/site-packages/kornia/contrib/models/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a78316d24ed2f58d093e0eeb7b8b6ac0aa42e970 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/base.py @@ -0,0 +1,75 @@ +# 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. +# + +from __future__ import annotations + +import os +from abc import ABC, abstractmethod +from typing import Any, Generic, Optional, TypeVar, cast + +import torch + +from kornia.core import Module + +ModelConfig = TypeVar("ModelConfig") + + +class ModelBase(ABC, Module, Generic[ModelConfig]): + """Abstract model class with some utilities function.""" + + def load_checkpoint(self, checkpoint: str, device: Optional[torch.device] = None) -> None: + """Load checkpoint from a given url or file. + + Args: + checkpoint: The url or filepath for the respective checkpoint + device: The desired device to load the weights and move the model + + """ + if os.path.isfile(checkpoint): + with open(checkpoint, "rb") as f: + state_dict = torch.load(f, map_location=device) + else: + state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=device) + + self.load_state_dict(state_dict) + + @staticmethod + @abstractmethod + def from_config(config: ModelConfig) -> ModelBase[ModelConfig]: + """Build/load the model. + + Args: + config: The specifications for the model be build/loaded + + """ + raise NotImplementedError + + def compile( + self, + *, + fullgraph: bool = False, + dynamic: bool = False, + backend: str = "inductor", + mode: Optional[str] = None, + options: Optional[dict[Any, Any]] = None, + disable: bool = False, + ) -> ModelBase[ModelConfig]: + compiled = torch.compile( + self, fullgraph=fullgraph, dynamic=dynamic, backend=backend, mode=mode, options=options, disable=disable + ) + compiled = cast(ModelBase[ModelConfig], compiled) + return compiled diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/common.py b/python_embeded/Lib/site-packages/kornia/contrib/models/common.py new file mode 100644 index 0000000000000000000000000000000000000000..176d3ab965ff445e739d7678962263f1ae0711d1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/common.py @@ -0,0 +1,165 @@ +# 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. +# + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core import Module, Tensor, pad + + +class ConvNormAct(nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int = 1, + act: str = "relu", + groups: int = 1, + conv_naming: str = "conv", + norm_naming: str = "norm", + act_naming: str = "act", + ) -> None: + super().__init__() + if kernel_size % 2 == 0: + # even kernel_size -> asymmetric padding + # PPHGNetV2 (for RT-DETR) uses kernel 2 + # follow TensorFlow/PaddlePaddle: bottom/right side is padded 1 more than top/left + # NOTE: this does not account for stride=2 + p1 = (kernel_size - 1) // 2 + p2 = kernel_size - 1 - p1 + self.pad = nn.ZeroPad2d((p1, p2, p1, p2)) + padding = 0 + else: + padding = (kernel_size - 1) // 2 + conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, 1, groups, False) + norm = nn.BatchNorm2d(out_channels) + activation = {"relu": nn.ReLU, "silu": nn.SiLU, "none": nn.Identity}[act](inplace=True) + + self.__setattr__(conv_naming, conv) + self.__setattr__(norm_naming, norm) + self.__setattr__(act_naming, activation) + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py +class MLP(Module): + def __init__( + self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim, *h], [*h, output_dim])) + self.sigmoid_output = sigmoid_output + + def forward(self, x: Tensor) -> Tensor: + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x + + +# Adapted from timm +# https://github.com/huggingface/pytorch-image-models/blob/v0.9.2/timm/layers/drop.py#L137 +class DropPath(Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True) -> None: + super().__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x: Tensor) -> Tensor: + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / (s + self.eps).sqrt() + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, int]]: + """Partition into non-overlapping windows with padding if needed. + + Args: + x: input tokens with [B, H, W, C]. + window_size: window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]) -> Tensor: + """Window unpartition into original sequences and removing padding. + + Args: + windows: input tokens with [B * num_windows, window_size, window_size, C]. + window_size: window size. + pad_hw: padded height and width (Hp, Wp). + hw: original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec12f2fda1c5de949d12dded9eaceae1a8179cee --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/__init__.py @@ -0,0 +1,20 @@ +# 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. +# + +from .model import EfficientViT, EfficientViTConfig + +__all__ = ["EfficientViT", "EfficientViTConfig"] diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/backbone.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..2159b40fc776295ac728d3938744a943c1e11e84 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/backbone.py @@ -0,0 +1,367 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 +from __future__ import annotations + +from typing import Any + +import torch +from torch import nn + +from kornia.contrib.models.efficient_vit.nn.ops import ( # type: ignore + ConvLayer, + DSConv, + EfficientViTBlock, + FusedMBConv, + IdentityLayer, + MBConv, + OpSequential, + ResBlock, + ResidualBlock, +) +from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config + + +class EfficientViTBackbone(nn.Module): + def __init__( + self, + width_list: list[int], + depth_list: list[int], + in_channels: int = 3, + dim: int = 32, + expand_ratio: float = 4, + norm: str = "bn2d", + act_func: str = "hswish", + ) -> None: + super().__init__() + + self.width_list = [] + # input stem + input_stem = [ + ConvLayer(in_channels=in_channels, out_channels=width_list[0], stride=2, norm=norm, act_func=act_func) + ] + for _ in range(depth_list[0]): + block = self.build_local_block( + in_channels=width_list[0], + out_channels=width_list[0], + stride=1, + expand_ratio=1, + norm=norm, + act_func=act_func, + ) + input_stem.append(ResidualBlock(block, IdentityLayer())) + in_channels = width_list[0] + self.input_stem = OpSequential(input_stem) + self.width_list.append(in_channels) + + # stages + stages = [] + for w, d in zip(width_list[1:3], depth_list[1:3]): + stage = [] + for i in range(d): + stride = 2 if i == 0 else 1 + block = self.build_local_block( + in_channels=in_channels, + out_channels=w, + stride=stride, + expand_ratio=expand_ratio, + norm=norm, + act_func=act_func, + ) + block = ResidualBlock(block, IdentityLayer() if stride == 1 else None) + stage.append(block) + in_channels = w + stages.append(OpSequential(stage)) + self.width_list.append(in_channels) + + for w, d in zip(width_list[3:], depth_list[3:]): + stage = [] + block = self.build_local_block( + in_channels=in_channels, + out_channels=w, + stride=2, + expand_ratio=expand_ratio, + norm=norm, + act_func=act_func, + fewer_norm=True, + ) + stage.append(ResidualBlock(block, None)) + in_channels = w + + for _ in range(d): + stage.append( + EfficientViTBlock( + in_channels=in_channels, dim=dim, expand_ratio=expand_ratio, norm=norm, act_func=act_func + ) + ) + stages.append(OpSequential(stage)) + self.width_list.append(in_channels) + self.stages = nn.ModuleList(stages) + + @staticmethod + def build_local_block( + in_channels: int, + out_channels: int, + stride: int, + expand_ratio: float, + norm: str, + act_func: str, + fewer_norm: bool = False, + ) -> nn.Module: + if expand_ratio == 1: + block = DSConv( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + use_bias=(True, False) if fewer_norm else False, + norm=(None, norm) if fewer_norm else norm, + act_func=(act_func, None), + ) + else: + block = MBConv( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + expand_ratio=expand_ratio, + use_bias=(True, True, False) if fewer_norm else False, + norm=(None, None, norm) if fewer_norm else norm, + act_func=(act_func, act_func, None), + ) + return block + + def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]: + output_dict = {"input": x} + output_dict["stage0"] = x = self.input_stem(x) + for stage_id, stage in enumerate(self.stages, 1): + output_dict[f"stage{stage_id}"] = x = stage(x) + output_dict["stage_final"] = x + return output_dict + + +def efficientvit_backbone_b0(**kwargs: dict[str, Any]) -> EfficientViTBackbone: + """Create EfficientViT B0.""" + backbone = EfficientViTBackbone( + width_list=[8, 16, 32, 64, 128], + depth_list=[1, 2, 2, 2, 2], + dim=16, + **build_kwargs_from_config(kwargs, EfficientViTBackbone), + ) + return backbone + + +def efficientvit_backbone_b1(**kwargs: dict[str, Any]) -> EfficientViTBackbone: + """Create EfficientViT B1.""" + backbone = EfficientViTBackbone( + width_list=[16, 32, 64, 128, 256], + depth_list=[1, 2, 3, 3, 4], + dim=16, + **build_kwargs_from_config(kwargs, EfficientViTBackbone), + ) + return backbone + + +def efficientvit_backbone_b2(**kwargs: dict[str, Any]) -> EfficientViTBackbone: + """Create EfficientViT B2.""" + backbone = EfficientViTBackbone( + width_list=[24, 48, 96, 192, 384], + depth_list=[1, 3, 4, 4, 6], + dim=32, + **build_kwargs_from_config(kwargs, EfficientViTBackbone), + ) + return backbone + + +def efficientvit_backbone_b3(**kwargs: dict[str, Any]) -> EfficientViTBackbone: + """Create EfficientViT B3.""" + backbone = EfficientViTBackbone( + width_list=[32, 64, 128, 256, 512], + depth_list=[1, 4, 6, 6, 9], + dim=32, + **build_kwargs_from_config(kwargs, EfficientViTBackbone), + ) + return backbone + + +class EfficientViTLargeBackbone(nn.Module): + def __init__( + self, + width_list: list[int], + depth_list: list[int], + in_channels: int = 3, + qkv_dim: int = 32, + norm: str = "bn2d", + act_func: str = "gelu", + ) -> None: + super().__init__() + + self.width_list = [] + stages = [] + # stage 0 + stage0 = [ + ConvLayer(in_channels=in_channels, out_channels=width_list[0], stride=2, norm=norm, act_func=act_func) + ] + for _ in range(depth_list[0]): + block = self.build_local_block( + stage_id=0, + in_channels=width_list[0], + out_channels=width_list[0], + stride=1, + expand_ratio=1, + norm=norm, + act_func=act_func, + ) + stage0.append(ResidualBlock(block, IdentityLayer())) + in_channels = width_list[0] + stages.append(OpSequential(stage0)) + self.width_list.append(in_channels) + + for stage_id, (w, d) in enumerate(zip(width_list[1:4], depth_list[1:4]), start=1): + stage = [] + for i in range(d + 1): + stride = 2 if i == 0 else 1 + block = self.build_local_block( + stage_id=stage_id, + in_channels=in_channels, + out_channels=w, + stride=stride, + expand_ratio=4 if stride == 1 else 16, + norm=norm, + act_func=act_func, + fewer_norm=stage_id > 2, + ) + block = ResidualBlock(block, IdentityLayer() if stride == 1 else None) + stage.append(block) + in_channels = w + stages.append(OpSequential(stage)) + self.width_list.append(in_channels) + + for stage_id, (w, d) in enumerate(zip(width_list[4:], depth_list[4:]), start=4): + stage = [] + block = self.build_local_block( + stage_id=stage_id, + in_channels=in_channels, + out_channels=w, + stride=2, + expand_ratio=24, + norm=norm, + act_func=act_func, + fewer_norm=True, + ) + stage.append(ResidualBlock(block, None)) + in_channels = w + + for _ in range(d): + stage.append( + EfficientViTBlock( + in_channels=in_channels, dim=qkv_dim, expand_ratio=6, norm=norm, act_func=act_func + ) + ) + stages.append(OpSequential(stage)) + self.width_list.append(in_channels) + self.stages = nn.ModuleList(stages) + + @staticmethod + def build_local_block( + stage_id: int, + in_channels: int, + out_channels: int, + stride: int, + expand_ratio: float, + norm: str, + act_func: str, + fewer_norm: bool = False, + ) -> nn.Module: + if expand_ratio == 1: + block = ResBlock( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + use_bias=(True, False) if fewer_norm else False, + norm=(None, norm) if fewer_norm else norm, + act_func=(act_func, None), + ) + elif stage_id <= 2: + block = FusedMBConv( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + expand_ratio=expand_ratio, + use_bias=(True, False) if fewer_norm else False, + norm=(None, norm) if fewer_norm else norm, + act_func=(act_func, None), + ) + else: + block = MBConv( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + expand_ratio=expand_ratio, + use_bias=(True, True, False) if fewer_norm else False, + norm=(None, None, norm) if fewer_norm else norm, + act_func=(act_func, act_func, None), + ) + return block + + def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]: + output_dict = {"input": x} + for stage_id, stage in enumerate(self.stages): + output_dict[f"stage{stage_id}"] = x = stage(x) + output_dict["stage_final"] = x + return output_dict + + +def efficientvit_backbone_l0(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone: + """Create EfficientViT L0.""" + backbone = EfficientViTLargeBackbone( + width_list=[32, 64, 128, 256, 512], + depth_list=[1, 1, 1, 4, 4], + **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone), + ) + return backbone + + +def efficientvit_backbone_l1(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone: + """Create EfficientViT L.""" + backbone = EfficientViTLargeBackbone( + width_list=[32, 64, 128, 256, 512], + depth_list=[1, 1, 1, 6, 6], + **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone), + ) + return backbone + + +def efficientvit_backbone_l2(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone: + """Create EfficientViT L2.""" + backbone = EfficientViTLargeBackbone( + width_list=[32, 64, 128, 256, 512], + depth_list=[1, 2, 2, 8, 8], + **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone), + ) + return backbone + + +def efficientvit_backbone_l3(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone: + """Create EfficientViT L3.""" + backbone = EfficientViTLargeBackbone( + width_list=[64, 128, 256, 512, 1024], + depth_list=[1, 2, 2, 8, 8], + **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone), + ) + return backbone diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/model.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/model.py new file mode 100644 index 0000000000000000000000000000000000000000..253bf90966d65146d774fc0ee4b886f83720274c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/model.py @@ -0,0 +1,111 @@ +# 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. +# + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal + +import torch + +from kornia.contrib.models.base import ModelBase +from kornia.contrib.models.efficient_vit import backbone as vit +from kornia.core import Tensor + + +def _get_base_url(model_type: Literal["b1", "b2", "b3"] = "b1", resolution: Literal[224, 256, 288] = 224) -> str: + """Return the base URL of the model weights.""" + return f"https://huggingface.co/kornia/efficientvit_imagenet_{model_type}_r{resolution}/resolve/main/{model_type}-r{resolution}.pt" + + +@dataclass +class EfficientViTConfig: + """Configuration to construct EfficientViT model. + + Model weights can be loaded from a checkpoint URL or local path. + The model weights are hosted on HuggingFace's model hub: https://huggingface.co/kornia. + + Args: + checkpoint: URL or local path of model weights. + + """ + + checkpoint: str = field(default_factory=_get_base_url) + + @classmethod + def from_pretrained( + cls, model_type: Literal["b1", "b2", "b3"], resolution: Literal[224, 256, 288] + ) -> EfficientViTConfig: + """Return a configuration object from a pre-trained model. + + Args: + model_type: model type, one of :obj:`"b1"`, :obj:`"b2"`, :obj:`"b3"`. + resolution: input resolution, one of :obj:`224`, :obj:`256`, :obj:`288`. + + """ + return cls(checkpoint=_get_base_url(model_type=model_type, resolution=resolution)) + + +class EfficientViT(ModelBase[EfficientViTConfig]): + """EfficientViT backbone model.""" + + def __init__(self, backbone: vit.EfficientViTBackbone | vit.EfficientViTLargeBackbone) -> None: + super().__init__() + self.backbone = backbone + + @staticmethod + def from_config(config: EfficientViTConfig) -> EfficientViT: + """Build the EfficientViT model from a configuration object. + + Args: + config: EfficientViT configuration object. See :class:`EfficientViTConfig`. + + Returns: + EfficientViT: the EfficientViT model. + + """ + # load the model from the checkpoint + try: + model_file = torch.hub.load_state_dict_from_url(config.checkpoint, map_location="cpu") + model_file = model_file["state_dict"] if "state_dict" in model_file else model_file + except RuntimeError: + raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from None + + file_name = config.checkpoint.split("/")[-1] + model_type = file_name.split("-")[0] + + if model_type not in ["b0", "b1", "b2", "b3", "l0", "l1", "l2", "l3"]: + raise ValueError(f"Unknown model type: {model_type}.") + + # create and load the model weights without strict until we polish the model files + model = getattr(vit, f"efficientvit_backbone_{model_type}")() + model.load_state_dict(model_file, strict=False) + + return EfficientViT(backbone=model) + + def forward(self, images: Tensor) -> Tensor: + """Extract features from the input images. + + Args: + images: input images tensor of shape :math:`(B, C, H, W)`. + + Returns: + Dict[str, Tensor]: a dictionary containing the features. + + """ + feats = self.backbone(images) + return feats diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d273d5cba09827eabbe13c7f953f35f94a5f9ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/__init__.py @@ -0,0 +1,16 @@ +# 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. +# diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/act.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/act.py new file mode 100644 index 0000000000000000000000000000000000000000..0faa48c38aa06bcec030096e1cafed31a760a492 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/act.py @@ -0,0 +1,47 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 +from __future__ import annotations + +from functools import partial +from typing import Any, Optional, Union + +from torch import nn + +from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config + +# register activation function here +REGISTERED_ACT_DICT: dict[str, type[nn.Module]] = { + "relu": nn.ReLU, + "relu6": nn.ReLU6, + "hswish": nn.Hardswish, + "silu": nn.SiLU, + "gelu": partial(nn.GELU, approximate="tanh"), # type: ignore +} + + +def build_act(name: Optional[str], **kwargs: dict[str, Any]) -> Union[nn.Module, None]: + """Return activation op.""" + if name in REGISTERED_ACT_DICT: + act_cls = REGISTERED_ACT_DICT[name] + args = build_kwargs_from_config(kwargs, act_cls) + return act_cls(**args) + + return None diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/norm.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8b721c90a93ef11b08940b694d3e5f20b3b917 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/norm.py @@ -0,0 +1,55 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 +from __future__ import annotations + +from typing import Any, Optional + +import torch +from torch import nn + +from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config + + +class LayerNorm2d(nn.LayerNorm): + def forward(self, x: torch.Tensor) -> torch.Tensor: + out = x - torch.mean(x, dim=1, keepdim=True) + out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps) + if self.elementwise_affine: + out = out * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1) + return out + + +# register normalization function here +REGISTERED_NORM_DICT: dict[str, type] = {"bn2d": nn.BatchNorm2d, "ln": nn.LayerNorm, "ln2d": LayerNorm2d} + + +def build_norm(name: str = "bn2d", num_features: Optional[int] = None, **kwargs: Any) -> Optional[nn.Module]: + """Return norm op.""" + if name in ["ln", "ln2d"]: + kwargs["normalized_shape"] = num_features + else: + kwargs["num_features"] = num_features + if name in REGISTERED_NORM_DICT: + norm_cls = REGISTERED_NORM_DICT[name] + args = build_kwargs_from_config(kwargs, norm_cls) + return norm_cls(**args) + else: + return None diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/ops.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7a680455d0c071539c21c6d4a6a19e32380744 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/nn/ops.py @@ -0,0 +1,431 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 + +# type: ignore +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.contrib.models.efficient_vit.nn.act import build_act +from kornia.contrib.models.efficient_vit.nn.norm import build_norm +from kornia.contrib.models.efficient_vit.utils import get_same_padding, val2tuple +from kornia.utils._compat import autocast + +__all__ = [ + "ConvLayer", + "DSConv", + "EfficientViTBlock", + "FusedMBConv", + "IdentityLayer", + "MBConv", + "OpSequential", + "ResBlock", + "ResidualBlock", +] + +################################################################################# +# Basic Layers # +################################################################################# + + +class ConvLayer(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size=3, + stride=1, + dilation=1, + groups=1, + use_bias=False, + dropout=0, + norm="bn2d", + act_func="relu", + ): + super().__init__() + + padding = get_same_padding(kernel_size) + padding *= dilation + + self.dropout = nn.Dropout2d(dropout, inplace=False) if dropout > 0 else None + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size=(kernel_size, kernel_size), + stride=(stride, stride), + padding=padding, + dilation=(dilation, dilation), + groups=groups, + bias=use_bias, + ) + self.norm = build_norm(norm, num_features=out_channels) + self.act = build_act(act_func) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.dropout is not None: + x = self.dropout(x) + x = self.conv(x) + if self.norm: + x = self.norm(x) + if self.act: + x = self.act(x) + return x + + +class IdentityLayer(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + + +################################################################################# +# Basic Blocks # +################################################################################# + + +class DSConv(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size=3, + stride=1, + use_bias=False, + norm=("bn2d", "bn2d"), + act_func=("relu6", None), + ): + super().__init__() + + use_bias = val2tuple(use_bias, 2) + norm = val2tuple(norm, 2) + act_func = val2tuple(act_func, 2) + + self.depth_conv = ConvLayer( + in_channels, + in_channels, + kernel_size, + stride, + groups=in_channels, + norm=norm[0], + act_func=act_func[0], + use_bias=use_bias[0], + ) + self.point_conv = ConvLayer( + in_channels, out_channels, 1, norm=norm[1], act_func=act_func[1], use_bias=use_bias[1] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.depth_conv(x) + x = self.point_conv(x) + return x + + +class MBConv(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size=3, + stride=1, + mid_channels=None, + expand_ratio=6, + use_bias=False, + norm=("bn2d", "bn2d", "bn2d"), + act_func=("relu6", "relu6", None), + ): + super().__init__() + + use_bias = val2tuple(use_bias, 3) + norm = val2tuple(norm, 3) + act_func = val2tuple(act_func, 3) + mid_channels = mid_channels or round(in_channels * expand_ratio) + + self.inverted_conv = ConvLayer( + in_channels, mid_channels, 1, stride=1, norm=norm[0], act_func=act_func[0], use_bias=use_bias[0] + ) + self.depth_conv = ConvLayer( + mid_channels, + mid_channels, + kernel_size, + stride=stride, + groups=mid_channels, + norm=norm[1], + act_func=act_func[1], + use_bias=use_bias[1], + ) + self.point_conv = ConvLayer( + mid_channels, out_channels, 1, norm=norm[2], act_func=act_func[2], use_bias=use_bias[2] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.inverted_conv(x) + x = self.depth_conv(x) + x = self.point_conv(x) + return x + + +class FusedMBConv(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size=3, + stride=1, + mid_channels=None, + expand_ratio=6, + groups=1, + use_bias=False, + norm=("bn2d", "bn2d"), + act_func=("relu6", None), + ): + super().__init__() + use_bias = val2tuple(use_bias, 2) + norm = val2tuple(norm, 2) + act_func = val2tuple(act_func, 2) + + mid_channels = mid_channels or round(in_channels * expand_ratio) + + self.spatial_conv = ConvLayer( + in_channels, + mid_channels, + kernel_size, + stride, + groups=groups, + use_bias=use_bias[0], + norm=norm[0], + act_func=act_func[0], + ) + self.point_conv = ConvLayer( + mid_channels, out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.spatial_conv(x) + x = self.point_conv(x) + return x + + +class ResBlock(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size=3, + stride=1, + mid_channels=None, + expand_ratio=1, + use_bias=False, + norm=("bn2d", "bn2d"), + act_func=("relu6", None), + ): + super().__init__() + use_bias = val2tuple(use_bias, 2) + norm = val2tuple(norm, 2) + act_func = val2tuple(act_func, 2) + + mid_channels = mid_channels or round(in_channels * expand_ratio) + + self.conv1 = ConvLayer( + in_channels, mid_channels, kernel_size, stride, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0] + ) + self.conv2 = ConvLayer( + mid_channels, out_channels, kernel_size, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.conv1(x) + x = self.conv2(x) + return x + + +class LiteMLA(nn.Module): + r"""Lightweight multi-scale linear attention.""" + + def __init__( + self, + in_channels: int, + out_channels: int, + heads: int or None = None, + heads_ratio: float = 1.0, + dim=8, + use_bias=False, + norm=(None, "bn2d"), + act_func=(None, None), + kernel_func="relu", + scales: tuple[int, ...] = (5,), + eps=1.0e-15, + ): + super().__init__() + self.eps = eps + heads = heads or int(in_channels // dim * heads_ratio) + + total_dim = heads * dim + + use_bias = val2tuple(use_bias, 2) + norm = val2tuple(norm, 2) + act_func = val2tuple(act_func, 2) + + self.dim = dim + self.qkv = ConvLayer(in_channels, 3 * total_dim, 1, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0]) + self.aggreg = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d( + 3 * total_dim, + 3 * total_dim, + scale, + padding=get_same_padding(scale), + groups=3 * total_dim, + bias=use_bias[0], + ), + nn.Conv2d(3 * total_dim, 3 * total_dim, 1, groups=3 * heads, bias=use_bias[0]), + ) + for scale in scales + ] + ) + self.kernel_func = build_act(kernel_func, inplace=False) + + self.proj = ConvLayer( + total_dim * (1 + len(scales)), out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1] + ) + + @autocast(enabled=False) + def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor: + B, _, H, W = list(qkv.size()) + + if qkv.dtype == torch.float16: + qkv = qkv.float() + + qkv = torch.reshape(qkv, (B, -1, 3 * self.dim, H * W)) + qkv = torch.transpose(qkv, -1, -2) + q, k, v = (qkv[..., 0 : self.dim], qkv[..., self.dim : 2 * self.dim], qkv[..., 2 * self.dim :]) + + # lightweight linear attention + q = self.kernel_func(q) + k = self.kernel_func(k) + + # linear matmul + trans_k = k.transpose(-1, -2) + + v = F.pad(v, (0, 1), mode="constant", value=1) + kv = torch.matmul(trans_k, v) + out = torch.matmul(q, kv) + out = out[..., :-1] / (out[..., -1:] + self.eps) + + out = torch.transpose(out, -1, -2) + out = torch.reshape(out, (B, -1, H, W)) + return out + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # generate multi-scale q, k, v + qkv = self.qkv(x) + multi_scale_qkv = [qkv] + for op in self.aggreg: + multi_scale_qkv.append(op(qkv)) + multi_scale_qkv = torch.cat(multi_scale_qkv, dim=1) + + out = self.relu_linear_att(multi_scale_qkv) + out = self.proj(out) + + return out + + +class EfficientViTBlock(nn.Module): + def __init__( + self, + in_channels: int, + heads_ratio: float = 1.0, + dim=32, + expand_ratio: float = 4, + norm="bn2d", + act_func="hswish", + ): + super().__init__() + self.context_module = ResidualBlock( + LiteMLA( + in_channels=in_channels, out_channels=in_channels, heads_ratio=heads_ratio, dim=dim, norm=(None, norm) + ), + IdentityLayer(), + ) + local_module = MBConv( + in_channels=in_channels, + out_channels=in_channels, + expand_ratio=expand_ratio, + use_bias=(True, True, False), + norm=(None, None, norm), + act_func=(act_func, act_func, None), + ) + self.local_module = ResidualBlock(local_module, IdentityLayer()) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.context_module(x) + x = self.local_module(x) + return x + + +################################################################################# +# Functional Blocks # +################################################################################# + + +class ResidualBlock(nn.Module): + def __init__( + self, main: nn.Module or None, shortcut: nn.Module or None, post_act=None, pre_norm: nn.Module or None = None + ): + super().__init__() + + self.pre_norm = pre_norm + self.main = main + self.shortcut = shortcut + self.post_act = build_act(post_act) + + def forward_main(self, x: torch.Tensor) -> torch.Tensor: + if self.pre_norm is None: + return self.main(x) + else: + return self.main(self.pre_norm(x)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.main is None: + res = x + elif self.shortcut is None: + res = self.forward_main(x) + else: + res = self.forward_main(x) + self.shortcut(x) + if self.post_act: + res = self.post_act(res) + return res + + +class OpSequential(nn.Module): + def __init__(self, op_list: list[nn.Module or None]): + super().__init__() + valid_op_list = [] + for op in op_list: + if op is not None: + valid_op_list.append(op) + self.op_list = nn.ModuleList(valid_op_list) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + for op in self.op_list: + x = op(x) + return x diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2367415791eabb5c421a711b4c4510f562e10b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/__init__.py @@ -0,0 +1,26 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 + +# TODO: promote this to kornia +from .list import val2tuple +from .network import build_kwargs_from_config, get_same_padding + +__all__ = ["build_kwargs_from_config", "get_same_padding", "val2tuple"] diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/list.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/list.py new file mode 100644 index 0000000000000000000000000000000000000000..55a5d64124dd476420b5bc93e8ec27419add984d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/list.py @@ -0,0 +1,44 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 +from __future__ import annotations + +from typing import Any, Union + + +def val2list(x: Union[list[Any], tuple[Any, ...], Any], repeat_time: int = 1) -> list[Any]: + """Convert value to list.""" + if isinstance(x, list): + return x + elif isinstance(x, tuple): + return list(x) + else: + return [x] * repeat_time + + +def val2tuple(x: Union[list[Any], tuple[Any, ...], Any], min_len: int = 1, idx_repeat: int = -1) -> tuple[Any, ...]: + """Convert value to tuple.""" + x = val2list(x) + + # repeat elements if necessary + if len(x) > 0: + x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))] + + return tuple(x) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/network.py b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/network.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8df4b277dd6ffe8116be4efb8bd7e2eb07f718 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/efficient_vit/utils/network.py @@ -0,0 +1,43 @@ +# 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. +# + +# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction +# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han +# International Conference on Computer Vision (ICCV), 2023 +from __future__ import annotations + +from inspect import signature +from typing import Any, Union + + +def get_same_padding(kernel_size: Union[int, tuple[int, ...]]) -> Union[int, tuple[int, ...]]: + """Return padding values.""" + if isinstance(kernel_size, (tuple,)): + return tuple([get_same_padding(ks) for ks in kernel_size]) # type: ignore + + # assert kernel_size % 2 > 0, "kernel size should be odd number" + return kernel_size // 2 + + +def build_kwargs_from_config(config: dict[str, Any], target_func: Any) -> dict[str, Any]: + """Return kwargs from config object.""" + valid_keys = list(signature(target_func).parameters) + kwargs = {} + for key, value in config.items(): + if key in valid_keys: + kwargs[key] = value + return kwargs diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43a75b201f132224bd78dbd67bb7200ad20e2e8e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig, RTDETRModelType +from kornia.contrib.models.rt_detr.post_processor import DETRPostProcessor diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d273d5cba09827eabbe13c7f953f35f94a5f9ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/__init__.py @@ -0,0 +1,16 @@ +# 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. +# diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hgnetv2.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hgnetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..7529b13eb478a2cabd4baa1e33736b792b9237ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hgnetv2.py @@ -0,0 +1,148 @@ +# 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. +# + +"""Based on code from +https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/ +ppdet/modeling/backbones/hgnet_v2.py. +""" # noqa: D205 + +from __future__ import annotations + +from typing import NamedTuple + +from torch import nn + +from kornia.contrib.models.common import ConvNormAct +from kornia.core import Module, Tensor, concatenate +from kornia.core.check import KORNIA_CHECK + + +class StemBlock(Module): + def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None: + super().__init__() + self.stem1 = ConvNormAct(in_channels, mid_channels, 3, 2) + self.stem2a = ConvNormAct(mid_channels, mid_channels // 2, 2) + self.stem2b = ConvNormAct(mid_channels // 2, mid_channels, 2) + self.stem3 = ConvNormAct(mid_channels * 2, mid_channels, 3, 2) + self.stem4 = ConvNormAct(mid_channels, out_channels, 1) + self.pool = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.MaxPool2d(2, 1)) + + def forward(self, x: Tensor) -> Tensor: + x = self.stem1(x) + x = concatenate([self.pool(x), self.stem2b(self.stem2a(x))], 1) + x = self.stem4(self.stem3(x)) + return x + + +# Separable conv +class LightConvNormAct(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, kernel_size: int) -> None: + super().__init__() + self.conv1 = ConvNormAct(in_channels, out_channels, 1, act="none") # point-wise + self.conv2 = ConvNormAct(out_channels, out_channels, kernel_size, groups=out_channels) # depth-wise + + +class StageConfig(NamedTuple): + in_channels: int + mid_channels: int + out_channels: int + num_blocks: int + downsample: bool + light_block: bool + kernel_size: int + layer_num: int + + +class HGBlock(Module): + def __init__(self, in_channels: int, config: StageConfig, identity: bool) -> None: + super().__init__() + self.identity = identity + + layer_cls = LightConvNormAct if config.light_block else ConvNormAct + self.layers = nn.ModuleList() + for i in range(config.layer_num): + ch_in = in_channels if i == 0 else config.mid_channels + self.layers.append(layer_cls(ch_in, config.mid_channels, config.kernel_size)) + + total_channels = in_channels + config.mid_channels * config.layer_num + self.aggregation_squeeze_conv = ConvNormAct(total_channels, config.out_channels // 2, 1) + self.aggregation_excitation_conv = ConvNormAct(config.out_channels // 2, config.out_channels, 1) + + def forward(self, x: Tensor) -> Tensor: + feats = [x] + for layer in self.layers: + feats.append(layer(feats[-1])) + out = concatenate(feats, 1) + out = self.aggregation_squeeze_conv(out) + out = self.aggregation_excitation_conv(out) + return x + out if self.identity else out + + +class HGStage(nn.Sequential): + def __init__(self, config: StageConfig) -> None: + super().__init__() + ch_in = config.in_channels + self.downsample = ConvNormAct(ch_in, ch_in, 3, 2, "none", ch_in) if config.downsample else None + self.blocks = nn.Sequential( + HGBlock(ch_in, config, False), + *[HGBlock(config.out_channels, config, True) for _ in range(config.num_blocks - 1)], + ) + + +class PPHGNetV2(Module): + def __init__(self, stem_channels: list[int], stage_configs: list[StageConfig]) -> None: + KORNIA_CHECK(len(stem_channels) == 3) + KORNIA_CHECK(len(stage_configs) == 4) + super().__init__() + self.out_channels = [config.out_channels for config in stage_configs[-3:]] + self.stem = StemBlock(*stem_channels) + self.stages = nn.ModuleList() + for cfg in stage_configs: + self.stages.append(HGStage(cfg)) + + def forward(self, x: Tensor) -> list[Tensor]: + x = self.stem(x) + s2 = self.stages[0](x) + s3 = self.stages[1](s2) + s4 = self.stages[2](s3) + s5 = self.stages[3](s4) + return [s3, s4, s5] + + @staticmethod + def from_config(variant: str) -> PPHGNetV2: + if variant == "L": + return PPHGNetV2( + stem_channels=[3, 32, 48], + stage_configs=[ + StageConfig(48, 48, 128, 1, False, False, 3, 6), + StageConfig(128, 96, 512, 1, True, False, 3, 6), + StageConfig(512, 192, 1024, 3, True, True, 5, 6), + StageConfig(1024, 384, 2048, 1, True, True, 5, 6), + ], + ) + elif variant == "X": + return PPHGNetV2( + stem_channels=[3, 32, 64], + stage_configs=[ + StageConfig(64, 64, 128, 1, False, False, 3, 6), + StageConfig(128, 128, 512, 2, True, False, 3, 6), + StageConfig(512, 256, 1024, 5, True, True, 5, 6), + StageConfig(1024, 512, 2048, 2, True, True, 5, 6), + ], + ) + else: + raise ValueError("Only variant L and X are supported") diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..aa0e8d1c8e2939e7b3311b2d1d0ab1024f0afff0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py @@ -0,0 +1,246 @@ +# 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. +# + +"""Based on the code from +https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/ +ppdet/modeling/transformers/hybrid_encoder.py. +""" # noqa: D205 + +from __future__ import annotations + +import copy +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.utils.fusion import fuse_conv_bn_weights + +from kornia.contrib.models.common import ConvNormAct +from kornia.core import Module, Tensor, concatenate, pad +from kornia.utils._compat import torch_meshgrid + + +class RepVggBlock(Module): + def __init__(self, in_channels: int, out_channels: int) -> None: + super().__init__() + self.conv1 = ConvNormAct(in_channels, out_channels, 3, act="none") + self.conv2 = ConvNormAct(in_channels, out_channels, 1, act="none") + self.act = nn.SiLU(inplace=True) + self.conv: Optional[nn.Conv2d] = None + + def forward(self, x: Tensor) -> Tensor: + if self.conv is not None: + out = self.act(self.conv(x)) + else: + out = self.act(self.conv1(x) + self.conv2(x)) + return out + + @torch.no_grad() + def optimize_for_deployment(self) -> None: + def _fuse_conv_bn_weights(m: ConvNormAct) -> tuple[nn.Parameter, nn.Parameter]: + if m.norm.running_mean is None or m.norm.running_var is None: + raise ValueError + + return fuse_conv_bn_weights( + m.conv.weight, + m.conv.bias, + m.norm.running_mean, + m.norm.running_var, + m.norm.eps, + m.norm.weight, + m.norm.bias, + ) + + kernel3x3, bias3x3 = _fuse_conv_bn_weights(self.conv1) + kernel1x1, bias1x1 = _fuse_conv_bn_weights(self.conv2) + kernel3x3.add_(pad(kernel1x1, [1, 1, 1, 1])) + bias3x3.add_(bias1x1) + + self.conv = nn.Conv2d(kernel3x3.shape[1], kernel3x3.shape[0], 3, 1, 1) + self.conv.weight = kernel3x3 + self.conv.bias = bias3x3 + + +class CSPRepLayer(Module): + def __init__(self, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0) -> None: + super().__init__() + hidden_channels = int(out_channels * expansion) + self.conv1 = ConvNormAct(in_channels, hidden_channels, 1, act="silu") + self.conv2 = ConvNormAct(in_channels, hidden_channels, 1, act="silu") + self.bottlenecks = nn.Sequential(*[RepVggBlock(hidden_channels, hidden_channels) for _ in range(num_blocks)]) + self.conv3 = ( + ConvNormAct(hidden_channels, out_channels, 1, act="silu") + if hidden_channels != out_channels + else nn.Identity() + ) + + def forward(self, x: Tensor) -> Tensor: + return self.conv3(self.bottlenecks(self.conv1(x)) + self.conv2(x)) + + +# almost identical to nn.TransformerEncoderLayer +# but add positional embeddings to q and k +class AIFI(Module): + def __init__(self, embed_dim: int, num_heads: int, dim_feedforward: int, dropout: float = 0.0) -> None: + super().__init__() + self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout) # NOTE: batch_first = False + + self.linear1 = nn.Linear(embed_dim, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, embed_dim) + + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.norm1 = nn.LayerNorm(embed_dim) + self.norm2 = nn.LayerNorm(embed_dim) + self.act = nn.GELU() + + def forward(self, x: Tensor) -> Tensor: + # using post-norm + N, C, H, W = x.shape + x = x.permute(2, 3, 0, 1).flatten(0, 1) # (N, C, H, W) -> (H * W, N, C) + + # NOTE: cache pos_emb as buffer + pos_emb = self.build_2d_sincos_pos_emb(W, H, C, device=x.device, dtype=x.dtype) + q = k = x + pos_emb + + attn, _ = self.self_attn(q, k, x, need_weights=True) + x = self.norm1(x + self.dropout1(attn)) + x = self.norm2(x + self.dropout2(self.ffn(x))) + + x = x.view(H, W, N, C).permute(2, 3, 0, 1) # (H * W, N, C) -> (N, C, H, W) + return x + + def ffn(self, x: Tensor) -> Tensor: + return self.linear2(self.dropout(self.act(self.linear1(x)))) + + # TODO: make this into a reusable function + # https://github.com/facebookresearch/moco-v3/blob/main/vits.py#L53 + # https://github.com/PaddlePaddle/PaddleDetection/blob/79267419e1743157f376a7cb251e01caa3338ce0/ppdet/modeling/transformers/hybrid_encoder.py#L217 + @staticmethod + def build_2d_sincos_pos_emb( + w: int, + h: int, + embed_dim: int, + temp: float = 10_000.0, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ) -> Tensor: + """Construct 2D sin-cos positional embeddings. + + Args: + w: width of the image or feature map + h: height of the image or feature map + embed_dim: embedding dimension + temp: temperature coefficient + device: device to place the positional embeddings + dtype: data type of the positional embeddings + + Returns: + positional embeddings, shape :math:`(H * W, 1, C)` + + """ + xs = torch.arange(w, device=device, dtype=dtype) + ys = torch.arange(h, device=device, dtype=dtype) + grid_x, grid_y = torch_meshgrid([xs, ys], indexing="ij") + + pos_dim = embed_dim // 4 + omega = torch.arange(pos_dim, device=device, dtype=dtype) / pos_dim + omega = 1.0 / (temp**omega) + + out_x = grid_x.reshape(-1, 1) * omega.view(1, -1) + out_y = grid_y.reshape(-1, 1) * omega.view(1, -1) + + pos_emb = concatenate([out_x.sin(), out_x.cos(), out_y.sin(), out_y.cos()], 1) + return pos_emb.unsqueeze(1) # (H * W, 1, C) + + +class TransformerEncoder(nn.Module): + def __init__(self, encoder_layer: nn.Module, num_layers: int) -> None: + super().__init__() + self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)]) + self.num_layers = num_layers + + def forward(self, src: Tensor) -> Tensor: # NOTE: Missing src_mask: Tensor = None, pos_embed: Tensor = None + output = src + for layer in self.layers: + output = layer(output) + + return output + + +class CCFM(Module): + def __init__(self, num_fmaps: int, hidden_dim: int, expansion: float = 1.0) -> None: + super().__init__() + self.lateral_convs = nn.ModuleList() + self.fpn_blocks = nn.ModuleList() + for _ in range(num_fmaps - 1): + self.lateral_convs.append(ConvNormAct(hidden_dim, hidden_dim, 1, 1, "silu")) + self.fpn_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion)) + + self.downsample_convs = nn.ModuleList() + self.pan_blocks = nn.ModuleList() + for _ in range(num_fmaps - 1): + self.downsample_convs.append(ConvNormAct(hidden_dim, hidden_dim, 3, 2, "silu")) + self.pan_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion)) + + def forward(self, fmaps: list[Tensor]) -> list[Tensor]: + # fmaps is ordered from hi-res to low-res + fmaps = list(fmaps) # shallow clone + + # new_fmaps is ordered from low-res to hi-res + new_fmaps = [fmaps.pop()] + while fmaps: + new_fmaps[-1] = self.lateral_convs[len(new_fmaps) - 1](new_fmaps[-1]) + up_lowres_fmap = F.interpolate(new_fmaps[-1], scale_factor=2.0, mode="nearest") + hires_fmap = fmaps.pop() + + concat_fmap = concatenate([up_lowres_fmap, hires_fmap], 1) + new_fmaps.append(self.fpn_blocks[len(new_fmaps) - 1](concat_fmap)) + + fmaps = [new_fmaps.pop()] + while new_fmaps: + down_hires_fmap = self.downsample_convs[len(fmaps) - 1](fmaps[-1]) + lowres_fmap = new_fmaps.pop() + + concat_fmap = concatenate([down_hires_fmap, lowres_fmap], 1) + fmaps.append(self.pan_blocks[len(fmaps) - 1](concat_fmap)) + + return fmaps + + +class HybridEncoder(Module): + def __init__(self, in_channels: list[int], hidden_dim: int, dim_feedforward: int, expansion: float = 1.0) -> None: + super().__init__() + self.input_proj = nn.ModuleList( + [ + ConvNormAct( # To align the naming strategy for the official weights + in_ch, hidden_dim, 1, act="none", conv_naming="0", norm_naming="1", act_naming="2" + ) + for in_ch in in_channels + ] + ) + encoder_layer = AIFI(hidden_dim, 8, dim_feedforward) + self.encoder = nn.Sequential(TransformerEncoder(encoder_layer, 1)) + self.ccfm = CCFM(len(in_channels), hidden_dim, expansion) + + def forward(self, fmaps: list[Tensor]) -> list[Tensor]: + projected_maps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)] + projected_maps[-1] = self.encoder(projected_maps[-1]) + new_fmaps = self.ccfm(projected_maps) + return new_fmaps diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/resnet_d.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/resnet_d.py new file mode 100644 index 0000000000000000000000000000000000000000..a9cead84f53409c9270ce6e623db54308b06f521 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/resnet_d.py @@ -0,0 +1,154 @@ +# 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. +# + +"""ResNet-D as described in https://arxiv.org/abs/1812.01187. + +Based on the code from https://github.com/pytorch/vision/blob/v0.15.1/torchvision/models/resnet.py +https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.6/ppdet/modeling/backbones/resnet.py +""" + +from __future__ import annotations + +from collections import OrderedDict + +from torch import nn + +from kornia.contrib.models.common import ConvNormAct +from kornia.core import Module, Tensor +from kornia.core.check import KORNIA_CHECK + + +def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> Module: + return ( + nn.Sequential( + OrderedDict([("pool", nn.AvgPool2d(2, 2)), ("conv", ConvNormAct(in_channels, out_channels, 1, act="none"))]) + ) + if stride == 2 + else ConvNormAct(in_channels, out_channels, 1, act="none") + ) + + +class BasicBlockD(Module): + expansion = 1 + + def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None: + KORNIA_CHECK(stride in {1, 2}) + super().__init__() + self.convs = nn.Sequential( + OrderedDict( + [ + ("branch2a", ConvNormAct(in_channels, out_channels, 3, stride=stride)), + ("branch2b", ConvNormAct(out_channels, out_channels, 3, act="none")), + ] + ) + ) + self.short = nn.Identity() if shortcut else _make_shortcut(in_channels, out_channels, stride) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x: Tensor) -> Tensor: + return self.relu(self.convs(x) + self.short(x)) + + +class BottleneckD(Module): + expansion = 4 + + def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None: + KORNIA_CHECK(stride in {1, 2}) + super().__init__() + expanded_out_channels = out_channels * self.expansion + self.convs = nn.Sequential( + OrderedDict( + [ + ("branch2a", ConvNormAct(in_channels, out_channels, 1)), + ("branch2b", ConvNormAct(out_channels, out_channels, 3, stride=stride)), + ("branch2c", ConvNormAct(out_channels, expanded_out_channels, 1, act="none")), + ] + ) + ) + self.short = nn.Identity() if shortcut else _make_shortcut(in_channels, expanded_out_channels, stride) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x: Tensor) -> Tensor: + return self.relu(self.convs(x) + self.short(x)) + + +class Block(nn.Sequential): + def __init__(self, blocks: Module) -> None: + super().__init__() + self.blocks = blocks + + +class ResNetD(Module): + def __init__(self, n_blocks: list[int], block: type[BasicBlockD | BottleneckD]) -> None: + KORNIA_CHECK(len(n_blocks) == 4) + super().__init__() + in_channels = 64 + self.conv1 = nn.Sequential( + OrderedDict( + [ + ("conv1_1", ConvNormAct(3, in_channels // 2, 3, stride=2)), + ("conv1_2", ConvNormAct(in_channels // 2, in_channels // 2, 3)), + ("conv1_3", ConvNormAct(in_channels // 2, in_channels, 3)), + ("pool", nn.MaxPool2d(3, stride=2, padding=1)), + ] + ) + ) + + res2, in_channels = self.make_stage(in_channels, 64, 1, n_blocks[0], block) + res3, in_channels = self.make_stage(in_channels, 128, 2, n_blocks[1], block) + res4, in_channels = self.make_stage(in_channels, 256, 2, n_blocks[2], block) + res5, in_channels = self.make_stage(in_channels, 512, 2, n_blocks[3], block) + + self.res_layers = nn.ModuleList([res2, res3, res4, res5]) + + self.out_channels = [ch * block.expansion for ch in [128, 256, 512]] + + @staticmethod + def make_stage( + in_channels: int, out_channels: int, stride: int, n_blocks: int, block: type[BasicBlockD | BottleneckD] + ) -> tuple[Module, int]: + stage = Block( + nn.Sequential( + block(in_channels, out_channels, stride, False), + *[block(out_channels * block.expansion, out_channels, 1, True) for _ in range(n_blocks - 1)], + ) + ) + return stage, out_channels * block.expansion + + def forward(self, x: Tensor) -> list[Tensor]: + x = self.conv1(x) + res2 = self.res_layers[0](x) + res3 = self.res_layers[1](res2) + res4 = self.res_layers[2](res3) + res5 = self.res_layers[3](res4) + return [res3, res4, res5] + + @staticmethod + def from_config(variant: str | int) -> ResNetD: + variant = str(variant) + if variant == "18": + return ResNetD([2, 2, 2, 2], BasicBlockD) + elif variant == "34": + return ResNetD([3, 4, 6, 3], BasicBlockD) + elif variant == "50": + return ResNetD([3, 4, 6, 3], BottleneckD) + elif variant == "101": + return ResNetD([3, 4, 23, 3], BottleneckD) + elif variant == "152": + return ResNetD([3, 8, 36, 3], BottleneckD) + else: + raise ValueError("Only variant 18, 34, 50, 101, and 152 are supported") diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..28320af84f3c5137c7d0c13ce7ad3b0acab026bb --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py @@ -0,0 +1,494 @@ +# 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. +# + +# Based on code from: +# https://github.com/lyuwenyu/RT-DETR/blob/8a1b85a91f527bed0c4e2424a7a6b4bcdd200fb1/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py + +from __future__ import annotations + +import copy +from typing import Optional + +import torch +from torch import nn + +from kornia.contrib.models.common import MLP, ConvNormAct +from kornia.core import Module, Tensor, concatenate +from kornia.utils._compat import torch_meshgrid + + +def _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: + """Inverse sigmoid function. + + Args: + x: input tensor + eps: epsilon value for numerical stability + + Returns: + output tensor + + """ + out = x.clip(min=0.0, max=1.0) + return torch.log(out.clip(min=eps) / (1.0 - out).clip(min=eps)) + + +def _deformable_attention_kernel( + value: Tensor, value_spatial_shapes: list[tuple[int, int]], sampling_locations: Tensor, attention_weights: Tensor +) -> Tensor: + """Deformable Attention Kernel used in Deformable DETR. + + Described in https://arxiv.org/abs/2010.04159. + + Args: + value: shape (N, Lv, n_head * C) + value_spatial_shapes: [(H0, W0), (H1, W1), ...] + sampling_locations: shape (N, Lq, n_head, n_levels, n_points, 2) + attention_weights: shape (N, Lq, n_head, n_levels, n_points) + + Returns: + output, shape (N, Lq, n_head * C) + + """ + bs, _, n_head, c = value.shape + _, Len_q, _, n_levels, n_points, _ = sampling_locations.shape + + split_shape: list[int] = [h * w for h, w in value_spatial_shapes] + value_list = value.split(split_shape, dim=1) + sampling_grids = 2 * sampling_locations - 1 + + sampling_value_list: list[Tensor] = [] + for level, (h, w) in enumerate(value_spatial_shapes): + # N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_ + value_l_ = value_list[level].flatten(2).permute(0, 2, 1).reshape(bs * n_head, c, h, w) + # N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2 + sampling_grid_l_ = sampling_grids[:, :, :, level].permute(0, 2, 1, 3, 4).flatten(0, 1) + # N_*M_, D_, Lq_, P_ + sampling_value_l_ = torch.nn.functional.grid_sample( + value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False + ) + sampling_value_list.append(sampling_value_l_) + + # (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_*M_, 1, Lq_, L_*P_) + attention_weights = attention_weights.permute(0, 2, 1, 3, 4).reshape(bs * n_head, 1, Len_q, n_levels * n_points) + output = ( + (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights) + .sum(-1) + .reshape(bs, n_head * c, Len_q) + ) + + return output.permute(0, 2, 1) + + +class MultiScaleDeformableAttention(Module): + """Multi-scale Deformable Attention used in Deformable DETR. + + Described in https://arxiv.org/abs/2010.04159. + """ + + def __init__(self, embed_dim: int, num_heads: int, num_levels: int, num_points: int) -> None: + super().__init__() + self.num_heads = num_heads + self.num_levels = num_levels + self.num_points = num_points + self.total_points = num_heads * num_levels * num_points + + self.head_dim = embed_dim // num_heads + # KORNIA_CHECK not working with onnx + # assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads" + + self.sampling_offsets = nn.Linear(embed_dim, self.total_points * 2) + self.attention_weights = nn.Linear(embed_dim, self.total_points) + self.value_proj = nn.Linear(embed_dim, embed_dim) + self.output_proj = nn.Linear(embed_dim, embed_dim) + + def forward( + self, query: Tensor, reference_points: Tensor, value: Tensor, value_spatial_shapes: list[tuple[int, int]] + ) -> Tensor: + """Run forward. + + Args: + query: shape (N, Lq, C) + reference_points: shape (N, Lq, n_levels, 4) + value: shape (N, Lv, C) + value_spatial_shapes: [(H0, W0), (H1, W1), ...] + + Returns: + output, shape (N, Lq, C) + + """ + N, Lenq, _ = query.shape + _, Len_v, _ = value.shape + + sampling_offsets = self.sampling_offsets(query).reshape( + N, Lenq, self.num_heads, self.num_levels, self.num_points, 2 + ) + attention_weights = self.attention_weights(query).reshape( + N, Lenq, self.num_heads, self.num_levels * self.num_points + ) + attention_weights = attention_weights.softmax(-1).reshape( + N, Lenq, self.num_heads, self.num_levels, self.num_points + ) + + # prepare the spatial sampling grid + reference_points_cxcy = reference_points[:, :, None, :, None, :2] + reference_points_wh = reference_points[:, :, None, :, None, 2:] + sampling_locations = reference_points_cxcy + sampling_offsets / self.num_points * reference_points_wh * 0.5 + + value_buf = self.value_proj(value).reshape(N, Len_v, self.num_heads, self.head_dim) + + out = _deformable_attention_kernel(value_buf, value_spatial_shapes, sampling_locations, attention_weights) + + # final projection + out = self.output_proj(out) + + return out + + +class TransformerDecoderLayer(Module): + """Deformable Transformer Decoder layer used in Deformable DETR. + + Described in: https://arxiv.org/abs/2010.04159. + """ + + def __init__(self, embed_dim: int, num_heads: int, dropout: float, num_levels: int, num_points: int) -> None: + super().__init__() + # self attn + self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout, batch_first=True) + self.dropout1 = nn.Dropout(dropout) + self.norm1 = nn.LayerNorm(embed_dim) + + # cross attn + self.cross_attn = MultiScaleDeformableAttention(embed_dim, num_heads, num_levels, num_points) + self.dropout2 = nn.Dropout(dropout) + self.norm2 = nn.LayerNorm(embed_dim) + + # ffn + self.linear1 = nn.Linear(embed_dim, embed_dim * 4) + self.activation = nn.ReLU(inplace=True) + self.dropout3 = nn.Dropout(dropout) + self.linear2 = nn.Linear(embed_dim * 4, embed_dim) + self.dropout4 = nn.Dropout(dropout) + self.norm3 = nn.LayerNorm(embed_dim) + + def _ffn(self, x: Tensor) -> Tensor: + return self.linear2(self.dropout3(self.activation(self.linear1(x)))) + + def forward( + self, + tgt: Tensor, + ref_points: Tensor, + memory: Tensor, + memory_spatial_shapes: list[tuple[int, int]], + memory_level_start_index: Optional[list[int]] = None, + attn_mask: Optional[Tensor] = None, + memory_mask: Optional[Tensor] = None, + query_pos_embed: Optional[Tensor] = None, + ) -> Tensor: + # TODO: rename variables because is confusing + # self attention + q = k = tgt + query_pos_embed + out, _ = self.self_attn(q, k, value=tgt) + tgt = self.norm1(tgt + self.dropout1(out)) + + # cross attention + out = self.cross_attn(tgt + query_pos_embed, ref_points, memory, memory_spatial_shapes) + tgt = self.norm2(tgt + self.dropout2(out)) + + # ffn + out = self.norm3(tgt + self.dropout4(self._ffn(tgt))) + + return out + + +class TransformerDecoder(Module): + def __init__(self, hidden_dim: int, decoder_layer: nn.Module, num_layers: int, eval_idx: int = -1) -> None: + super().__init__() + self.layers = nn.ModuleList([copy.deepcopy(decoder_layer) for _ in range(num_layers)]) + self.hidden_dim = hidden_dim + self.num_layers = num_layers + self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx + + def forward( + self, + tgt: Tensor, + ref_points_unact: Tensor, + memory: Tensor, + memory_spatial_shapes: list[tuple[int, int]], + memory_level_start_index: list[int], + bbox_head: nn.ModuleList, + score_head: nn.ModuleList, + query_pos_head: nn.Module, + attn_mask: Optional[Tensor] = None, + memory_mask: Optional[Tensor] = None, + ) -> tuple[Tensor, Tensor]: + output: Tensor = tgt + dec_out_bboxes: list[Tensor] = [] + dec_out_logits: list[Tensor] = [] + ref_points_detach = torch.sigmoid(ref_points_unact) + + for i, layer in enumerate(self.layers): + ref_points_input = ref_points_detach.unsqueeze(2) + query_pos_embed: Tensor = query_pos_head(ref_points_detach) + + output = layer( + output, + ref_points_input, + memory, + memory_spatial_shapes, + memory_level_start_index, + attn_mask, + memory_mask, + query_pos_embed, + ) + + inter_ref_bbox = torch.sigmoid(bbox_head[i](output) + _inverse_sigmoid(ref_points_detach)) + + # TODO: will be supported later + # if self.training: + # dec_out_logits.append(score_head[i](output)) + # if i == 0: + # dec_out_bboxes.append(inter_ref_bbox) + # else: + # dec_out_bboxes.append(torch.sigmoid(bbox_head[i](output) + _inverse_sigmoid(ref_points))) + # elif i == self.eval_idx: + # dec_out_logits.append(score_head[i](output)) + # dec_out_bboxes.append(inter_ref_bbox) + # break + if i == self.eval_idx: + dec_out_logits.append(score_head[i](output)) + dec_out_bboxes.append(inter_ref_bbox) + break + + # ref_points_detach = inter_ref_bbox.detach( + # ) if self.training else inter_ref_bbox + ref_points_detach = inter_ref_bbox + + return torch.stack(dec_out_bboxes), torch.stack(dec_out_logits) + + +class RTDETRHead(Module): + def __init__( + self, + num_classes: int, + hidden_dim: int, + num_queries: int, + in_channels: list[int], + num_decoder_layers: int, + num_heads: int = 8, + num_decoder_points: int = 4, + num_levels: int = 3, + dropout: float = 0.0, + num_denoising: int = 100, + ) -> None: + super().__init__() + self.num_classes = num_classes + self.num_queries = num_queries + # TODO: verify this is correct + if len(in_channels) > num_levels: + raise ValueError(f"`num_levels` cannot be greater than {len(in_channels)}. Got {num_levels}.") + self.num_levels = num_levels + + # build the input projection layers + self.input_proj = nn.ModuleList() + for ch_in in in_channels: + self.input_proj.append(ConvNormAct(ch_in, hidden_dim, 1, act="none")) + # NOTE: might be missing some layers here ? + # https://github.com/lyuwenyu/RT-DETR/blob/main/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L403-L410 + + # NOTE: need to be integrated with the TransformerDecoderLayer + decoder_layer = TransformerDecoderLayer( + embed_dim=hidden_dim, + num_heads=num_heads, + dropout=dropout, + num_levels=self.num_levels, + num_points=num_decoder_points, + ) + + self.decoder = TransformerDecoder( + hidden_dim=hidden_dim, decoder_layer=decoder_layer, num_layers=num_decoder_layers + ) + + # denoising part + if num_denoising > 0: + self.denoising_class_embed = nn.Embedding( + num_classes + 1, hidden_dim, padding_idx=num_classes + ) # not used in evaluation + + # decoder embedding + self.query_pos_head = MLP(4, 2 * hidden_dim, hidden_dim, num_layers=2) + + # encoder head + self.enc_output = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim)) + self.enc_score_head = nn.Linear(hidden_dim, num_classes) + self.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, num_layers=3) + + # decoder head + self.dec_score_head = nn.ModuleList([nn.Linear(hidden_dim, num_classes) for _ in range(num_decoder_layers)]) + self.dec_bbox_head = nn.ModuleList( + [MLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(num_decoder_layers)] + ) + + def forward(self, feats: Tensor) -> tuple[Tensor, Tensor]: + # input projection and embedding + memory, spatial_shapes, level_start_index = self._get_encoder_input(feats) + + # prepare denoising training + denoising_class, denoising_bbox_unact, attn_mask = None, None, None + + target, init_ref_points_unact, enc_topk_bboxes, enc_topk_logits = self._get_decoder_input( + memory, spatial_shapes, denoising_class, denoising_bbox_unact + ) + + # decoder + out_bboxes, out_logits = self.decoder( + target, + init_ref_points_unact, + memory, + spatial_shapes, + level_start_index, + self.dec_bbox_head, + self.dec_score_head, + self.query_pos_head, + attn_mask=attn_mask, + ) + + return out_logits[-1], out_bboxes[-1] + + def _get_encoder_input(self, feats: Tensor) -> tuple[Tensor, list[tuple[int, int]], list[int]]: + # get projection features + proj_feats: list[Tensor] = [self.input_proj[i](feat) for i, feat in enumerate(feats)] + + if self.num_levels > len(proj_feats): + len_srcs = len(proj_feats) + for i in range(len_srcs, self.num_levels): + if i == len_srcs: + proj_feats.append(self.input_proj[i](feats[-1])) + else: + proj_feats.append(self.input_proj[i](proj_feats[-1])) + + # get encoder inputs + feat_flatten_list: list[Tensor] = [] + spatial_shapes: list[tuple[int, int]] = [] + level_start_index: list[int] = [0] + + for _, feat in enumerate(proj_feats): + _, _, h, w = feat.shape + # [b, c, h, w] -> [b, h*w, c] + feat_flatten_list.append(feat.flatten(2).permute(0, 2, 1)) + # [num_levels, 2] + spatial_shapes.append((h, w)) + # [l], start index of each level + level_start_index.append(h * w + level_start_index[-1]) + + # [b, l, c] + feat_flatten: Tensor = concatenate(feat_flatten_list, 1) + + level_start_index.pop() + return feat_flatten, spatial_shapes, level_start_index + + def _get_decoder_input( + self, + memory: Tensor, + spatial_shapes: list[tuple[int, int]], + denoising_class: Optional[Tensor] = None, + denoising_bbox_unact: Optional[Tensor] = None, + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + # prepare input for decoder + # TODO: cache anchors and valid_mask as buffers + anchors, valid_mask = self._generate_anchors(spatial_shapes, device=memory.device, dtype=memory.dtype) + + # memory = torch.where(valid_mask, memory, 0) + memory = valid_mask.to(memory) * memory # TODO fix type error for onnx export + + output_memory = self.enc_output(memory) + + enc_outputs_class = self.enc_score_head(output_memory) + enc_outputs_coord_unact = self.enc_bbox_head(output_memory) + anchors + + _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.num_queries, dim=1) + + reference_points_unact = enc_outputs_coord_unact.gather( + dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_unact.shape[-1]) + ) + + enc_topk_bboxes = torch.sigmoid(reference_points_unact) + if denoising_bbox_unact is not None: + reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1) + + enc_topk_logits = enc_outputs_class.gather( + dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1]) + ) + + # extract region features + target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1])) + + if denoising_class is not None: + target = torch.concat([denoising_class, target], 1) + + return target.detach(), reference_points_unact.detach(), enc_topk_bboxes, enc_topk_logits + + @staticmethod + def _generate_anchors( + spatial_shapes: list[tuple[int, int]], + grid_size: float = 0.05, + eps: float = 0.01, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ) -> tuple[Tensor, Tensor]: + """Generate anchors for RT-DETR. + + Args: + spatial_shapes: shape (width, height) of the feature maps + grid_size: size of the grid + eps: specify the minimum and maximum size of the anchors + device: device to place the anchors + dtype: data type for the anchors + + Returns: + logit of anchors and mask + + """ + # TODO: might make this (or some parts of it) into a separate reusable function + anchors_list: list[Tensor] = [] + + for i, (h, w) in enumerate(spatial_shapes): + # TODO: fix later kornia.utils.create_meshgrid() + grid_y, grid_x = torch_meshgrid( + [torch.arange(h, device=device, dtype=dtype), torch.arange(w, device=device, dtype=dtype)], + indexing="ij", + ) + grid_xy = torch.stack([grid_x, grid_y], -1) # HxWx2 + + # this satisfies onnx export + wh = torch.empty(2, device=device, dtype=dtype) + wh[0] = w + wh[1] = h + + grid_xy = (grid_xy + 0.5) / wh # normalize to [0, 1] + grid_wh = torch.ones_like(grid_xy) * grid_size * (2.0**i) + anchors_list.append(concatenate([grid_xy, grid_wh], -1).reshape(-1, h * w, 4)) + + anchors = concatenate(anchors_list, 1) + valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True) + anchors = torch.log(anchors / (1 - anchors)) # anchors.logit() fails ONNX export + + inf_t = torch.empty(1, device=device, dtype=dtype) + inf_t[0] = float("inf") + + anchors = torch.where(valid_mask, anchors, inf_t) + + return anchors, valid_mask diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/model.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/model.py new file mode 100644 index 0000000000000000000000000000000000000000..d23cdeb11d6e414df6aa3c306cad7c3fd984db08 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/model.py @@ -0,0 +1,297 @@ +# 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. +# + +"""Based on code from PaddleDetection.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import Enum +from typing import Optional + +import torch + +from kornia.contrib.models.base import ModelBase +from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2 +from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEncoder +from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD +from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead +from kornia.core import Tensor + +URLs = { + "rtdetr_r18vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r18vd_dec3_6x_coco_from_paddle.pth", + "rtdetr_r34vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r34vd_dec4_6x_coco_from_paddle.pth", + "rtdetr_r50vd_m": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_m_6x_coco_from_paddle.pth", + "rtdetr_r50vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_6x_coco_from_paddle.pth", + "rtdetr_r101vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r101vd_6x_coco_from_paddle.pth", +} + + +class RTDETRModelType(Enum): + """Enum class that maps RT-DETR model type.""" + + resnet18d = 0 + resnet34d = 1 + resnet50d = 2 + resnet101d = 3 + hgnetv2_l = 4 + hgnetv2_x = 5 + resnet50d_m = 6 + + +@dataclass +class RTDETRConfig: + """Configuration to construct RT-DETR model. + + Args: + model_type: model variant. Available models are + + - ResNetD-18: ``0``, ``'resnet18d'`` or :attr:`RTDETRModelType.resnet18d` + - ResNetD-34: ``1``, ``'resnet34d'`` or :attr:`RTDETRModelType.resnet34d` + - ResNetD-50: ``2``, ``'resnet50d'`` or :attr:`RTDETRModelType.resnet50d` + - ResNetD-101: ``3``, ``'resnet101d'`` or :attr:`RTDETRModelType.resnet101d` + - HGNetV2-L: ``4``, ``'hgnetv2_l'`` or :attr:`RTDETRModelType.hgnetv2_l` + - HGNetV2-X: ``5``, ``'hgnetv2_x'`` or :attr:`RTDETRModelType.hgnetv2_x` + + num_classes: number of classes. + checkpoint: URL or local path of model weights. + neck_hidden_dim: hidden dim for neck. + neck_dim_feedforward: feed-forward network dim for neck. + neck_expansion: expansion ratio for neck. + head_hidden_dim: hidden dim for head. + head_num_queries: number of queries for Deformable DETR transformer decoder. + head_num_decoder_layers: number of decoder layers for Deformable DETR transformer decoder. + + """ + + model_type: RTDETRModelType | str | int + num_classes: int + input_size: int = 640 + checkpoint: Optional[str] = None + + neck_hidden_dim: Optional[int] = None + neck_dim_feedforward: Optional[int] = None + neck_expansion: Optional[float] = None + head_hidden_dim: int = 256 + head_num_queries: int = 300 + head_num_decoder_layers: Optional[int] = None + confidence_threshold: float = 0.3 + + @staticmethod + def from_name(model_name: str, num_classes: int = 80) -> RTDETRConfig: + """Load model without pretrained weights. + + Args: + model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'. + num_classes: Number of classes to detect. + + """ + if model_name == "rtdetr_r18vd": + config = RTDETRConfig(RTDETRModelType.resnet18d, num_classes, input_size=640) + elif model_name == "rtdetr_r34vd": + config = RTDETRConfig(RTDETRModelType.resnet34d, num_classes, input_size=640) + elif model_name == "rtdetr_r50vd_m": + config = RTDETRConfig(RTDETRModelType.resnet50d_m, num_classes, input_size=640) + elif model_name == "rtdetr_r50vd": + config = RTDETRConfig(RTDETRModelType.resnet50d, num_classes, input_size=640) + elif model_name == "rtdetr_r101vd": + config = RTDETRConfig(RTDETRModelType.resnet101d, num_classes, input_size=640) + else: + raise ValueError + + return config + + +class RTDETR(ModelBase[RTDETRConfig]): + """RT-DETR Object Detection model, as described in https://arxiv.org/abs/2304.08069.""" + + def __init__(self, backbone: ResNetD | PPHGNetV2, encoder: HybridEncoder, decoder: RTDETRHead): + """Construct RT-DETR Object Detection model. + + Args: + backbone: backbone network for feature extraction. + encoder: neck network for feature fusion. + decoder: head network to decode features into detection results. + + """ + super().__init__() + self.backbone = backbone + self.encoder = encoder + self.decoder = decoder + + @staticmethod + def from_config(config: RTDETRConfig) -> RTDETR: + """Construct RT-DETR Object Detection model from a config object. + + Args: + config: configuration object for RT-DETR. + + .. note:: + For ``config.neck_hidden_dim``, ``config.neck_dim_feedforward``, ``config.neck_expansion``, and + ``config.head_num_decoder_layers``, if they are ``None``, their values will be replaced with the + default values depending on the ``config.model_type``. See the source code for the default values. + + """ + model_type = config.model_type + if isinstance(model_type, int): + model_type = RTDETRModelType(model_type) + elif isinstance(model_type, str): + model_type = getattr(RTDETRModelType, model_type) + + backbone: ResNetD | PPHGNetV2 + + if model_type == RTDETRModelType.resnet18d: + backbone = ResNetD.from_config(18) + neck_hidden_dim = config.neck_hidden_dim or 256 + neck_dim_feedforward = config.neck_dim_feedforward or 1024 + head_num_decoder_layers = config.head_num_decoder_layers or 3 + neck_expansion = config.neck_expansion or 0.5 + + elif model_type == RTDETRModelType.resnet34d: + backbone = ResNetD.from_config(34) + neck_hidden_dim = config.neck_hidden_dim or 256 + neck_dim_feedforward = config.neck_dim_feedforward or 1024 + head_num_decoder_layers = config.head_num_decoder_layers or 4 + neck_expansion = config.neck_expansion or 0.5 + + elif model_type == RTDETRModelType.resnet50d: + backbone = ResNetD.from_config(50) + neck_hidden_dim = config.neck_hidden_dim or 256 + neck_dim_feedforward = config.neck_dim_feedforward or 1024 + head_num_decoder_layers = config.head_num_decoder_layers or 6 + neck_expansion = config.neck_expansion or 1.0 + + elif model_type == RTDETRModelType.resnet50d_m: + backbone = ResNetD.from_config(50) + neck_hidden_dim = config.neck_hidden_dim or 256 + neck_dim_feedforward = config.neck_dim_feedforward or 1024 + head_num_decoder_layers = config.head_num_decoder_layers or 6 + neck_expansion = config.neck_expansion or 0.5 + + elif model_type == RTDETRModelType.resnet101d: + backbone = ResNetD.from_config(101) + neck_hidden_dim = config.neck_hidden_dim or 384 + neck_dim_feedforward = config.neck_dim_feedforward or 2048 + head_num_decoder_layers = config.head_num_decoder_layers or 6 + neck_expansion = config.neck_expansion or 1.0 + + elif model_type == RTDETRModelType.hgnetv2_l: + backbone = PPHGNetV2.from_config("L") + neck_hidden_dim = config.neck_hidden_dim or 256 + neck_dim_feedforward = config.neck_dim_feedforward or 1024 + head_num_decoder_layers = config.head_num_decoder_layers or 6 + neck_expansion = config.neck_expansion or 1.0 + + elif model_type == RTDETRModelType.hgnetv2_x: + backbone = PPHGNetV2.from_config("X") + neck_hidden_dim = config.neck_hidden_dim or 384 + neck_dim_feedforward = config.neck_dim_feedforward or 2048 + head_num_decoder_layers = config.head_num_decoder_layers or 6 + neck_expansion = config.neck_expansion or 1.0 + + model = RTDETR( + backbone, + HybridEncoder(backbone.out_channels, neck_hidden_dim, neck_dim_feedforward, neck_expansion), + RTDETRHead( + num_classes=config.num_classes, + hidden_dim=config.head_hidden_dim, + num_queries=config.head_num_queries, + in_channels=[neck_hidden_dim] * 3, + num_decoder_layers=head_num_decoder_layers, + ), + ) + + if config.checkpoint: + model.load_checkpoint(config.checkpoint) + return model + + @staticmethod + def from_pretrained(model_name: str) -> RTDETR: + """Load model from pretrained weights. + + Args: + model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'. + + """ + if model_name not in URLs: + raise ValueError(f"No pretrained model for '{model_name}'. Please select from {list(URLs.keys())}.") + + state_dict = torch.hub.load_state_dict_from_url( + URLs[model_name], map_location="cuda:0" if torch.cuda.is_available() else "cpu" + ) + + def map_name(old_name: str) -> str: + new_name = old_name + + # Encoder renaming + new_name = re.sub("encoder.pan_blocks", "encoder.ccfm.pan_blocks", new_name) + new_name = re.sub("encoder.downsample_convs", "encoder.ccfm.downsample_convs", new_name) + new_name = re.sub("encoder.fpn_blocks", "encoder.ccfm.fpn_blocks", new_name) + new_name = re.sub("encoder.lateral_convs", "encoder.ccfm.lateral_convs", new_name) + + # Backbone renaming + new_name = re.sub(".branch2b.", ".convs.branch2b.", new_name) + new_name = re.sub(".branch2a.", ".convs.branch2a.", new_name) + new_name = re.sub(".branch2c.", ".convs.branch2c.", new_name) + + return new_name + + def _state_dict_proc(state_dict: dict[str, Tensor]) -> dict[str, Tensor]: + state_dict = state_dict["ema"]["module"] # type:ignore + new_state_dict = {} + + # Apply the regex-based mapping function to each key + for old_name in state_dict.keys(): + new_name = map_name(old_name) + new_state_dict[new_name] = state_dict[old_name] + + return new_state_dict + + model = RTDETR.from_name(model_name, num_classes=80) + + model.load_state_dict(_state_dict_proc(state_dict)) + return model + + @staticmethod + def from_name(model_name: str, num_classes: int = 80) -> RTDETR: + """Load model without pretrained weights. + + Args: + model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'. + num_classes: number of classes to detect. + + """ + model = RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes)) + return model + + def forward(self, images: Tensor) -> tuple[Tensor, Tensor]: + """Detect objects in an image. + + Args: + images: images to be detected. Shape :math:`(N, C, H, W)`. + + Returns: + - **logits** - Tensor of shape :math:`(N, Q, K)`, where :math:`Q` is the number of queries, + :math:`K` is the number of classes. + - **boxes** - Tensor of shape :math:`(N, Q, 4)`, where :math:`Q` is the number of queries. + + """ + feats = self.backbone(images) + feats_buf = self.encoder(feats) + logits, boxes = self.decoder(feats_buf) + return logits, boxes diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/post_processor.py b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/post_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..be6532181a0b5fea6dae5693ed801c090c081fd4 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/rt_detr/post_processor.py @@ -0,0 +1,115 @@ +# 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. +# + +"""Post-processor for the RT-DETR model.""" + +from __future__ import annotations + +from typing import Optional, Union + +import torch + +from kornia.core import Module, Tensor, concatenate, tensor +from kornia.models.detection.utils import BoxFiltering + + +def mod(a: Tensor, b: int) -> Tensor: + """Compute the modulo operation for two numbers. + + This function calculates the remainder of the division of 'a' by 'b' + using the formula: a - (a // b) * b, which is equivalent to the modulo operation. + + Args: + a: The dividend. + b: The divisor. + + Returns: + The remainder of a divided by b. + + Example: + >>> mod(7, 3) + 1 + + """ + return a - (a // b) * b + + +# TODO: deprecate the confidence threshold and add the num_top_queries as a parameter and num_classes as a parameter +class DETRPostProcessor(Module): + def __init__( + self, + confidence_threshold: Optional[float] = None, + num_classes: int = 80, + num_top_queries: int = 300, + confidence_filtering: bool = True, + filter_as_zero: bool = False, + ) -> None: + super().__init__() + self.confidence_threshold = confidence_threshold + self.num_classes = num_classes + self.confidence_filtering = confidence_filtering + self.num_top_queries = num_top_queries + self.box_filtering = BoxFiltering( + tensor(confidence_threshold) if confidence_threshold is not None else None, filter_as_zero=filter_as_zero + ) + + def forward(self, logits: Tensor, boxes: Tensor, original_sizes: Tensor) -> Union[Tensor, list[Tensor]]: + """Post-process outputs from DETR. + + Args: + logits: tensor with shape :math:`(N, Q, K)`, where :math:`N` is the batch size, :math:`Q` is the number of + queries, :math:`K` is the number of classes. + boxes: tensor with shape :math:`(N, Q, 4)`, where :math:`N` is the batch size, :math:`Q` is the number of + queries. + original_sizes: tensor with shape :math:`(N, 2)`, where :math:`N` is the batch size and each element + represents the image size of (img_height, img_width). + + Returns: + Processed detections. For each image, the detections have shape (D, 6), where D is the number of detections + in that image, 6 represent (class_id, confidence_score, x, y, w, h). + + """ + # NOTE: consider using kornia BoundingBox + # NOTE: consider having a separate function to convert the detections to a list of bounding boxes + + # https://github.com/PaddlePaddle/PaddleDetection/blob/5d1f888362241790000950e2b63115dc8d1c6019/ppdet/modeling/post_process.py#L446 + # box format is cxcywh + # convert to xywh + # bboxes[..., :2] -= bboxes[..., 2:] * 0.5 # in-place operation is not torch.compile()-friendly + # TODO: replace using kornia BoundingBox + cxcy, wh = boxes[..., :2], boxes[..., 2:] + boxes_xy = concatenate([cxcy - wh * 0.5, wh], -1) + + # Get dynamic size from the input tensor itself + sizes_wh = original_sizes[0].flip(0).unsqueeze(0).unsqueeze(0).repeat(1, 1, 2) + + boxes_xy = boxes_xy * sizes_wh + scores = logits.sigmoid() # RT-DETR was trained with focal loss. thus sigmoid is used instead of softmax + + # retrieve the boxes with the highest score for each class + # https://github.com/lyuwenyu/RT-DETR/blob/b6bf0200b249a6e35b44e0308b6058f55b99696b/rtdetrv2_pytorch/src/zoo/rtdetr/rtdetr_postprocessor.py#L55-L62 + scores, index = torch.topk(scores.flatten(1), self.num_top_queries, dim=-1) + labels = mod(index, self.num_classes) + index = index // self.num_classes + boxes = boxes_xy.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes_xy.shape[-1])) + + all_boxes = concatenate([labels[..., None], scores[..., None], boxes], -1) + + if not self.confidence_filtering or self.confidence_threshold == 0: + return all_boxes + + return self.box_filtering(all_boxes, self.confidence_threshold) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..670fc65e7e75c0f8d3c3d4d4edb813cb94751f43 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/__init__.py @@ -0,0 +1,18 @@ +# 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. +# + +from kornia.contrib.models.sam.model import Sam, SamConfig, SamModelType diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/__init__.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d273d5cba09827eabbe13c7f953f35f94a5f9ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/__init__.py @@ -0,0 +1,16 @@ +# 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. +# diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/common.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/common.py new file mode 100644 index 0000000000000000000000000000000000000000..525961dbed1fe9483ba55fbbf0ec095573715a08 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/common.py @@ -0,0 +1,47 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/common.py +""" + +from __future__ import annotations + +from typing import Any + +from torch import nn + +from kornia.core import Module, Tensor + + +class MLPBlock(Module): + def __init__(self, embedding_dim: int, mlp_dim: int, act: type[Module] = nn.GELU) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: Tensor) -> Tensor: + return self.lin2(self.act(self.lin1(x))) + + +class LayerNorm(nn.LayerNorm): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.eps = 1e-6 diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/image_encoder.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..e0990ce750a7b8f751c044770499e14f506469af --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/image_encoder.py @@ -0,0 +1,351 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/image_encoder.py +""" + +from __future__ import annotations + +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.contrib.models.common import LayerNorm2d, window_partition, window_unpartition +from kornia.contrib.models.sam.architecture.common import MLPBlock +from kornia.core import Module, Tensor, zeros + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(Module): + def __init__( + self, + img_size: int = 1024, + *, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: type[Module] = nn.LayerNorm, + act_layer: type[Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: tuple[int, ...] = (), + ) -> None: + """Construct Image Encoder ViT. + + Args: + img_size: Input image size. + patch_size: Patch size. + in_chans: Number of input image channels. + embed_dim: Patch embedding dimension. + depth: Depth of ViT. + num_heads: Number of attention heads in each ViT block. + mlp_ratio: Ratio of mlp hidden dim to embedding dim. + out_chans: Number of output channels. + qkv_bias: If True, add a learnable bias to query, key, value. + norm_layer: Normalization layer. + act_layer: Activation layer. + use_abs_pos: If True, use absolute positional embeddings. + use_rel_pos: If True, add relative positional embeddings to the attention map. + rel_pos_zero_init: If True, zero initialize relative positional parameters. + window_size: Window size for window attention blocks. + global_attn_indexes: Indexes for blocks using global attention. + + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter(zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d(embed_dim, out_chans, kernel_size=1, bias=False), + LayerNorm2d(out_chans), + nn.Conv2d(out_chans, out_chans, kernel_size=3, padding=1, bias=False), + LayerNorm2d(out_chans), + ) + + def forward(self, x: Tensor) -> Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x + + +class Block(Module): + """Transformer blocks with support of window attention and residual propagation blocks.""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: type[Module] = nn.LayerNorm, + act_layer: type[Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[tuple[int, int]] = None, + ) -> None: + """Construct transformer block. + + Args: + dim: Number of input channels. + num_heads: Number of attention heads in each ViT block. + mlp_ratio: Ratio of mlp hidden dim to embedding dim. + qkv_bias: If True, add a learnable bias to query, key, value. + norm_layer: Normalization layer. + act_layer: Activation layer. + use_rel_pos: If True, add relative positional embeddings to the attention map. + rel_pos_zero_init: If True, zero initialize relative positional parameters. + window_size: Window size for window attention blocks. If it equals 0, then use global attention. + input_size: Input resolution for calculating the relative positional parameter size. + + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: Tensor) -> Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[tuple[int, int]] = None, + ) -> None: + """Construct attention block. + + Args: + dim: Number of input channels. + num_heads: Number of attention heads. + qkv_bias: If True, add a learnable bias to query, key, value. + use_rel_pos: If True, add relative positional embeddings to the attention map. + rel_pos_zero_init: If True, zero initialize relative positional parameters. + input_size: Input resolution for calculating the relative positional parameter size. + + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos and isinstance(input_size, tuple): + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: Tensor) -> Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor: + """Get relative positional embeddings according to the relative positions of query and key sizes. + + Args: + q_size: size of query q. + k_size: size of key k. + rel_pos: relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear" + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: Tensor, q: Tensor, rel_pos_h: Tensor, rel_pos_w: Tensor, q_size: tuple[int, int], k_size: tuple[int, int] +) -> Tensor: + """Calculate decomposed Relative Positional Embeddings. + + from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py + + + Args: + attn: attention map. + q: query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h: relative position embeddings (Lh, C) for height axis. + rel_pos_w: relative position embeddings (Lw, C) for width axis. + q_size: spatial sequence size of query q with (q_h, q_w). + k_size: spatial sequence size of key k with (k_h, k_w). + + Returns: + att: attention map with added relative positional embeddings. + + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view( + B, q_h * q_w, k_h * k_w + ) + + return attn + + +class PatchEmbed(Module): + """Image to Patch Embedding.""" + + def __init__( + self, + kernel_size: tuple[int, int] = (16, 16), + stride: tuple[int, int] = (16, 16), + padding: tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """Construct Patch Embedding. + + Args: + kernel_size: kernel size of the projection layer. + stride: stride of the projection layer. + padding: padding size of the projection layer. + in_chans: Number of input image channels. + embed_dim: Patch embedding dimension. + + """ + super().__init__() + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding) + + def forward(self, x: Tensor) -> Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/mask_decoder.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2120dad41730bcbc3cc0c6c258e077846ccb5e0e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/mask_decoder.py @@ -0,0 +1,158 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/mask_decoder.py +""" + +from __future__ import annotations + +import torch +from torch import nn + +from kornia.contrib.models.common import MLP, LayerNorm2d +from kornia.core import Module, Tensor, concatenate, stack + + +class MaskDecoder(Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: Module, + num_multimask_outputs: int = 3, + activation: type[Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """Predicts masks given an image and prompt embeddings, using a transformer architecture. + + Args: + transformer_dim: the channel dimension of the transformer + transformer: the transformer used to predict masks + num_multimask_outputs: the number of masks to predict when disambiguating masks + activation: the type of activation to use when upscaling masks + iou_head_depth: the depth of the MLP used to predict mask quality + iou_head_hidden_dim: the hidden dimension of the MLP used to predict mask quality + + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for i in range(self.num_mask_tokens)] + ) + + self.iou_prediction_head = MLP(transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth) + + def forward( + self, + image_embeddings: Tensor, + image_pe: Tensor, + sparse_prompt_embeddings: Tensor, + dense_prompt_embeddings: Tensor, + multimask_output: bool, + ) -> tuple[Tensor, Tensor]: + """Predict masks given image and prompt embeddings. + + Args: + image_embeddings: the embeddings from the image encoder + image_pe: positional encoding with the shape of image_embeddings + sparse_prompt_embeddings: the embeddings of the points and boxes + dense_prompt_embeddings: the embeddings of the mask inputs + multimask_output: Whether to return multiple masks or a single mask. + + Returns: + batched predicted masks + batched predictions of mask quality + + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for outptu + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: Tensor, + image_pe: Tensor, + sparse_prompt_embeddings: Tensor, + dense_prompt_embeddings: Tensor, + ) -> tuple[Tensor, Tensor]: + """Predicts masks. + + See 'forward' for more details. + """ + # Concatenate output tokens + output_tokens = concatenate([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens[None, ...].expand(sparse_prompt_embeddings.size(0), -1, -1) + tokens = concatenate((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: list[Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])) + hyper_in = stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/prompt_encoder.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3d743d526c55cfe683f30df3190074cdb926ff --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/prompt_encoder.py @@ -0,0 +1,206 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/prompt_encoder.py +""" + +from __future__ import annotations + +from math import pi +from typing import Optional + +import torch +from torch import nn + +from kornia.contrib.models.common import LayerNorm2d +from kornia.core import Device, Module, Tensor, concatenate, cos, sin, stack, zeros + + +class PromptEncoder(Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: tuple[int, int], + input_image_size: tuple[int, int], + mask_in_chans: int, + activation: type[Module] = nn.GELU, + ) -> None: + """Encode prompts for input to SAM's mask decoder. + + Args: + embed_dim: The prompts' embedding dimension + image_embedding_size: The spatial size of the image embedding, as (H, W). + input_image_size: The padded size of the image as input to the image encoder, as (H, W). + mask_in_chans: The number of hidden channels used for encoding input masks. + activation: The activation to use when encoding input masks. + + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> Tensor: + """Return the positional encoding used to encode point prompts, applied to a dense set of points the shape + of the image encoding. + + Returns: + Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w) + + """ # noqa: D205 + return self.pe_layer(self.image_embedding_size)[None, ...] + + def _embed_points(self, points: Tensor, labels: Tensor, pad: bool) -> Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = concatenate([points, padding_point], dim=1) + labels = concatenate([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: Tensor) -> Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: Tensor) -> Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor] + ) -> int: + """Get the batch size of the output given the batch size of the input prompts.""" + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> Device: + return self.point_embeddings[0].weight.device + + def forward( + self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor] + ) -> tuple[Tensor, Tensor]: + """Embeds different types of prompts, returning both sparse and dense embeddings. + + Args: + points: point coordinates and labels to embed. + boxes: boxes to embed + masks: masks to embed + + Returns: + - sparse embeddings for the points and boxes, with shape BxNx(embed_dim), where N is determined by the + number of input points and boxes. + - dense embeddings for the masks, in the shape Bx(embed_dim)x(embed_H)x(embed_W) + + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = concatenate([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = concatenate([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(Module): + """Positional encoding using random spatial frequencies.""" + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer("positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats))) + + def _pe_encoding(self, coords: Tensor) -> Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * pi * coords + # outputs d_1 x ... x d_n x C shape + return concatenate([sin(coords), cos(coords)], dim=-1) + + def forward(self, size: tuple[int, int]) -> Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + _dev = self.positional_encoding_gaussian_matrix.device + device = _dev if isinstance(_dev, torch.device) else None + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords(self, coords_input: Tensor, image_size: tuple[int, int]) -> Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float32)) # B x N x C diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/transformer.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..576a79b88fb87bfc6cce2a64f9429e2a0f28e196 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/architecture/transformer.py @@ -0,0 +1,235 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/transformer.py +""" + +from __future__ import annotations + +import math + +from torch import nn + +from kornia.contrib.models.sam.architecture.common import MLPBlock +from kornia.core import Module, Tensor +from kornia.core.check import KORNIA_CHECK + + +class TwoWayTransformer(Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: type[Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """Construct a transformer decoder that attends to an input image using queries whose positional embedding is + supplied. + + Args: + depth: number of layers in the transformer + embedding_dim: the channel dimension for the input embeddings + num_heads: the number of heads for multihead attention. Must divide embedding_dim + mlp_dim: the channel dimension internal to the MLP block + activation: the activation to use in the MLP block + attention_downsample_rate: downsampling rate from embedding dimension + + """ # noqa: D205 + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward(self, image_embedding: Tensor, image_pe: Tensor, point_embedding: Tensor) -> tuple[Tensor, Tensor]: + """Run forward. + + Args: + image_embedding: image to attend to. Should be shape B x embedding_dim x h x w for any h and w. + image_pe: the positional encoding to add to the image. Must have the same shape as image_embedding. + point_embedding: the embedding to add to the query points. Must have shape B x N_points x embedding_dim + for any N_points. + + Returns: + - the processed point_embedding + - the processed image_embedding + + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer(queries=queries, keys=keys, query_pe=point_embedding, key_pe=image_pe) + + # Apply the final attenion layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: type[Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """Construct a transformer block with four layers. + + (1) self-attention of sparse inputs, (2) cross attention of + sparse inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Args: + embedding_dim: the channel dimension of the embeddings + num_heads: the number of heads in the attention layers + mlp_dim: the hidden dimension of the mlp block + activation: the activation of the mlp block + skip_first_layer_pe: skip the PE on the first layer + attention_downsample_rate: downsampling rate from embedding dimension + + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(Module): + """Attention layer that allows for downscaling the embedding after projection to queries, keys, and values.""" + + def __init__(self, embedding_dim: int, num_heads: int, downsample_rate: int = 1) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + KORNIA_CHECK(self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim.") + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = attn.softmax(dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/sam/model.py b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8da174e265c414b642e254c4da7128e56571452c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/sam/model.py @@ -0,0 +1,350 @@ +# 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. +# + +"""Based from the original code from Meta Platforms, Inc. and affiliates. + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/build_sam.py + +https://github.com/facebookresearch/segment- +anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/sam.py +""" + +from __future__ import annotations + +import warnings +from dataclasses import dataclass +from enum import Enum +from typing import Any, Optional + +import torch + +from kornia.contrib.models import SegmentationResults +from kornia.contrib.models.base import ModelBase +from kornia.contrib.models.sam.architecture.common import LayerNorm +from kornia.contrib.models.sam.architecture.image_encoder import ImageEncoderViT +from kornia.contrib.models.sam.architecture.mask_decoder import MaskDecoder +from kornia.contrib.models.sam.architecture.prompt_encoder import PromptEncoder +from kornia.contrib.models.sam.architecture.transformer import TwoWayTransformer +from kornia.contrib.models.tiny_vit import TinyViT +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE + + +class SamModelType(Enum): + """Map the SAM model types.""" + + vit_h = 0 + vit_l = 1 + vit_b = 2 + mobile_sam = 3 + + +@dataclass +class SamConfig: + """Encapsulate the Config to build a SAM model. + + Args: + model_type: the available models are: + + - 0, 'vit_h' or :func:`kornia.contrib.sam.SamModelType.vit_h` + - 1, 'vit_l' or :func:`kornia.contrib.sam.SamModelType.vit_l` + - 2, 'vit_b' or :func:`kornia.contrib.sam.SamModelType.vit_b` + - 3, 'mobile_sam', or :func:`kornia.contrib.sam.SamModelType.mobile_sam` + + checkpoint: URL or a path for a file with the weights of the model + encoder_embed_dim: Patch embedding dimension. + encoder_depth: Depth of ViT. + encoder_num_heads: Number of attention heads in each ViT block. + encoder_global_attn_indexes: Encoder indexes for blocks using global attention. + + """ + + model_type: Optional[str | int | SamModelType] = None + checkpoint: Optional[str] = None + pretrained: bool = False + + encoder_embed_dim: Optional[int] = None + encoder_depth: Optional[int] = None + encoder_num_heads: Optional[int] = None + encoder_global_attn_indexes: Optional[tuple[int, ...]] = None + + +class Sam(ModelBase[SamConfig]): + mask_threshold: float = 0.0 + + def __init__( + self, image_encoder: ImageEncoderViT | TinyViT, prompt_encoder: PromptEncoder, mask_decoder: MaskDecoder + ) -> None: + """SAM predicts object masks from an image and input prompts. + + Args: + image_encoder: The backbone used to encode the image into image embeddings that allow for efficient mask + prediction. + prompt_encoder: Encodes various types of input prompts. + mask_decoder: Predicts masks from the image embeddings and encoded prompts. + + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + + @staticmethod + def from_name(name: str) -> Sam: + """Build/load the SAM model based on it's name. + + Args: + name: The name of the SAM model. Valid names are: + - 'vit_b' + - 'vit_l' + - 'vit_h' + - 'mobile_sam' + + Returns: + The respective SAM model + + """ + if name in ["vit_b", "vit_l", "vit_h", "mobile_sam"]: + return Sam.from_config(SamConfig(name)) + else: + raise ValueError(f"Invalid SAM model name: {name}") + + @staticmethod + def from_config(config: SamConfig) -> Sam: + """Build/load the SAM model based on it's config. + + Args: + config: The SamConfig data structure. If the model_type is available, build from it, otherwise will use + the parameters set. + + Returns: + The respective SAM model + + Example: + >>> from kornia.contrib.models.sam import SamConfig + >>> sam_model = Sam.from_config(SamConfig('vit_b')) + + """ + model_type = config.model_type + + if isinstance(model_type, int): + model_type = SamModelType(model_type) + elif isinstance(model_type, str): + _map_sam_type = { + "vit_h": SamModelType.vit_h, + "vit_l": SamModelType.vit_l, + "vit_b": SamModelType.vit_b, + "mobile_sam": SamModelType.mobile_sam, + } + model_type = _map_sam_type[model_type] + + if model_type == SamModelType.vit_b: + model = _build_sam( + encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=(2, 5, 8, 11) + ) + + elif model_type == SamModelType.vit_l: + model = _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=(5, 11, 17, 23), + ) + + elif model_type == SamModelType.vit_h: + model = _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=(7, 15, 23, 31), + ) + + elif model_type == SamModelType.mobile_sam: + # TODO: merge this with _build_sam() + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + + model = Sam( + image_encoder=TinyViT.from_config("5m", img_size=image_size, mobile_sam=True), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer(depth=2, embedding_dim=prompt_embed_dim, mlp_dim=2048, num_heads=8), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + # pixel_mean=[123.675, 116.28, 103.53], + # pixel_std=[58.395, 57.12, 57.375], + ) + + elif ( + isinstance(config.encoder_embed_dim, int) + and isinstance(config.encoder_depth, int) + and isinstance(config.encoder_num_heads, int) + and isinstance(config.encoder_global_attn_indexes, int) + ): + model = _build_sam( + encoder_embed_dim=config.encoder_embed_dim, + encoder_depth=config.encoder_depth, + encoder_num_heads=config.num_heads, + encoder_global_attn_indexes=config.encoder_global_attn_indexes, + ) + + else: + raise NotImplementedError("Unexpected config. The model_type should be provide or the encoder configs.") + + checkpoint = config.checkpoint + if config.pretrained: + if checkpoint is None: + checkpoint = { + SamModelType.vit_b: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", + SamModelType.vit_l: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth", + SamModelType.vit_h: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", + SamModelType.mobile_sam: "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt", + }[model_type] + else: + warnings.warn("checkpoint is not None. pretrained=True is ignored", stacklevel=1) + + if checkpoint: + model.load_checkpoint(checkpoint) + + return model + + @torch.no_grad() + def forward( + self, images: Tensor, batched_prompts: list[dict[str, Any]], multimask_output: bool + ) -> list[SegmentationResults]: + """Predicts masks end-to-end from provided images and prompts. + + This method expects that the images have already been pre-processed, at least been normalized, resized and + padded to be compatible with the `self.image_encoder`. + + .. note:: For each image :math:`(3, H, W)`, it is possible to input a batch (:math:`K`) of :math:`N` prompts, + the results are batched by the number of prompts batch. So given a prompt with :math:`K=5`, and + :math:`N=10`, the results will look like :math:`5xCxHxW` where :math:`C` is determined by + multimask_output. And within each of these masks :math:`(5xC)`, it should be possible to find + :math:`N` instances if the model succeed. + + Args: + images: The image as a torch tensor in :math:`(B, 3, H, W)` format, already transformed for input to the + model. + batched_prompts: A list over the batch of images (list length should be :math:`B`), each a dictionary with + the following keys. If it does not have the respective prompt, it should not be included + in this dictionary. The options are: + + - "points": tuple of (Tensor, Tensor) within the coordinate keypoints and their respective labels. + the tuple should look like (keypoints, labels), where: + + - The keypoints (a tensor) are a batched point prompts for this image, with shape + :math:`(K, N, 2)`. Already transformed to the input frame of the model. + - The labels (a tensor) are a batched labels for point prompts, with shape :math:`(K, N)`. + Where 1 indicates a foreground point and 0 indicates a background point. + + - "boxes": (Tensor) Batched box inputs, with shape :math:`(K, 4)`. Already transformed to the input + frame of the model. + - "mask_inputs": (Tensor) Batched mask inputs to the model, in the form :math:`(K, 1, H, W)`. + + multimask_output: Whether the model should predict multiple disambiguating masks, or return a single mask. + + Returns: + A list over input images, where each element is as SegmentationResults the following. + - logits: Low resolution logits with shape :math:`(K, C, H, W)`. Can be passed as mask input to + subsequent iterations of prediction. Where :math:`K` is the number of input prompts, + :math:`C` is determined by multimask_output, and :math:`H=W=256` are the model output size. + - scores: The model's predictions of mask quality (iou prediction), in shape BxC. + + """ + KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"]) + KORNIA_CHECK( + images.shape[0] == len(batched_prompts), + "The number of images (`B`) should match with the length of prompts!", + ) + + image_embeddings = self.image_encoder(images) + + outputs = [] + for prompt_record, curr_embedding in zip(batched_prompts, image_embeddings): + # Embed prompts + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=prompt_record.get("points", None), + boxes=prompt_record.get("boxes", None), + masks=prompt_record.get("mask_inputs", None), + ) + + # Predict masks + low_res_logits, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding[None, ...], + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Save results + outputs.append(SegmentationResults(low_res_logits, iou_predictions, self.mask_threshold)) + + return outputs + + +def _build_sam( + encoder_embed_dim: int, encoder_depth: int, encoder_num_heads: int, encoder_global_attn_indexes: tuple[int, ...] +) -> Sam: + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + + return Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=LayerNorm, + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer(depth=2, embedding_dim=prompt_embed_dim, mlp_dim=2048, num_heads=8), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + # pixel_mean=[123.675, 116.28, 103.53], + # pixel_std=[58.395, 57.12, 57.375], + ) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/structures.py b/python_embeded/Lib/site-packages/kornia/contrib/models/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb2fce66ec8f6a8257f4c1ae84ed35c0ee14af5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/structures.py @@ -0,0 +1,128 @@ +# 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. +# + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK +from kornia.geometry.transform import resize + + +@dataclass +class SegmentationResults: + """Encapsulate the results obtained by a Segmentation model. + + Args: + logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks + scores: The scores from the logits. Shape :math:`(B, C)` + mask_threshold: The threshold value to generate the `binary_masks` from the `logits` + + """ + + logits: Tensor + scores: Tensor + mask_threshold: float = 0.0 + + @property + def binary_masks(self) -> Tensor: + """Binary mask generated from logits considering the mask_threshold. + + Shape will be the same of logits :math:`(B, C, H, W)` where :math:`C` is the number masks predicted. + + .. note:: If you run `original_res_logits`, this will generate the masks + based on the original resolution logits. + Otherwise, this will use the low resolution logits (self.logits). + """ + if self._original_res_logits is not None: + x = self._original_res_logits + else: + x = self.logits + + return x > self.mask_threshold + + def original_res_logits( + self, input_size: tuple[int, int], original_size: tuple[int, int], image_size_encoder: Optional[tuple[int, int]] + ) -> Tensor: + """Remove padding and upscale the logits to the original image size. + + Resize to image encoder input -> remove padding (bottom and right) -> Resize to original size + + .. note:: This method set a internal `original_res_logits` which will be used if available for the binary masks. + + Args: + input_size: The size of the image input to the model, in (H, W) format. Used to remove padding. + original_size: The original size of the image before resizing for input to the model, in (H, W) format. + image_size_encoder: The size of the input image for image encoder, in (H, W) format. Used to resize the + logits back to encoder resolution before remove the padding. + + Returns: + Batched logits in :math:`(K, C, H, W)` format, where (H, W) is given by original_size. + + """ + x = self.logits + + if isinstance(image_size_encoder, tuple): + x = resize(x, size=image_size_encoder, interpolation="bilinear", align_corners=False, antialias=False) + x = x[..., : input_size[0], : input_size[1]] + + x = resize(x, size=original_size, interpolation="bilinear", align_corners=False, antialias=False) + + self._original_res_logits = x + return self._original_res_logits + + def squeeze(self, dim: int = 0) -> SegmentationResults: + """Realize a squeeze for the dim given for all properties.""" + self.logits = self.logits.squeeze(dim) + self.scores = self.scores.squeeze(dim) + if isinstance(self._original_res_logits, Tensor): + self._original_res_logits = self._original_res_logits.squeeze(dim) + + return self + + +@dataclass +class Prompts: + """Encapsulate the prompts inputs for a Model. + + Args: + points: A tuple with the keypoints (coordinates x, y) and their respective labels. Shape :math:`(K, N, 2)` for + the keypoints, and :math:`(K, N)` + boxes: Batched box inputs, with shape :math:`(K, 4)`. Expected to be into xyxy format. + masks: Batched mask prompts to the model with shape :math:`(K, 1, H, W)` + + """ + + points: Optional[tuple[Tensor, Tensor]] = None + boxes: Optional[Tensor] = None + masks: Optional[Tensor] = None + + def __post_init__(self) -> None: + if isinstance(self.keypoints, Tensor) and isinstance(self.boxes, Tensor): + KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], "The prompts should have the same batch size!") + + @property + def keypoints(self) -> Optional[Tensor]: + """The keypoints from the `points`.""" + return self.points[0] if isinstance(self.points, tuple) else None + + @property + def keypoints_labels(self) -> Optional[Tensor]: + """The keypoints labels from the `points`.""" + return self.points[1] if isinstance(self.points, tuple) else None diff --git a/python_embeded/Lib/site-packages/kornia/contrib/models/tiny_vit.py b/python_embeded/Lib/site-packages/kornia/contrib/models/tiny_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..ca01d7ad88660914cac28bbbf0312199c2497df2 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/models/tiny_vit.py @@ -0,0 +1,584 @@ +# 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. +# + +# https://github.com/microsoft/Cream/blob/8dc38822b99fff8c262c585a32a4f09ac504d693/TinyViT/models/tiny_vit.py +# https://github.com/ChaoningZhang/MobileSAM/blob/01ea8d0f5590082f0c1ceb0a3e2272593f20154b/mobile_sam/modeling/tiny_vit_sam.py + +from __future__ import annotations + +import itertools +import warnings +from typing import Any, Optional, Sequence + +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils import checkpoint + +from kornia.contrib.models.common import DropPath, LayerNorm2d, window_partition, window_unpartition +from kornia.core import Module, Tensor +from kornia.core.check import KORNIA_CHECK + + +def _make_pair(x: int | tuple[int, int]) -> tuple[int, int]: + return (x, x) if isinstance(x, int) else x + + +class ConvBN(nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int = 1, + padding: int = 0, + groups: int = 1, + activation: type[Module] = nn.Identity, + ) -> None: + super().__init__() + self.c = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, groups=groups, bias=False) + self.bn = nn.BatchNorm2d(out_channels) + self.act = activation() + + +class PatchEmbed(nn.Sequential): + def __init__(self, in_channels: int, embed_dim: int, activation: type[Module] = nn.GELU) -> None: + super().__init__() + self.seq = nn.Sequential( + ConvBN(in_channels, embed_dim // 2, 3, 2, 1), activation(), ConvBN(embed_dim // 2, embed_dim, 3, 2, 1) + ) + + +class MBConv(Module): + def __init__( + self, + in_channels: int, + out_channels: int, + expansion_ratio: float, + activation: type[Module] = nn.GELU, + drop_path: float = 0.0, + ) -> None: + super().__init__() + hidden_channels = int(in_channels * expansion_ratio) + self.conv1 = ConvBN(in_channels, hidden_channels, 1, activation=activation) # point-wise + self.conv2 = ConvBN(hidden_channels, hidden_channels, 3, 1, 1, hidden_channels, activation) # depth-wise + self.conv3 = ConvBN(hidden_channels, out_channels, 1) + self.drop_path = DropPath(drop_path) + self.act = activation() + + def forward(self, x: Tensor) -> Tensor: + return self.act(x + self.drop_path(self.conv3(self.conv2(self.conv1(x))))) + + +class PatchMerging(Module): + def __init__( + self, + input_resolution: int | tuple[int, int], + dim: int, + out_dim: int, + stride: int, + activation: type[Module] = nn.GELU, + ) -> None: + KORNIA_CHECK(stride in (1, 2), "stride must be either 1 or 2") + super().__init__() + self.input_resolution = _make_pair(input_resolution) + self.conv1 = ConvBN(dim, out_dim, 1, activation=activation) + self.conv2 = ConvBN(out_dim, out_dim, 3, stride, 1, groups=out_dim, activation=activation) + self.conv3 = ConvBN(out_dim, out_dim, 1) + + def forward(self, x: Tensor) -> Tensor: + if x.ndim == 3: + x = x.transpose(1, 2).unflatten(2, self.input_resolution) # (B, H * W, C) -> (B, C, H, W) + x = self.conv3(self.conv2(self.conv1(x))) + x = x.flatten(2).transpose(1, 2) # (B, C, H, W) -> (B, H * W, C) + return x + + +class ConvLayer(Module): + def __init__( + self, + dim: int, + depth: int, + activation: type[Module] = nn.GELU, + drop_path: float | list[float] = 0.0, + downsample: Optional[Module] = None, + use_checkpoint: bool = False, + conv_expand_ratio: float = 4.0, + ) -> None: + super().__init__() + self.use_checkpoint = use_checkpoint + + # build blocks + if not isinstance(drop_path, list): + drop_path = [drop_path] * depth + self.blocks = nn.ModuleList( + [MBConv(dim, dim, conv_expand_ratio, activation, drop_path[i]) for i in range(depth)] + ) + + # patch merging layer + self.downsample = downsample + + def forward(self, x: Tensor) -> Tensor: + for blk in self.blocks: + x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + +class MLP(nn.Sequential): + def __init__( + self, + in_features: int, + hidden_features: int, + out_features: int, + activation: type[Module] = nn.GELU, + drop: float = 0.0, + ) -> None: + super().__init__() + self.norm = nn.LayerNorm(in_features) + self.fc1 = nn.Linear(in_features, hidden_features) + self.act1 = activation() + self.drop1 = nn.Dropout(drop) + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop2 = nn.Dropout(drop) + + +# NOTE: differences from image_encoder.Attention: +# - different relative position encoding mechanism (separable/decomposed vs joint) +# - this impl supports attn_ratio (increase output size for value), though it is not used +class Attention(Module): + def __init__( + self, + dim: int, + key_dim: int, + num_heads: int = 8, + attn_ratio: float = 4.0, + resolution: tuple[int, int] = (14, 14), + ) -> None: + super().__init__() + self.num_heads = num_heads + self.scale = key_dim**-0.5 + self.key_dim = key_dim + self.nh_kd = key_dim * num_heads + self.d = int(attn_ratio * key_dim) + self.dh = int(attn_ratio * key_dim) * num_heads + self.attn_ratio = attn_ratio + h = self.dh + self.nh_kd * 2 + + self.norm = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, h) + self.proj = nn.Linear(self.dh, dim) + + indices, attn_offset_size = self.build_attention_bias(resolution) + self.attention_biases = nn.Parameter(torch.zeros(num_heads, attn_offset_size)) + self.register_buffer("attention_bias_idxs", indices, persistent=False) + self.attention_bias_idxs: Tensor + self.ab: Optional[Tensor] = None + + @staticmethod + def build_attention_bias(resolution: tuple[int, int]) -> tuple[Tensor, int]: + points = list(itertools.product(range(resolution[0]), range(resolution[1]))) + attention_offsets: dict[tuple[int, int], int] = {} + idxs: list[int] = [] + for p1 in points: + for p2 in points: + offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) + if offset not in attention_offsets: + attention_offsets[offset] = len(attention_offsets) + idxs.append(attention_offsets[offset]) + + N = len(points) + indices = torch.LongTensor(idxs).view(N, N) + attn_offset_size = len(attention_offsets) + return indices, attn_offset_size + + # is this really necessary? + @torch.no_grad() + def train(self, mode: bool = True) -> Attention: + super().train(mode) + self.ab = None if (mode and self.ab is not None) else self.attention_biases[:, self.attention_bias_idxs] + return self + + def forward(self, x: Tensor) -> Tensor: + B, N, _ = x.shape + x = self.norm(x) + qkv = self.qkv(x) + qkv = qkv.view(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + q, k, v = qkv.split([self.key_dim, self.key_dim, self.d], dim=3) + + bias = self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab + attn = (q @ k.transpose(-2, -1)) * self.scale + bias + + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh) + x = self.proj(x) + return x + + +class TinyViTBlock(Module): + def __init__( + self, + dim: int, + input_resolution: int | tuple[int, int], + num_heads: int, + window_size: int = 7, + mlp_ratio: float = 4.0, + drop: float = 0.0, + drop_path: float = 0.0, + local_conv_size: int = 3, + activation: type[Module] = nn.GELU, + ) -> None: + KORNIA_CHECK(dim % num_heads == 0, "dim must be divislbe by num_heads") + super().__init__() + self.input_resolution = _make_pair(input_resolution) + self.window_size = window_size + head_dim = dim // num_heads + + self.attn = Attention(dim, head_dim, num_heads, 1.0, (window_size, window_size)) + self.drop_path1 = DropPath(drop_path) + self.local_conv = ConvBN(dim, dim, local_conv_size, 1, local_conv_size // 2, dim) + self.mlp = MLP(dim, int(dim * mlp_ratio), dim, activation, drop) + self.drop_path2 = DropPath(drop_path) + + def forward(self, x: Tensor) -> Tensor: + H, W = self.input_resolution + B, L, C = x.shape + res_x = x + + x = x.view(B, H, W, C) + x, pad_hw = window_partition(x, self.window_size) # (B * num_windows, window_size, window_size, C) + x = self.attn(x.flatten(1, 2)) + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + x = x.view(B, L, C) + + x = res_x + self.drop_path1(x) + + x = x.transpose(1, 2).reshape(B, C, H, W) + x = self.local_conv(x) + x = x.view(B, C, L).transpose(1, 2) + + x = x + self.drop_path2(self.mlp(x)) + return x + + +class BasicLayer(Module): + def __init__( + self, + dim: int, + input_resolution: int | tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + mlp_ratio: float = 4.0, + drop: float = 0.0, + drop_path: float | list[float] = 0.0, + downsample: Optional[Module] = None, + use_checkpoint: bool = False, + local_conv_size: int = 3, + activation: type[Module] = nn.GELU, + ) -> None: + super().__init__() + self.use_checkpoint = use_checkpoint + + self.blocks = nn.ModuleList( + [ + TinyViTBlock( + dim, + input_resolution, + num_heads, + window_size, + mlp_ratio, + drop, + drop_path[i] if isinstance(drop_path, list) else drop_path, + local_conv_size, + activation, + ) + for i in range(depth) + ] + ) + + # patch merging layer + self.downsample = downsample + + def forward(self, x: Tensor) -> Tensor: + for blk in self.blocks: + x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + +class TinyViT(Module): + """TinyViT model, as described in https://arxiv.org/abs/2207.10666. + + Args: + img_size: Size of input image. + in_chans: Number of input image's channels. + num_classes: Number of output classes. + embed_dims: List of embedding dimensions. + depths: List of block count for each downsampling stage + num_heads: List of attention heads used in self-attention for each downsampling stage. + window_sizes: List of self-attention's window size for each downsampling stage. + mlp_ratio: Ratio of MLP dimension to embedding dimension in self-attention. + drop_rate: Dropout rate. + drop_path_rate: Stochastic depth rate. + use_checkpoint: Whether to use activation checkpointing to trade compute for memory. + mbconv_expand_ratio: Expansion ratio used in MBConv block. + local_conv_size: Kernel size of convolution used in TinyViTBlock + activation: activation function. + mobile_same: Whether to use modifications for MobileSAM. + + """ + + def __init__( + self, + img_size: int = 224, + in_chans: int = 3, + num_classes: int = 1000, + embed_dims: Sequence[int] = (96, 192, 384, 768), + depths: Sequence[int] = (2, 2, 6, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + window_sizes: Sequence[int] = (7, 7, 14, 7), + mlp_ratio: float = 4.0, + drop_rate: float = 0.0, + drop_path_rate: float = 0.0, + use_checkpoint: bool = False, + mbconv_expand_ratio: float = 4.0, + local_conv_size: int = 3, + # layer_lr_decay: float = 1.0, + activation: type[Module] = nn.GELU, + mobile_sam: bool = False, + ) -> None: + super().__init__() + self.img_size = img_size + self.mobile_sam = mobile_sam + self.neck: Optional[Module] + if mobile_sam: + # MobileSAM adjusts the stride to match the total stride of other ViT backbones + # used in the original SAM (stride 16) + strides = [2, 2, 1, 1] + self.neck = nn.Sequential( + nn.Conv2d(embed_dims[-1], 256, 1, bias=False), + LayerNorm2d(256), + nn.Conv2d(256, 256, 3, 1, 1, bias=False), + LayerNorm2d(256), + ) + else: + strides = [2, 2, 2, 1] + self.neck = None + + self.patch_embed = PatchEmbed(in_chans, embed_dims[0], activation) + input_resolution = img_size // 4 + + # NOTE: if we don't support training, this might be unimportant + # stochastic depth decay rule + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + + # build layers + n_layers = len(depths) + layers = [] + for i_layer, (embed_dim, depth, num_heads_i, window_size, stride) in enumerate( + zip(embed_dims, depths, num_heads, window_sizes, strides) + ): + out_dim = embed_dims[min(i_layer + 1, len(embed_dims) - 1)] + downsample = ( + PatchMerging(input_resolution, embed_dim, out_dim, stride, activation) + if (i_layer < n_layers - 1) + else None + ) + kwargs: dict[str, Any] = { + "dim": embed_dim, + "depth": depth, + "drop_path": dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + "downsample": downsample, + "use_checkpoint": use_checkpoint, + "activation": activation, + } + layer: ConvLayer | BasicLayer + if i_layer == 0: + layer = ConvLayer(conv_expand_ratio=mbconv_expand_ratio, **kwargs) + else: + layer = BasicLayer( + input_resolution=input_resolution, + num_heads=num_heads_i, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop=drop_rate, + local_conv_size=local_conv_size, + **kwargs, + ) + layers.append(layer) + input_resolution //= stride + self.layers = nn.Sequential(*layers) + self.feat_size = input_resolution # final feature map size + + # Classifier head + # NOTE: this is redundant for MobileSAM, but we still need it + # to load pre-trained weights with strict=True + # TODO: enable strict=False, or host our own weights + self.norm_head = nn.LayerNorm(embed_dims[-1]) + self.head = nn.Linear(embed_dims[-1], num_classes) + + def forward(self, x: Tensor) -> Tensor: + """Classify images if ``mobile_sam=False``, produce feature maps if ``mobile_sam=True``.""" + x = self.patch_embed(x) + x = self.layers(x) + + if self.mobile_sam: + # MobileSAM + x = x.unflatten(1, (self.feat_size, self.feat_size)).permute(0, 3, 1, 2) + x = self.neck(x) # type: ignore + else: + # classification + x = x.mean(1) + x = self.head(self.norm_head(x)) + return x + + @staticmethod + def from_config(variant: str, pretrained: bool | str = False, **kwargs: Any) -> TinyViT: + """Create a TinyViT model from pre-defined variants. + + Args: + variant: TinyViT variant. Possible values: ``'5m'``, ``'11m'``, ``'21m'``. + pretrained: whether to use pre-trained weights. Possible values: ``False``, ``True``, ``'in22k'``, + ``'in1k'``. For TinyViT-21M (``variant='21m'``), ``'in1k_384'``, ``'in1k_512'`` are also available. + **kwargs: other keyword arguments that will be passed to :class:`TinyViT`. + + .. note:: + When ``img_size`` is different from the pre-trained size, bicubic interpolation will be performed on + attention biases. When using ``pretrained=True``, ImageNet-1k checkpoint (``'in1k'``) is used. + For feature extraction or fine-tuning, ImageNet-22k checkpoint (``'in22k'``) is preferred. + + """ + KORNIA_CHECK(variant in ("5m", "11m", "21m"), "Only variant 5m, 11m, and 21m are supported") + return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs) + + +def _load_pretrained(model: TinyViT, url: str) -> TinyViT: + model_state_dict = model.state_dict() + state_dict = torch.hub.load_state_dict_from_url(url) + + # official checkpoint has "model" key + if "model" in state_dict: + state_dict = state_dict["model"] + + # https://github.com/microsoft/Cream/blob/8dc38822b99fff8c262c585a32a4f09ac504d693/TinyViT/utils.py#L163 + # bicubic interpolate attention biases + ab_keys = [k for k in state_dict.keys() if "attention_biases" in k] + for k in ab_keys: + n_heads1, L1 = state_dict[k].shape + n_heads2, L2 = model_state_dict[k].shape + KORNIA_CHECK(n_heads1 == n_heads2, f"Fail to load {k}. Pre-trained checkpoint should have num_heads={n_heads1}") + + if L1 != L2: + S1 = int(L1**0.5) + S2 = int(L2**0.5) + attention_biases = state_dict[k].view(1, n_heads1, S1, S1) + attention_biases = F.interpolate(attention_biases, size=(S2, S2), mode="bicubic") + state_dict[k] = attention_biases.view(n_heads2, L2) + + if state_dict["head.weight"].shape[0] != model.head.out_features: + msg = "Number of classes does not match pre-trained checkpoint's. Resetting classification head to zeros" + warnings.warn(msg, stacklevel=1) + state_dict["head.weight"] = torch.zeros_like(model.head.weight) + state_dict["head.bias"] = torch.zeros_like(model.head.bias) + + model.load_state_dict(state_dict) + return model + + +def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT: + model = TinyViT( + embed_dims=[64, 128, 160, 320], + depths=[2, 2, 6, 2], + num_heads=[2, 4, 5, 10], + window_sizes=[7, 7, 14, 7], + drop_path_rate=0.0, + **kwargs, + ) + + if pretrained: + if pretrained is True: + pretrained = "in1k" + + url = { + "in22k": ( + "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth" + ), + "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth", + }[pretrained] + model = _load_pretrained(model, url) + + return model + + +def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT: + model = TinyViT( + embed_dims=[64, 128, 256, 448], + depths=[2, 2, 6, 2], + num_heads=[2, 4, 8, 14], + window_sizes=[7, 7, 14, 7], + drop_path_rate=0.1, + **kwargs, + ) + + if pretrained: + if pretrained is True: + pretrained = "in1k" + + url = { + "in22k": ( + "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth" + ), + "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth", + }[pretrained] + model = _load_pretrained(model, url) + + return model + + +def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT: + model = TinyViT( + embed_dims=[96, 192, 384, 576], + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 18], + window_sizes=[7, 7, 14, 7], + drop_path_rate=0.2, + **kwargs, + ) + + if pretrained: + if pretrained is True: + pretrained = "in1k" + img_size = kwargs.get("img_size", 224) + if img_size >= 384: + pretrained = "in1k_384" + if img_size >= 512: + pretrained = "in1k_512" + + url = { + "in22k": ( + "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth" + ), + "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth", + "in1k_384": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth", + "in1k_512": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth", + }[pretrained] + model = _load_pretrained(model, url) + + return model diff --git a/python_embeded/Lib/site-packages/kornia/contrib/object_detection.py b/python_embeded/Lib/site-packages/kornia/contrib/object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..ff99a8c4c6640ac8f489636ba93d4c08cd20815c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/object_detection.py @@ -0,0 +1,101 @@ +# 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. +# + +from __future__ import annotations + +import warnings +from typing import Any + +from kornia.models.detection.base import ( + BoundingBox as BoundingBoxBase, +) +from kornia.models.detection.base import ( + BoundingBoxDataFormat, +) +from kornia.models.detection.base import ( + ObjectDetector as ObjectDetectorBase, +) +from kornia.models.detection.base import ( + ObjectDetectorResult as ObjectDetectorResultBase, +) +from kornia.models.detection.base import ( + results_from_detections as results_from_detections_base, +) +from kornia.models.utils import ResizePreProcessor as ResizePreProcessorBase + +__all__ = [ + "BoundingBox", + "BoundingBoxDataFormat", + "ObjectDetector", + "ObjectDetectorResult", + "ResizePreProcessor", + "results_from_detections", +] + + +class BoundingBox(BoundingBoxBase): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + warnings.warn( + "BoundingBox is deprecated and will be removed in v0.8.0. Use kornia.models.detection.BoundingBox instead.", + DeprecationWarning, + stacklevel=1, + ) + + +def results_from_detections(*args: Any, **kwargs: Any) -> list[ObjectDetectorResultBase]: + """Return detector results.""" + warnings.warn( + "results_from_detections is deprecated and will be removed in v0.8.0. " + "Use kornia.models.detection.results_from_detections instead.", + DeprecationWarning, + stacklevel=1, + ) + return results_from_detections_base(*args, **kwargs) + + +class ResizePreProcessor(ResizePreProcessorBase): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + warnings.warn( + "ResizePreProcessor is deprecated and will be removed in v0.8.0. " + "Use kornia.models.utils.ResizePreProcessor instead.", + DeprecationWarning, + stacklevel=1, + ) + + +class ObjectDetector(ObjectDetectorBase): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + warnings.warn( + "ObjectDetector is deprecated and will be removed in v0.8.0. " + "Use kornia.models.detection.ObjectDetector instead.", + DeprecationWarning, + stacklevel=1, + ) + + +class ObjectDetectorResult(ObjectDetectorResultBase): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + warnings.warn( + "ObjectDetectorResult is deprecated and will be removed in v0.8.0. " + "Use kornia.models.detection.ObjectDetectorResult instead.", + DeprecationWarning, + stacklevel=1, + ) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/visual_prompter.py b/python_embeded/Lib/site-packages/kornia/contrib/visual_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..d1aab672898bca8b90f59f6d2598a55c4cca9055 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/visual_prompter.py @@ -0,0 +1,405 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any, Optional + +import torch + +from kornia.augmentation import LongestMaxSize +from kornia.augmentation.container.augment import AugmentationSequential +from kornia.contrib.models import Prompts, SegmentationResults +from kornia.contrib.models.sam import Sam, SamConfig +from kornia.core import Tensor, pad, tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE +from kornia.enhance import normalize +from kornia.geometry.boxes import Boxes +from kornia.geometry.keypoints import Keypoints + + +class VisualPrompter: + r"""Allow the user to run multiple query with multiple prompts for a model. + + At the moment, we just support the SAM model. The model is loaded based on the given config. + + For default the images are transformed to have their long side with size of the `image_encoder.img_size`. This + Prompter class ensure to transform the images and the prompts before prediction. Also, the image is passed + automatically for the method `preprocess_image`, which is responsible for normalize the image and pad it to have + the right size for the SAM model :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`. For + default the image is normalized by the mean and standard deviation of the SAM dataset values. + + Args: + config: A model config to generate the model. Now just the SAM model is supported. + device: The desired device to use the model. + dtype: The desired dtype to use the model. + + Example: + >>> # prompter = VisualPrompter() # Will load the vit h for default + >>> # You can load a custom SAM type for modifying the config + >>> prompter = VisualPrompter(SamConfig('vit_b')) + >>> image = torch.rand(3, 25, 30) + >>> prompter.set_image(image) + >>> boxes = Boxes( + ... torch.tensor( + ... [[[[0, 0], [0, 10], [10, 0], [10, 10]]]], + ... device=prompter.device, + ... dtype=torch.float32 + ... ), + ... mode='xyxy' + ... ) + >>> prediction = prompter.predict(boxes=boxes) + >>> prediction.logits.shape + torch.Size([1, 3, 256, 256]) + + """ + + def __init__( + self, + config: Optional[SamConfig] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ) -> None: + super().__init__() + if config is None: + config = SamConfig(model_type="vit_h", pretrained=True) + + if isinstance(config, SamConfig): + self.model = Sam.from_config(config) + transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),) + self.pixel_mean: Optional[Tensor] = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255 + self.pixel_std: Optional[Tensor] = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255 + else: + raise NotImplementedError + + self.model = self.model.to(device=device, dtype=dtype) + self.transforms = AugmentationSequential(*transforms, same_on_batch=True) + + self.device = device + self.dtype = dtype + self._original_image_size: None | tuple[int, int] = None + self._input_image_size: None | tuple[int, int] = None + self._input_encoder_size: None | tuple[int, int] = None + self.reset_image() + + def preprocess_image(self, x: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> Tensor: + """Normalize and pad a tensor. + + For normalize the tensor: will prioritize the `mean` and `std` passed as argument, if None will use the default + Sam Dataset values. + + For pad the tensor: Will pad the tensor into the right and bottom to match with the size of + `self.model.image_encoder.img_size` + + Args: + x: The image to be preprocessed + mean: Mean for each channel. + std: Standard deviations for each channel. + + Returns: + The image preprocessed (normalized if has mean and str available and padded to encoder size) + + """ + if isinstance(mean, Tensor) and isinstance(std, Tensor): + x = normalize(x, mean, std) + elif isinstance(self.pixel_mean, Tensor) and isinstance(self.pixel_std, Tensor): + x = normalize(x, self.pixel_mean, self.pixel_std) + + encoder_im_size = self.model.image_encoder.img_size + pad_h = encoder_im_size - x.shape[-2] + pad_w = encoder_im_size - x.shape[-1] + x = pad(x, (0, pad_w, 0, pad_h)) + + return x + + @torch.no_grad() + def set_image(self, image: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> None: + """Set the embeddings from the given image with `image_decoder` of the model. + + Prepare the given image with the selected transforms and the preprocess method. + + Args: + image: RGB image. Normally images with range of [0-1], the model preprocess normalize the + pixel values with the mean and std defined in its initialization. Expected to be into a float32 + dtype. Shape :math:`(3, H, W)`. + mean: mean value of dataset for normalization. + std: standard deviation of dataset for normalization. + + """ + KORNIA_CHECK_SHAPE(image, ["3", "H", "W"]) + + self.reset_image() + + self._original_image_size = (image.shape[-2], image.shape[-1]) + + image = self.transforms(image, data_keys=["input"]) + self._tfs_params = self.transforms._params + self._input_image_size = (image.shape[-2], image.shape[-1]) + + image = self.preprocess_image(image, mean, std) + + self._input_encoder_size = (image.shape[-2], image.shape[-1]) + + self.image_embeddings = self.model.image_encoder(image) + self.is_image_set = True + + def _valid_keypoints(self, keypoints: Keypoints | Tensor, labels: Tensor) -> Keypoints: + """Validate the keypoints shape and ensure to be a Keypoints.""" + KORNIA_CHECK_SHAPE(keypoints.data, ["K", "N", "2"]) + KORNIA_CHECK_SHAPE(labels.data, ["K", "N"]) + KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], "The keypoints and labels should have the same batch size") + + if isinstance(keypoints, Tensor): + keypoints = Keypoints.from_tensor(keypoints) + + return keypoints + + def _valid_boxes(self, boxes: Boxes | Tensor) -> Boxes: + """Validate the boxes shape and ensure to be a Boxes into xyxy mode.""" + if isinstance(boxes, Tensor): + KORNIA_CHECK_SHAPE(boxes.data, ["K", "4"]) + boxes = Boxes(boxes, mode="xyxy") + + if boxes.mode == "xyxy": + boxes_xyxy = boxes + else: + boxes_xyxy = Boxes(boxes.to_tensor(mode="xyxy"), mode="xyxy") + + return boxes_xyxy + + def _valid_masks(self, masks: Tensor) -> Tensor: + """Validate the input masks shape.""" + KORNIA_CHECK_SHAPE(masks, ["K", "1", "256", "256"]) + return masks + + def _transform_prompts( + self, *prompts: Tensor | Boxes | Keypoints, data_keys: Optional[list[str]] = None + ) -> dict[str, Tensor | Boxes | Keypoints]: + transformed_prompts = self.transforms(*prompts, data_keys=data_keys, params=self._tfs_params) + if data_keys is None: + data_keys = [] + + # prevent unpacking tensor when creating the output dict (issue #2627) + if not isinstance(transformed_prompts, (list, tuple)): + transformed_prompts = [transformed_prompts] + return {key: transformed_prompts[idx] for idx, key in enumerate(data_keys)} + + def preprocess_prompts( + self, + keypoints: Optional[Keypoints | Tensor] = None, + keypoints_labels: Optional[Tensor] = None, + boxes: Optional[Boxes | Tensor] = None, + masks: Optional[Tensor] = None, + ) -> Prompts: + """Validate and preprocess the given prompts to be aligned with the input image.""" + data_keys = [] + to_transform: list[Keypoints | Boxes | Tensor] = [] + + if isinstance(keypoints, (Keypoints, Tensor)) and isinstance(keypoints_labels, Tensor): + keypoints = self._valid_keypoints(keypoints, keypoints_labels) + data_keys.append("keypoints") + to_transform.append(keypoints) + + if isinstance(boxes, (Boxes, Tensor)): + self._valid_boxes(boxes) + data_keys.append("bbox_xyxy") + to_transform.append(boxes) + + if isinstance(masks, Tensor): + self._valid_masks(masks) + + data = self._transform_prompts(*to_transform, data_keys=data_keys) + + if "keypoints" in data and isinstance(data["keypoints"], Keypoints): + kpts_tensor = data["keypoints"].to_tensor() + if KORNIA_CHECK_IS_TENSOR(kpts_tensor) and KORNIA_CHECK_IS_TENSOR(keypoints_labels): + points = (kpts_tensor, keypoints_labels) + else: + points = None + + if "bbox_xyxy" in data and isinstance(data["bbox_xyxy"], Boxes): + _bbox = data["bbox_xyxy"].to_tensor(mode="xyxy") + if KORNIA_CHECK_IS_TENSOR(_bbox): + bbox = _bbox + else: + bbox = None + + return Prompts(points=points, boxes=bbox, masks=masks) + + @torch.no_grad() + def predict( + self, + keypoints: Optional[Keypoints | Tensor] = None, + keypoints_labels: Optional[Tensor] = None, + boxes: Optional[Boxes | Tensor] = None, + masks: Optional[Tensor] = None, + multimask_output: bool = True, + output_original_size: bool = True, + ) -> SegmentationResults: + """Predict masks for the given image based on the input prompts. + + Args: + keypoints: Point prompts to the model. Each point is in (X,Y) in pixels. Shape :math:`(K, N, 2)`. Where + `N` is the number of points and `K` the number of prompts. + keypoints_labels: Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background + point. Shape :math:`(K, N)`. Where `N` is the number of points, and `K` the number of + prompts. + boxes: A box prompt to the model. If a tensor, should be in a xyxy mode. Shape :math:`(K, 4)` + masks: A low resolution mask input to the model, typically coming from a previous prediction + iteration. Has shape :math:`(K, 1, H, W)`, where for SAM, H=W=256. + multimask_output: If true, the model will return three masks. For ambiguous input prompts (such as a + single click), this will often produce better masks than a single prediction. If only + a single mask is needed, the model's predicted quality score can be used to select the + best mask. For non-ambiguous prompts, such as multiple input prompts, + multimask_output=False can give better results. + output_original_size: If true, the logits of `SegmentationResults` will be post-process to match the + original input image size. + + Returns: + A prediction with the logits and scores (IoU of each predicted mask) + + """ + KORNIA_CHECK(self.is_image_set, "An image must be set with `self.set_image(...)` before `predict` be called!") + + prompts = self.preprocess_prompts(keypoints, keypoints_labels, boxes, masks) + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=prompts.points, boxes=prompts.boxes, masks=prompts.masks + ) + del prompts + + # Predict masks + logits, scores = self.model.mask_decoder( + image_embeddings=self.image_embeddings, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + results = SegmentationResults(logits, scores) + if ( + output_original_size + and isinstance(self._input_image_size, tuple) + and isinstance(self._original_image_size, tuple) + ): + results.original_res_logits(self._input_image_size, self._original_image_size, self._input_encoder_size) + + # results = results.squeeze(0) + + return results + + def reset_image(self) -> None: + self._tfs_params = None + self._original_image_size = None + self._input_image_size = None + self._input_encoder_size = None + + if hasattr(self, "image_embeddings"): + del self.image_embeddings + + self.image_embeddings = None + self.is_image_set = False + + def compile( + self, + *, + fullgraph: bool = False, + dynamic: bool = False, + backend: str = "inductor", + mode: Optional[str] = None, + options: Optional[dict[Any, Any]] = None, + disable: bool = False, + ) -> None: + """Apply `torch.compile(...)`/dynamo API into the VisualPrompter API. + + .. note:: For more information about the dynamo API check the official docs + https://pytorch.org/docs/stable/generated/torch.compile.html + + Args: + fullgraph: Whether it is ok to break model into several subgraphs + dynamic: Use dynamic shape tracing + backend: backend to be used + mode: Can be either “default”, “reduce-overhead” or “max-autotune” + options: A dictionary of options to pass to the backend. + disable: Turn torch.compile() into a no-op for testing + + Example: + >>> # prompter = VisualPrompter() + >>> # prompter.compile() # You should have torch >= 2.0.0 installed + >>> # Use the prompter methods ... + + """ + # self.set_image = torch.compile( # type: ignore[method-assign] + # self.set_image, + # fullgraph=fullgraph, + # dynamic=dynamic, + # backend=backend, + # mode=mode, + # options=options, + # disable=disable, + # ) + # FIXME: compile set image will try to compile AugmentationSequential which fails + self.model.image_encoder = torch.compile( # type: ignore + self.model.image_encoder, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + + # self.preprocess_image = torch.compile( # type: ignore[method-assign] + # self.preprocess_image, + # fullgraph=fullgraph, + # dynamic=dynamic, + # backend=backend, + # mode=mode, + # options=options, + # disable=disable, + # ) + + # FIXME: compile predict will try to compile Preproc prompts, which need to compileAugmentationSequential + # which fails + # self.predict = torch.compile( # type: ignore[method-assign] + # self.predict, + # fullgraph=fullgraph, + # dynamic=dynamic, + # backend=backend, + # mode=mode, + # options=options, + # disable=disable, + # ) + self.model.mask_decoder = torch.compile( # type: ignore + self.model.mask_decoder, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + self.model.prompt_encoder = torch.compile( # type: ignore + self.model.prompt_encoder, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) diff --git a/python_embeded/Lib/site-packages/kornia/contrib/vit.py b/python_embeded/Lib/site-packages/kornia/contrib/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c31ea7a10f4fe6cbb81a679ae7d31346f649a9 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/vit.py @@ -0,0 +1,316 @@ +# 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. +# + +"""Module that implement Vision Transformer (ViT). + +Paper: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transformers-1 + +Based on: `https://towardsdatascience.com/implementing-visualttransformer-in-pytorch-184f9f16f632` + +Added some tricks from: `https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py` +""" + +from __future__ import annotations + +from typing import Any, Callable + +import torch +from torch import nn + +from kornia.core import Module, Tensor, concatenate +from kornia.core.check import KORNIA_CHECK + +__all__ = ["VisionTransformer"] + + +class ResidualAdd(Module): + def __init__(self, fn: Callable[..., Tensor]) -> None: + super().__init__() + self.fn = fn + + def forward(self, x: Tensor, **kwargs: Any) -> Tensor: + res = x + x = self.fn(x, **kwargs) + x += res + return x + + +class FeedForward(nn.Sequential): + def __init__(self, in_features: int, hidden_features: int, out_features: int, dropout_rate: float = 0.0) -> None: + super().__init__( + nn.Linear(in_features, hidden_features), + nn.GELU(), + nn.Dropout(dropout_rate), + nn.Linear(hidden_features, out_features), + nn.Dropout(dropout_rate), # added one extra as in timm + ) + + +class MultiHeadAttention(Module): + def __init__(self, emb_size: int, num_heads: int, att_drop: float, proj_drop: float) -> None: + super().__init__() + self.emb_size = emb_size + self.num_heads = num_heads + head_size = emb_size // num_heads # from timm + self.scale = head_size**-0.5 # from timm + + if self.emb_size % self.num_heads: + raise ValueError( + f"Size of embedding inside the transformer decoder must be visible by number of heads" + f"for correct multi-head attention " + f"Got: {self.emb_size} embedding size and {self.num_heads} numbers of heads" + ) + + # fuse the queries, keys and values in one matrix + self.qkv = nn.Linear(emb_size, emb_size * 3) + self.att_drop = nn.Dropout(att_drop) + self.projection = nn.Linear(emb_size, emb_size) + self.projection_drop = nn.Dropout(proj_drop) # added timm trick + + def forward(self, x: Tensor) -> Tensor: + B, N, C = x.shape + # split keys, queries and values in num_heads + # NOTE: the line below differs from timm + # timm: qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + + # sum up over the last axis + att = torch.einsum("bhqd, bhkd -> bhqk", q, k) * self.scale + att = att.softmax(dim=-1) + att = self.att_drop(att) + + # sum up over the third axis + out = torch.einsum("bhal, bhlv -> bhav ", att, v) + out = out.permute(0, 2, 1, 3).contiguous().view(B, N, -1) + out = self.projection(out) + out = self.projection_drop(out) + return out + + +class TransformerEncoderBlock(nn.Sequential): + def __init__(self, embed_dim: int, num_heads: int, dropout_rate: float, dropout_attn: float) -> None: + super().__init__( + ResidualAdd( + nn.Sequential( + nn.LayerNorm(embed_dim, 1e-6), + MultiHeadAttention(embed_dim, num_heads, dropout_attn, dropout_rate), + nn.Dropout(dropout_rate), + ) + ), + ResidualAdd( + nn.Sequential( + nn.LayerNorm(embed_dim, 1e-6), + FeedForward(embed_dim, embed_dim * 4, embed_dim, dropout_rate=dropout_rate), + nn.Dropout(dropout_rate), + ) + ), + ) + + +class TransformerEncoder(Module): + def __init__( + self, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + dropout_rate: float = 0.0, + dropout_attn: float = 0.0, + ) -> None: + super().__init__() + self.blocks = nn.Sequential( + *(TransformerEncoderBlock(embed_dim, num_heads, dropout_rate, dropout_attn) for _ in range(depth)) + ) + self.results: list[Tensor] = [] + + def forward(self, x: Tensor) -> Tensor: + self.results = [] + out = x + for m in self.blocks.children(): + out = m(out) + self.results.append(out) + return out + + +class PatchEmbedding(Module): + """Compute the 2d image patch embedding ready to pass to transformer encoder.""" + + def __init__( + self, + in_channels: int = 3, + out_channels: int = 768, + patch_size: int = 16, + image_size: int = 224, + backbone: Module | None = None, + ) -> None: + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.patch_size = patch_size + + # logic needed in case a backbone is passed + self.backbone = backbone or nn.Conv2d(in_channels, out_channels, kernel_size=patch_size, stride=patch_size) + if backbone is not None: + out_channels, feat_size = self._compute_feats_dims((in_channels, image_size, image_size)) + self.out_channels = out_channels + else: + feat_size = (image_size // patch_size) ** 2 + + self.cls_token = nn.Parameter(torch.randn(1, 1, out_channels)) + self.positions = nn.Parameter(torch.randn(feat_size + 1, out_channels)) + + def _compute_feats_dims(self, image_size: tuple[int, int, int]) -> tuple[int, int]: + out = self.backbone(torch.zeros(1, *image_size)).detach() + return out.shape[-3], out.shape[-2] * out.shape[-1] + + def forward(self, x: Tensor) -> Tensor: + x = self.backbone(x) + B, N, _, _ = x.shape + x = x.view(B, N, -1).permute(0, 2, 1) # BxNxE + cls_tokens = self.cls_token.repeat(B, 1, 1) # Bx1xE + # prepend the cls token to the input + x = concatenate([cls_tokens, x], dim=1) # Bx(N+1)xE + # add position embedding + x += self.positions + return x + + +class VisionTransformer(Module): + """Vision transformer (ViT) module. + + The module is expected to be used as operator for different vision tasks. + + The method is inspired from existing implementations of the paper :cite:`dosovitskiy2020vit`. + + .. warning:: + This is an experimental API subject to changes in favor of flexibility. + + Args: + image_size: the size of the input image. + patch_size: the size of the patch to compute the embedding. + in_channels: the number of channels for the input. + embed_dim: the embedding dimension inside the transformer encoder. + depth: the depth of the transformer. + num_heads: the number of attention heads. + dropout_rate: dropout rate. + dropout_attn: attention dropout rate. + backbone: an nn.Module to compute the image patches embeddings. + + Example: + >>> img = torch.rand(1, 3, 224, 224) + >>> vit = VisionTransformer(image_size=224, patch_size=16) + >>> vit(img).shape + torch.Size([1, 197, 768]) + + """ + + def __init__( + self, + image_size: int = 224, + patch_size: int = 16, + in_channels: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + dropout_rate: float = 0.0, + dropout_attn: float = 0.0, + backbone: Module | None = None, + ) -> None: + super().__init__() + self.image_size = image_size + self.patch_size = patch_size + self.in_channels = in_channels + self.embed_size = embed_dim + + self.patch_embedding = PatchEmbedding(in_channels, embed_dim, patch_size, image_size, backbone) + hidden_dim = self.patch_embedding.out_channels + self.encoder = TransformerEncoder(hidden_dim, depth, num_heads, dropout_rate, dropout_attn) + self.norm = nn.LayerNorm(hidden_dim, 1e-6) + + @property + def encoder_results(self) -> list[Tensor]: + return self.encoder.results + + def forward(self, x: Tensor) -> Tensor: + if not isinstance(x, Tensor): + raise TypeError(f"Input x type is not a Tensor. Got: {type(x)}") + + if self.image_size not in (*x.shape[-2:],) and x.shape[-3] != self.in_channels: + raise ValueError( + f"Input image shape must be Bx{self.in_channels}x{self.image_size}x{self.image_size}. Got: {x.shape}" + ) + + out = self.patch_embedding(x) + out = self.encoder(out) + out = self.norm(out) + return out + + @staticmethod + def from_config(variant: str, pretrained: bool = False, **kwargs: Any) -> VisionTransformer: + """Build ViT model based on the given config string. + + The format is ``vit_{size}/{patch_size}``. + E.g. ``vit_b/16`` means ViT-Base, patch size 16x16. If ``pretrained=True``, AugReg weights are loaded. + The weights are hosted on HuggingFace's model hub: https://huggingface.co/kornia. + + .. note:: + The available weights are: ``vit_l/16``, ``vit_b/16``, ``vit_s/16``, ``vit_ti/16``, + ``vit_b/32``, ``vit_s/32``. + + Args: + variant: ViT model variant e.g. ``vit_b/16``. + pretrained: whether to load pre-trained AugReg weights. + kwargs: other keyword arguments that will be passed to :func:`kornia.contrib.vit.VisionTransformer`. + + Returns: + The respective ViT model + + Example: + >>> from kornia.contrib import VisionTransformer + >>> vit_model = VisionTransformer.from_config("vit_b/16", pretrained=True) + + """ + model_type, patch_size_str = variant.split("/") + patch_size = int(patch_size_str) + + model_config = { + "vit_ti": {"embed_dim": 192, "depth": 12, "num_heads": 3}, + "vit_s": {"embed_dim": 384, "depth": 12, "num_heads": 6}, + "vit_b": {"embed_dim": 768, "depth": 12, "num_heads": 12}, + "vit_l": {"embed_dim": 1024, "depth": 24, "num_heads": 16}, + "vit_h": {"embed_dim": 1280, "depth": 32, "num_heads": 16}, + }[model_type] + kwargs.update(model_config, patch_size=patch_size) + + model = VisionTransformer(**kwargs) + + if pretrained: + url = _get_weight_url(variant) + state_dict = torch.hub.load_state_dict_from_url(url) + model.load_state_dict(state_dict) + + return model + + +_AVAILABLE_WEIGHTS = ["vit_l/16", "vit_b/16", "vit_s/16", "vit_ti/16", "vit_b/32", "vit_s/32"] + + +def _get_weight_url(variant: str) -> str: + """Return the URL of the model weights.""" + KORNIA_CHECK(variant in _AVAILABLE_WEIGHTS, f"Variant {variant} does not have pre-trained checkpoint") + model_type, patch_size = variant.split("/") + return f"https://huggingface.co/kornia/{model_type}{patch_size}_augreg_i21k_r224/resolve/main/{model_type}-{patch_size}.pth" diff --git a/python_embeded/Lib/site-packages/kornia/contrib/vit_mobile.py b/python_embeded/Lib/site-packages/kornia/contrib/vit_mobile.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8ee3a17ed2513b54b85de7145300f1a2267972 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/contrib/vit_mobile.py @@ -0,0 +1,319 @@ +# 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. +# + +from typing import Any, Dict, Tuple + +import torch +from torch import nn + +from kornia.core import Module, Tensor + + +def conv_1x1_bn(inp: int, oup: int) -> Module: + """Apply 1x1 Convolution with Batch Norm.""" + return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.SiLU()) + + +def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> Module: + """Apply NxN Convolution with Batch Norm.""" + return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.SiLU()) + + +class PreNorm(Module): + def __init__(self, dim: int, fn: Module) -> None: + super().__init__() + self.norm = nn.LayerNorm(dim) + self.fn = fn + + def forward(self, x: Tensor, **kwargs: Dict[str, Any]) -> Tensor: + return self.fn(self.norm(x), **kwargs) + + +class FeedForward(Module): + def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None: + super().__init__() + self.net = nn.Sequential( + nn.Linear(dim, hidden_dim), nn.SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout) + ) + + def forward(self, x: Tensor) -> Tensor: + return self.net(x) + + +class Attention(Module): + def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None: + super().__init__() + inner_dim = dim_head * heads + project_out = not (heads == 1 and dim_head == dim) + + self.heads = heads + self.scale = dim_head**-0.5 + + self.attend = nn.Softmax(dim=-1) + self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False) + + self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + qkv = self.to_qkv(x).chunk(3, dim=-1) + + b, p, n, hd = qkv[0].shape + q, k, v = (t.reshape(b, p, n, self.heads, hd // self.heads).transpose(2, 3) for t in qkv) + + dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale + attn = self.attend(dots) + out = torch.matmul(attn, v) + out = out.transpose(2, 3).reshape(b, p, n, hd) + return self.to_out(out) + + +class Transformer(Module): + """Transformer block described in ViT. + + Paper: https://arxiv.org/abs/2010.11929 + Based on: https://github.com/lucidrains/vit-pytorch + + Args: + dim: input dimension. + depth: depth for transformer block. + heads: number of heads in multi-head attention layer. + dim_head: head size. + mlp_dim: dimension of the FeedForward layer. + dropout: dropout ratio, defaults to 0. + + """ + + def __init__(self, dim: int, depth: int, heads: int, dim_head: int, mlp_dim: int, dropout: float = 0.0) -> None: + super().__init__() + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PreNorm(dim, Attention(dim, heads, dim_head, dropout)), + PreNorm(dim, FeedForward(dim, mlp_dim, dropout)), + ] + ) + ) + + def forward(self, x: Tensor) -> Tensor: + for attn, ff in self.layers: + x = attn(x) + x + x = ff(x) + x + return x + + +class MV2Block(Module): + """MV2 block described in MobileNetV2. + + Paper: https://arxiv.org/pdf/1801.04381 + Based on: https://github.com/tonylins/pytorch-mobilenet-v2 + + Args: + inp: input channel. + oup: output channel. + stride: stride for convolution, defaults to 1, set to 2 if down-sample. + expansion: expansion ratio for hidden dimension, defaults to 4. + + """ + + def __init__(self, inp: int, oup: int, stride: int = 1, expansion: int = 4) -> None: + super().__init__() + self.stride = stride + + hidden_dim = int(inp * expansion) + self.use_res_connect = self.stride == 1 and inp == oup + + if expansion == 1: + self.conv = nn.Sequential( + # depthwise + nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False), + nn.BatchNorm2d(hidden_dim), + nn.SiLU(), + # pointwise + nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), + nn.BatchNorm2d(oup), + ) + else: + self.conv = nn.Sequential( + # pointwise + nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), + nn.BatchNorm2d(hidden_dim), + nn.SiLU(), + # depthwise + nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False), + nn.BatchNorm2d(hidden_dim), + nn.SiLU(), + # pointwise + nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), + nn.BatchNorm2d(oup), + ) + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + +class MobileViTBlock(Module): + """MobileViT block mentioned in MobileViT. + + Args: + dim: input dimension of Transformer. + depth: depth of Transformer. + channel: input channel. + kernel_size: kernel size. + patch_size: patch size for folding and unfloding. + mlp_dim: dimension of the FeedForward layer in Transformer. + dropout: dropout ratio, defaults to 0. + + """ + + def __init__( + self, + dim: int, + depth: int, + channel: int, + kernel_size: int, + patch_size: Tuple[int, int], + mlp_dim: int, + dropout: float = 0.0, + ) -> None: + super().__init__() + self.ph, self.pw = patch_size + + self.conv1 = conv_nxn_bn(channel, channel, kernel_size) + self.conv2 = conv_1x1_bn(channel, dim) + + self.transformer = Transformer(dim, depth, 4, 8, mlp_dim, dropout) + + self.conv3 = conv_1x1_bn(dim, channel) + self.conv4 = conv_nxn_bn(2 * channel, channel, kernel_size) + + def forward(self, x: Tensor) -> Tensor: + y = x.clone() + + # Local representations + x = self.conv1(x) + x = self.conv2(x) + + b, d, h, w = x.shape + nh, nw = h // self.ph, w // self.pw + + # Global representations + # [b, d, h, w] -> [b * d * nh, nw, ph, pw] + x = x.reshape(b * d * nh, self.ph, nw, self.pw).transpose(1, 2) + # [b * d * nh, nw, ph, pw] -> [b, (ph pw), (nh nw), d] + x = x.reshape(b, d, nh * nw, self.ph * self.pw).transpose(1, 3) + + x = self.transformer(x) + + # [b, (ph pw), (nh nw), d] -> [b * d * nh, nw, ph, pw] + x = x.transpose(1, 3).reshape(b * d * nh, nw, self.ph, self.pw) + # [b * d * nh, nw, ph, pw] -> [b, d, h, w] + x = x.transpose(1, 2).reshape(b, d, h, w) + + # Fusion + x = self.conv3(x) + x = torch.cat((x, y), 1) + x = self.conv4(x) + return x + + +class MobileViT(Module): + """Module MobileViT. Default arguments is for MobileViT XXS. + + Paper: https://arxiv.org/abs/2110.02178 + Based on: https://github.com/chinhsuanwu/mobilevit-pytorch + + Args: + mode: 'xxs', 'xs' or 's', defaults to 'xxs'. + in_channels: the number of channels for the input image. + patch_size: image_size must be divisible by patch_size. + dropout: dropout ratio in Transformer. + + Example: + >>> img = torch.rand(1, 3, 256, 256) + >>> mvit = MobileViT(mode='xxs') + >>> mvit(img).shape + torch.Size([1, 320, 8, 8]) + + """ + + def __init__( + self, mode: str = "xxs", in_channels: int = 3, patch_size: Tuple[int, int] = (2, 2), dropout: float = 0.0 + ) -> None: + super().__init__() + if mode == "xxs": + expansion = 2 + dims = [64, 80, 96] + channels = [16, 16, 24, 24, 48, 48, 64, 64, 80, 80, 320] + elif mode == "xs": + expansion = 4 + dims = [96, 120, 144] + channels = [16, 32, 48, 48, 64, 64, 80, 80, 96, 96, 384] + elif mode == "s": + expansion = 4 + dims = [144, 192, 240] + channels = [16, 32, 64, 64, 96, 96, 128, 128, 160, 160, 640] + + kernel_size = 3 + depth = [2, 4, 3] + + self.conv1 = conv_nxn_bn(in_channels, channels[0], stride=2) + + self.mv2 = nn.ModuleList([]) + self.mv2.append(MV2Block(channels[0], channels[1], 1, expansion)) + self.mv2.append(MV2Block(channels[1], channels[2], 2, expansion)) + self.mv2.append(MV2Block(channels[2], channels[3], 1, expansion)) + self.mv2.append(MV2Block(channels[2], channels[3], 1, expansion)) # Repeat + self.mv2.append(MV2Block(channels[3], channels[4], 2, expansion)) + self.mv2.append(MV2Block(channels[5], channels[6], 2, expansion)) + self.mv2.append(MV2Block(channels[7], channels[8], 2, expansion)) + + self.mvit = nn.ModuleList([]) + self.mvit.append( + MobileViTBlock(dims[0], depth[0], channels[5], kernel_size, patch_size, int(dims[0] * 2), dropout=dropout) + ) + self.mvit.append( + MobileViTBlock(dims[1], depth[1], channels[7], kernel_size, patch_size, int(dims[1] * 4), dropout=dropout) + ) + self.mvit.append( + MobileViTBlock(dims[2], depth[2], channels[9], kernel_size, patch_size, int(dims[2] * 4), dropout=dropout) + ) + + self.conv2 = conv_1x1_bn(channels[-2], channels[-1]) + + def forward(self, x: Tensor) -> Tensor: + x = self.conv1(x) + x = self.mv2[0](x) + + x = self.mv2[1](x) + x = self.mv2[2](x) + x = self.mv2[3](x) # Repeat + + x = self.mv2[4](x) + x = self.mvit[0](x) + + x = self.mv2[5](x) + x = self.mvit[1](x) + + x = self.mv2[6](x) + x = self.mvit[2](x) + x = self.conv2(x) + return x diff --git a/python_embeded/Lib/site-packages/kornia/core/__init__.py b/python_embeded/Lib/site-packages/kornia/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7f0a735e4159c4c7bd878009de0ab5979dbe8f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/__init__.py @@ -0,0 +1,103 @@ +# 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. +# + +from . import external +from ._backend import ( + Device, + Dtype, + Module, + ModuleList, + Parameter, + Sequential, + Tensor, + arange, + as_tensor, + complex, + concatenate, + cos, + deg2rad, + diag, + einsum, + eye, + linspace, + map_coordinates, + normalize, + ones, + ones_like, + pad, + rad2deg, + rand, + sin, + softmax, + stack, + tan, + tensor, + where, + zeros, + zeros_like, +) +from .mixin import ( + ImageModuleMixIn, + ONNXExportMixin, + ONNXMixin, + ONNXRuntimeMixin, +) +from .module import ImageModule, ImageSequential +from .tensor_wrapper import TensorWrapper # type: ignore + +__all__ = [ + "Device", + "Dtype", + "ImageModule", + "ImageModuleMixIn", + "ImageSequential", + "Module", + "ModuleList", + "ONNXExportMixin", + "ONNXMixin", + "ONNXRuntimeMixin", + "Parameter", + "Sequential", + "Tensor", + "TensorWrapper", + "arange", + "as_tensor", + "complex", + "concatenate", + "cos", + "deg2rad", + "diag", + "einsum", + "external", + "eye", + "linspace", + "map_coordinates", + "normalize", + "ones", + "ones_like", + "pad", + "rad2deg", + "rand", + "sin", + "softmax", + "stack", + "tan", + "tensor", + "where", + "zeros", + "zeros_like", +] diff --git a/python_embeded/Lib/site-packages/kornia/core/_backend.py b/python_embeded/Lib/site-packages/kornia/core/_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..07f04f5d6e9a544a08733b84920249fe3ccc426e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/_backend.py @@ -0,0 +1,66 @@ +# 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. +# + +from __future__ import annotations + +from typing import Union + +import torch + +# classes +Tensor = torch.Tensor +tensor = torch.tensor +Module = torch.nn.Module +ModuleList = torch.nn.ModuleList +Parameter = torch.nn.Parameter +Sequential = torch.nn.Sequential + +# functions +# NOTE: ideally we expose what we find in numpy +arange = torch.arange +concatenate = torch.cat +stack = torch.stack +linspace = torch.linspace +normalize = torch.nn.functional.normalize +pad = torch.nn.functional.pad +eye = torch.eye +einsum = torch.einsum +zeros = torch.zeros +zeros_like = torch.zeros_like +ones = torch.ones +ones_like = torch.ones_like +where = torch.where +complex = torch.complex +diag = torch.diag +softmax = torch.nn.functional.softmax +map_coordinates = torch.nn.functional.grid_sample +cos = torch.cos +sin = torch.sin +tan = torch.tan +deg2rad = torch.deg2rad +rad2deg = torch.rad2deg + +# constructors +as_tensor = torch.as_tensor +from_numpy = torch.from_numpy + +# random +rand = torch.rand + +# type alias +Device = Union[str, torch.device, None] +Dtype = Union[torch.dtype, None] diff --git a/python_embeded/Lib/site-packages/kornia/core/check.py b/python_embeded/Lib/site-packages/kornia/core/check.py new file mode 100644 index 0000000000000000000000000000000000000000..91abe55d2a05129c55fd5a2a150da5036395ce3f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/check.py @@ -0,0 +1,466 @@ +# 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. +# + +"""The testing package contains testing-specific utilities.""" + +from __future__ import annotations + +from typing import Any, Optional, Sequence, TypeVar, cast + +from torch import float16, float32, float64 +from typing_extensions import TypeGuard + +from kornia.core import Tensor + +__all__ = [ + "KORNIA_CHECK", + "KORNIA_CHECK_DM_DESC", + "KORNIA_CHECK_IS_COLOR", + "KORNIA_CHECK_IS_GRAY", + "KORNIA_CHECK_IS_IMAGE", + "KORNIA_CHECK_IS_LIST_OF_TENSOR", + "KORNIA_CHECK_IS_TENSOR", + "KORNIA_CHECK_LAF", + "KORNIA_CHECK_SAME_DEVICE", + "KORNIA_CHECK_SAME_DEVICES", + "KORNIA_CHECK_SHAPE", + "KORNIA_CHECK_TYPE", + "KORNIA_UNWRAP", +] + +# Logger api + + +# TODO: add somehow type check, or enforce to do it before +def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> bool: + """Check whether a tensor has a specified shape. + + The shape can be specified with a implicit or explicit list of strings. + The guard also check whether the variable is a type `Tensor`. + + Args: + x: the tensor to evaluate. + shape: a list with strings with the expected shape. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + Exception: if the input tensor is has not the expected shape and raises is True. + + Example: + >>> x = torch.rand(2, 3, 4, 4) + >>> KORNIA_CHECK_SHAPE(x, ["B", "C", "H", "W"]) # implicit + True + + >>> x = torch.rand(2, 3, 4, 4) + >>> KORNIA_CHECK_SHAPE(x, ["2", "3", "H", "W"]) # explicit + True + + """ + if "*" == shape[0]: + shape_to_check = shape[1:] + x_shape_to_check = x.shape[-len(shape) + 1 :] + elif "*" == shape[-1]: + shape_to_check = shape[:-1] + x_shape_to_check = x.shape[: len(shape) - 1] + else: + shape_to_check = shape + x_shape_to_check = x.shape + + if len(x_shape_to_check) != len(shape_to_check): + if raises: + raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}") + else: + return False + + for i in range(len(x_shape_to_check)): + # The voodoo below is because torchscript does not like + # that dim can be both int and str + dim_: str = shape_to_check[i] + if not dim_.isnumeric(): + continue + dim = int(dim_) + if x_shape_to_check[i] != dim: + if raises: + raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}") + else: + return False + return True + + +def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True) -> bool: + """Check any arbitrary boolean condition. + + Args: + condition: the condition to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + Exception: if the condition is met and raises is True. + + Example: + >>> x = torch.rand(2, 3, 3) + >>> KORNIA_CHECK(x.shape[-2:] == (3, 3), "Invalid homography") + True + + """ + if not condition: + if raises: + raise Exception(f"{condition} not true.\n{msg}") + return False + return True + + +def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any: + """Unwraps an optional contained value that may or not be present. + + Args: + maybe_obj: the object to unwrap. + typ: expected type after unwrap. + + """ + # TODO: this function will change after kornia/pr#1987 + return cast(typ, maybe_obj) + + +T = TypeVar("T", bound=type) + + +# TODO: fix mypy typeguard issue +def KORNIA_CHECK_TYPE( + x: object, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True +) -> TypeGuard[T]: + """Check the type of an aribratry variable. + + Args: + x: any input variable. + typ: the expected type of the variable. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the input variable does not match with the expected and raises is True. + + Example: + >>> KORNIA_CHECK_TYPE("foo", str, "Invalid string") + True + + """ + # TODO: Move to use typeguard here dropping support for JIT + if not isinstance(x, typ): + if raises: + raise TypeError(f"Invalid type: {type(x)}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[Tensor]: + """Check the input variable is a Tensor. + + Args: + x: any input variable. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the input variable does not match with the expected and raises is True. + + Example: + >>> x = torch.rand(2, 3, 3) + >>> KORNIA_CHECK_IS_TENSOR(x, "Invalid tensor") + True + + """ + # TODO: Move to use typeguard here dropping support for JIT + if not isinstance(x, Tensor): + if raises: + raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[Tensor]]: + """Check the input variable is a List of Tensors. + + Args: + x: Any sequence of objects + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the input variable does not match with the expected and raises is True. + + Return: + True if the input is a list of Tensors, otherwise return False. + + Example: + >>> x = torch.rand(2, 3, 3) + >>> KORNIA_CHECK_IS_LIST_OF_TENSOR(x, raises=False) + False + >>> KORNIA_CHECK_IS_LIST_OF_TENSOR([x]) + True + + """ + are_tensors = isinstance(x, list) and all(isinstance(d, Tensor) for d in x) + if not are_tensors: + if raises: + raise TypeError(f"Provided container of type {type(x)} is not a list of tensors") + return False + return True + + +def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool: + """Check whether two tensor in the same device. + + Args: + x: first tensor to evaluate. + y: sencod tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the two tensors are not in the same device and raises is True. + + Example: + >>> x1 = torch.rand(2, 3, 3) + >>> x2 = torch.rand(1, 3, 1) + >>> KORNIA_CHECK_SAME_DEVICE(x1, x2) + True + + """ + if x.device != y.device: + if raises: + raise TypeError(f"Not same device for tensors. Got: {x.device} and {y.device}") + return False + return True + + +def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None, raises: bool = True) -> bool: + """Check whether a list provided tensors live in the same device. + + Args: + tensors: a list of tensors. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + Exception: if all the tensors are not in the same device and raises is True. + + Example: + >>> x1 = torch.rand(2, 3, 3) + >>> x2 = torch.rand(1, 3, 1) + >>> KORNIA_CHECK_SAME_DEVICES([x1, x2], "Tensors not in the same device") + True + + """ + KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, "Expected a list with at least one element", raises) + if not all(tensors[0].device == x.device for x in tensors): + if raises: + raise Exception(f"Not same device for tensors. Got: {[x.device for x in tensors]}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool: + """Check whether two tensor have the same shape. + + Args: + x: first tensor to evaluate. + y: sencod tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the two tensors have not the same shape and raises is True. + + Example: + >>> x1 = torch.rand(2, 3, 3) + >>> x2 = torch.rand(2, 3, 3) + >>> KORNIA_CHECK_SAME_SHAPE(x1, x2) + True + + """ + if x.shape != y.shape: + if raises: + raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}") + return False + return True + + +def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool: + """Check whether an image tensor is a color images. + + Args: + x: image tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if all the input tensor has not a shape :math:`(3,H,W)` and raises is True. + + Example: + >>> img = torch.rand(2, 3, 4, 4) + >>> KORNIA_CHECK_IS_COLOR(img, "Image is not color") + True + + """ + if len(x.shape) < 3 or x.shape[-3] != 3: + if raises: + raise TypeError(f"Not a color tensor. Got: {type(x)}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool: + """Check whether an image tensor is grayscale. + + Args: + x: image tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(H,W)` and raises is True. + + Example: + >>> img = torch.rand(2, 1, 4, 4) + >>> KORNIA_CHECK_IS_GRAY(img, "Image is not grayscale") + True + + """ + if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1): + if raises: + raise TypeError(f"Not a gray tensor. Got: {type(x)}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool: + """Check whether an image tensor is grayscale or color. + + Args: + x: image tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(3,H,W)` and raises is True. + + Example: + >>> img = torch.rand(2, 3, 4, 4) + >>> KORNIA_CHECK_IS_COLOR_OR_GRAY(img, "Image is not color or grayscale") + True + + """ + if len(x.shape) < 3 or x.shape[-3] not in [1, 3]: + if raises: + raise TypeError(f"Not a color or gray tensor. Got: {type(x)}.\n{msg}") + return False + return True + + +def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool: + """Check whether an image tensor is ranged properly [0, 1] for float or [0, 2 ** bits] for int. + + Args: + x: image tensor to evaluate. + msg: message to show in the exception. + raises: bool indicating whether an exception should be raised upon failure. + bits: the image bits. The default checks if given integer input image is an + 8-bit image (0-255) or not. + + Raises: + TypeException: if all the input tensor has not 1) a shape :math:`(3,H,W)`, + 2) [0, 1] for float or [0, 255] for int, 3) and raises is True. + + Example: + >>> img = torch.rand(2, 3, 4, 4) + >>> KORNIA_CHECK_IS_IMAGE(img, "It is not an image") + True + + """ + # Combine the color or gray check with the range check + if not raises and not KORNIA_CHECK_IS_COLOR_OR_GRAY(x, msg, raises): + return False + + min_val, max_val = x.min(), x.max() + if x.dtype in [float16, float32, float64]: + if min_val < 0.0 or max_val > 1.0: + return _handle_invalid_range(msg, raises, min_val, max_val) + else: + max_int_value = 2**bits - 1 + if min_val < 0 or max_val > max_int_value: + return _handle_invalid_range(msg, raises, min_val, max_val) + return True + + +def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: bool = True) -> bool: + """Check whether the provided descriptors match with a distance matrix. + + Args: + desc1: first descriptor tensor to evaluate. + desc2: second descriptor tensor to evaluate. + dm: distance matrix tensor to evaluate. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + TypeException: if the descriptors shape do not match with the distance matrix and raises is True. + + Example: + >>> desc1 = torch.rand(4) + >>> desc2 = torch.rand(8) + >>> dm = torch.rand(4, 8) + >>> KORNIA_CHECK_DM_DESC(desc1, desc2, dm) + True + + """ + if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))): + if raises: + raise TypeError( + f"distance matrix shape {dm.shape} is not onsistent with descriptors shape: desc1 {desc1.shape} " + f"desc2 {desc2.shape}" + ) + return False + return True + + +def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool: + """Check whether a Local Affine Frame (laf) has a valid shape. + + Args: + laf: local affine frame tensor to evaluate. + raises: bool indicating whether an exception should be raised upon failure. + + Raises: + Exception: if the input laf does not have a shape :math:`(B,N,2,3)` and raises is True. + + Example: + >>> lafs = torch.rand(2, 10, 2, 3) + >>> KORNIA_CHECK_LAF(lafs) + True + + """ + return KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"], raises) + + +def _handle_invalid_range(msg: Optional[str], raises: bool, min_val: float | Tensor, max_val: float | Tensor) -> bool: + """Helper function to handle invalid range cases.""" + err_msg = f"Invalid image value range. Expect [0, 1] but got [{min_val}, {max_val}]." + if msg is not None: + err_msg += f"\n{msg}" + if raises: + raise ValueError(err_msg) + return False diff --git a/python_embeded/Lib/site-packages/kornia/core/external.py b/python_embeded/Lib/site-packages/kornia/core/external.py new file mode 100644 index 0000000000000000000000000000000000000000..11aed1699084cac7b198a11faea776f399461846 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/external.py @@ -0,0 +1,162 @@ +# 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. +# + +import importlib +import logging +import subprocess +import sys +from types import ModuleType +from typing import List, Optional + +from kornia.config import InstallationMode, kornia_config + +logger = logging.getLogger(__name__) + + +class LazyLoader: + """A class that implements lazy loading for Python modules. + + This class defers the import of a module until an attribute of the module is accessed. + It helps in reducing the initial load time and memory usage of a script, especially when + dealing with large or optional dependencies that might not be used in every execution. + + Attributes: + module_name: The name of the module to be lazily loaded. + module: The actual module object, initialized to None and loaded upon first access. + + """ + + auto_install: bool = False + + def __init__(self, module_name: str, dev_dependency: bool = False) -> None: + """Initialize the LazyLoader with the name of the module. + + Args: + module_name: The name of the module to be lazily loaded. + dev_dependency: If the dependency is required in the dev environment. + If True, the module will be loaded in the dev environment. + If False, the module will not be loaded in the dev environment. + + """ + self.module_name = module_name + self.module: Optional[ModuleType] = None + self.dev_dependency = dev_dependency + + def _install_package(self, module_name: str) -> None: + logger.info(f"Installing `{module_name}` ...") + subprocess.run([sys.executable, "-m", "pip", "install", "-U", module_name], shell=False, check=False) # noqa: S603 + + def _load(self) -> None: + """Load the module if it hasn't been loaded yet. + + This method is called internally when an attribute of the module is accessed for the first time. It attempts to + import the module and raises an ImportError with a custom message if the module is not installed. + """ + if not self.dev_dependency: + if "--doctest-modules" in sys.argv: + logger.info(f"Doctest detected, skipping loading of '{self.module_name}'") + return + try: + if __sphinx_build__: # type:ignore + logger.info(f"Sphinx detected, skipping loading of '{self.module_name}'") + return + except NameError: + pass + + if self.module is None: + try: + self.module = importlib.import_module(self.module_name) + except ImportError as e: + if kornia_config.lazyloader.installation_mode == InstallationMode.AUTO or self.auto_install: + self._install_package(self.module_name) + elif kornia_config.lazyloader.installation_mode == InstallationMode.ASK: + to_ask = True + if_install = input( + f"Optional dependency '{self.module_name}' is not installed. " + "You may silent this prompt by `kornia_config.lazyloader.installation_mode = 'auto'`. " + "Do you wish to install the dependency? [Y]es, [N]o, [A]ll." + ) + while to_ask: + if if_install.lower() == "y" or if_install.lower() == "yes": + self._install_package(self.module_name) + self.module = importlib.import_module(self.module_name) + to_ask = False + elif if_install.lower() == "a" or if_install.lower() == "all": + self.auto_install = True + self._install_package(self.module_name) + self.module = importlib.import_module(self.module_name) + to_ask = False + elif if_install.lower() == "n" or if_install.lower() == "no": + raise ImportError( + f"Optional dependency '{self.module_name}' is not installed. " + f"Please install it to use this functionality." + ) from e + else: + if_install = input("Invalid input. Please enter 'Y', 'N', or 'A'.") + + elif kornia_config.lazyloader.installation_mode == InstallationMode.RAISE: + raise ImportError( + f"Optional dependency '{self.module_name}' is not installed. " + f"Please install it to use this functionality." + ) from e + self.module = importlib.import_module(self.module_name) + + def __getattr__(self, item: str) -> object: + """Load the module (if not already loaded) and returns the requested attribute. + + This method is called when an attribute of the LazyLoader instance is accessed. + It ensures that the module is loaded and then returns the requested attribute. + + Args: + item: The name of the attribute to be accessed. + + Returns: + The requested attribute of the loaded module. + + """ + self._load() + return getattr(self.module, item) + + def __dir__(self) -> List[str]: + """Load the module (if not already loaded) and returns the list of attributes of the module. + + This method is called when the built-in dir() function is used on the LazyLoader instance. + It ensures that the module is loaded and then returns the list of attributes of the module. + + Returns: + list: The list of attributes of the loaded module. + + """ + self._load() + return dir(self.module) + + +# NOTE: This section is used for lazy loading of external modules. However, sphinx +# would also try to support lazy loading of external modules. To avoid that, we +# may set the module name to `autodoc_mock_imports` in conf.py to avoid undesired +# installation of external modules. +numpy = LazyLoader("numpy", dev_dependency=True) +PILImage = LazyLoader("PIL.Image", dev_dependency=True) +onnx = LazyLoader("onnx", dev_dependency=True) +diffusers = LazyLoader("diffusers") +transformers = LazyLoader("transformers") +onnxruntime = LazyLoader("onnxruntime") +boxmot = LazyLoader("boxmot") +segmentation_models_pytorch = LazyLoader("segmentation_models_pytorch") +basicsr = LazyLoader("basicsr") +requests = LazyLoader("requests") +ivy = LazyLoader("ivy") diff --git a/python_embeded/Lib/site-packages/kornia/core/mixin/__init__.py b/python_embeded/Lib/site-packages/kornia/core/mixin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a0dbf88d60618bcba219ba3eb1c668a923b3850e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/mixin/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from .image_module import ImageModuleMixIn +from .onnx import ONNXExportMixin, ONNXMixin, ONNXRuntimeMixin diff --git a/python_embeded/Lib/site-packages/kornia/core/mixin/image_module.py b/python_embeded/Lib/site-packages/kornia/core/mixin/image_module.py new file mode 100644 index 0000000000000000000000000000000000000000..113dfba3bd040e1d20a9a0f4c00912f84e3ee0f5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/mixin/image_module.py @@ -0,0 +1,253 @@ +# 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. +# + +import datetime +import math +import os +from functools import wraps +from typing import Any, Callable, List, Optional, Tuple, Union + +from kornia.core._backend import Tensor, from_numpy +from kornia.core.external import PILImage as Image +from kornia.core.external import numpy as np + + +class ImageModuleMixIn: + """A MixIn that handles image-based operations. + + This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features. + Note that this MixIn fits the classes that return one image tensor only. + """ + + _output_image: Any + + def convert_input_output( + self, + input_names_to_handle: Optional[List[Any]] = None, + output_type: str = "tensor", + ) -> Callable[[Any], Any]: + """Convert input and output types for a function. + + Args: + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + + Returns: + Callable: Decorated function with converted input and output types. + + """ + + def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Union[Any, List[Any]]: + # If input_names_to_handle is None, handle all inputs + if input_names_to_handle is None: + # Convert all args to tensors + args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args) + # Convert all kwargs to tensors + kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()} + else: + # Convert specified args to tensors + args = list(args) # type:ignore + for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)): + if name in input_names_to_handle: + args[i] = self.to_tensor(arg) # type:ignore + # Convert specified kwargs to tensors + for name, value in kwargs.items(): + if name in input_names_to_handle: + kwargs[name] = self.to_tensor(value) + + # Call the actual forward method + tensor_outputs = func(*args, **kwargs) + + if not isinstance(tensor_outputs, (tuple,)): + tensor_outputs = (tensor_outputs,) + + # Convert outputs to the desired type + outputs = [] + for output in tensor_outputs: + if output_type == "tensor": + outputs.append(output) + elif output_type == "numpy": + outputs.append(self.to_numpy(output)) + elif output_type == "pil": + outputs.append(self.to_pil(output)) + else: + raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.") + + return outputs if len(outputs) > 1 else outputs[0] + + return wrapper + + return decorator + + def _is_valid_arg(self, arg: Any) -> bool: + """Check if the argument is a valid type for conversion. + + Args: + arg: The argument to check. + + Returns: + bool: True if valid, False otherwise. + + """ + if isinstance(arg, (str,)) and os.path.exists(arg): + return True + if isinstance(arg, (Tensor,)): + return True + # Make sure that the numpy and PIL are not necessarily needed to be imported. + if isinstance(arg, (np.ndarray,)): # type: ignore + return True + if isinstance(arg, (Image.Image)): # type: ignore + return True + return False + + def to_tensor(self, x: Any) -> Tensor: + """Convert input to tensor. + + Supports image path, numpy array, PIL image, and raw tensor. + + Args: + x: The input to convert. + + Returns: + Tensor: The converted tensor. + + """ + if isinstance(x, (str,)): + from kornia.io import ImageLoadType, load_image # pylint: disable=C0415 + + return load_image(x, ImageLoadType.UNCHANGED) / 255 + if isinstance(x, (Tensor,)): + return x + if isinstance(x, (np.ndarray,)): # type: ignore + from kornia.utils.image import image_to_tensor # pylint: disable=C0415 + + return image_to_tensor(x) / 255 + if isinstance(x, (Image.Image,)): # type: ignore + return from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore + raise TypeError("Input type not supported") + + def to_numpy(self, x: Any) -> "np.array": # type: ignore + """Convert input to numpy array. + + Args: + x: The input to convert. + + Returns: + np.array: The converted numpy array. + + """ + if isinstance(x, (Tensor,)): + return x.cpu().detach().numpy() + if isinstance(x, (np.ndarray,)): # type: ignore + return x + if isinstance(x, (Image.Image,)): # type: ignore + return np.array(x) # type: ignore + raise TypeError("Input type not supported") + + def to_pil(self, x: Any) -> "Image.Image": # type: ignore + """Convert input to PIL image. + + Args: + x: The input to convert. + + Returns: + Image.Image: The converted PIL image. + + """ + if isinstance(x, (Tensor,)): + x = x.cpu().detach() * 255 + if x.dim() == 3: + x = x.permute(1, 2, 0) + return Image.fromarray(x.byte().numpy()) # type: ignore + elif x.dim() == 4: + x = x.permute(0, 2, 3, 1) + return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore + else: + raise NotImplementedError + if isinstance(x, (np.ndarray,)): # type: ignore + raise NotImplementedError + if isinstance(x, (Image.Image,)): # type: ignore + return x + raise TypeError("Input type not supported") + + def _detach_tensor_to_cpu( + self, output_image: Union[Tensor, List[Tensor], Tuple[Tensor]] + ) -> Union[Tensor, List[Tensor], Tuple[Tensor]]: + if isinstance(output_image, (Tensor,)): + return output_image.detach().cpu() + if isinstance( + output_image, + ( + list, + tuple, + ), + ): + return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore + raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`") + + def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]: + """Return PIL images. + + Args: + n_row: Number of images displayed in each row of the grid. + backend: visualization backend. Only PIL is supported now. + display: Whether or not to show the image. + + """ + if self._output_image is None: + raise ValueError("No pre-computed images found. Needs to execute first.") + + if len(self._output_image.shape) == 3: + out_image = self._output_image + elif len(self._output_image.shape) == 4: + from kornia.utils.image import make_grid # pylint: disable=C0415 + + if n_row is None: + n_row = math.ceil(self._output_image.shape[0] ** 0.5) + out_image = make_grid(self._output_image, n_row, padding=2) + else: + raise ValueError + + if backend == "pil" and display: + Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore + return None + if backend == "pil": + return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore + raise ValueError(f"Unsupported backend `{backend}`.") + + def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None: + """Save the output image(s) to a directory. + + Args: + name: Directory to save the images. + n_row: Number of images displayed in each row of the grid. + + """ + from kornia.io import write_image # pylint: disable=C0415 + from kornia.utils.image import make_grid # pylint: disable=C0415 + + if name is None: + name = f"Kornia-{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}.jpg" + if len(self._output_image.shape) == 3: + out_image = self._output_image + if len(self._output_image.shape) == 4: + if n_row is None: + n_row = math.ceil(self._output_image.shape[0] ** 0.5) + out_image = make_grid(self._output_image, n_row, padding=2) + write_image(name, out_image.mul(255.0).byte()) diff --git a/python_embeded/Lib/site-packages/kornia/core/mixin/onnx.py b/python_embeded/Lib/site-packages/kornia/core/mixin/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..3885f3c201f506d4554d18e6b86f2ad75259c29e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/mixin/onnx.py @@ -0,0 +1,430 @@ +# 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. +# + +from __future__ import annotations + +import copy +import io +from typing import ( + Any, + ClassVar, + Optional, + Union, +) + +import torch + +import kornia +from kornia.core import Module, Tensor, rand +from kornia.core.external import numpy as np +from kornia.core.external import onnx +from kornia.core.external import onnxruntime as ort + + +class ONNXExportMixin: + """Mixin class that provides ONNX export functionality for objects that support it. + + Attributes: + ONNX_EXPORTABLE: + A flag indicating whether the object can be exported to ONNX. Default is True. + ONNX_DEFAULT_INPUTSHAPE: + Default input shape for the ONNX export. A list of integers where `-1` indicates + dynamic dimensions. Default is [-1, -1, -1, -1]. + ONNX_DEFAULT_OUTPUTSHAPE: + Default output shape for the ONNX export. A list of integers where `-1` indicates + dynamic dimensions. Default is [-1, -1, -1, -1]. + ONNX_EXPORT_PSEUDO_SHAPE: + This is used to create a dummy input tensor for the ONNX export. Default is [1, 3, 256, 256]. + It dimension shall match the ONNX_DEFAULT_INPUTSHAPE and ONNX_DEFAULT_OUTPUTSHAPE. + Non-image dimensions are allowed. + + Note: + - If `ONNX_EXPORTABLE` is False, indicating that the object cannot be exported to ONNX. + + """ + + ONNX_EXPORTABLE: bool = True + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1] + ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[list[int]] = [1, 3, 256, 256] + ADDITIONAL_METADATA: ClassVar[list[tuple[str, str]]] = [] + + def to_onnx( + self, + onnx_name: Optional[str] = None, + input_shape: Optional[list[int]] = None, + output_shape: Optional[list[int]] = None, + pseudo_shape: Optional[list[int]] = None, + model: Optional[Module] = None, + save: bool = True, + additional_metadata: Optional[list[tuple[str, str]]] = None, + **kwargs: Any, + ) -> onnx.ModelProto: # type: ignore + """Export the current object to an ONNX model file. + + Args: + onnx_name: + The name of the output ONNX file. If not provided, a default name in the + format "Kornia-.onnx" will be used. + input_shape: + The input shape for the model as a list of integers. If None, + `ONNX_DEFAULT_INPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`. + output_shape: + The output shape for the model as a list of integers. If None, + `ONNX_DEFAULT_OUTPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`. + pseudo_shape: + The pseudo shape for the model as a list of integers. If None, + `ONNX_EXPORT_PSEUDO_SHAPE` will be used. + model: + The model to export. If not provided, the current object will be used. + save: + If to save the model or load it. + additional_metadata: + Additional metadata to add to the ONNX model. + **kwargs: + Additional keyword arguments to pass to the `torch.onnx.export` function. + + Notes: + - A dummy input tensor is created based on the provided or default input shape. + - Dynamic axes for input and output tensors are configured where dimensions are marked `-1`. + - The model is exported with `torch.onnx.export`, with constant folding enabled and opset version set to 17. + + """ + if not self.ONNX_EXPORTABLE: + raise RuntimeError("This object cannot be exported to ONNX.") + + if input_shape is None: + input_shape = self.ONNX_DEFAULT_INPUTSHAPE + if output_shape is None: + output_shape = self.ONNX_DEFAULT_OUTPUTSHAPE + + if onnx_name is None: + onnx_name = f"Kornia-{self.__class__.__name__}.onnx" + + dummy_input = self._create_dummy_input(input_shape, pseudo_shape) + dynamic_axes = self._create_dynamic_axes(input_shape, output_shape) + + default_args: dict[str, Any] = { + "export_params": True, + "opset_version": 17, + "do_constant_folding": True, + "input_names": ["input"], + "output_names": ["output"], + "dynamic_axes": dynamic_axes, + } + default_args.update(kwargs) + + onnx_buffer = io.BytesIO() + torch.onnx.export( + model or self, # type: ignore[arg-type] + dummy_input, # type: ignore[arg-type] + onnx_buffer, # type: ignore[arg-type] + **default_args, + ) + onnx_buffer.seek(0) + onnx_model = onnx.load(onnx_buffer) # type: ignore + + if additional_metadata is None: + additional_metadata = [] + additional_metadata = copy.deepcopy(additional_metadata) + additional_metadata.extend(self.ADDITIONAL_METADATA) + onnx_model = kornia.onnx.utils.add_metadata(onnx_model, additional_metadata) + if save: + onnx.save(onnx_model, onnx_name) # type: ignore + return onnx_model + + def _create_dummy_input( + self, input_shape: list[int], pseudo_shape: Optional[list[int]] = None + ) -> Union[tuple[Any, ...], Tensor]: + return rand( + *[ + ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim) + for i, dim in enumerate(input_shape) + ] + ) + + def _create_dynamic_axes(self, input_shape: list[int], output_shape: list[int]) -> dict[str, dict[int, str]]: + return { + "input": {i: "dim_" + str(i) for i, dim in enumerate(input_shape) if dim == -1}, + "output": {i: "dim_" + str(i) for i, dim in enumerate(output_shape) if dim == -1}, + } + + +class ONNXRuntimeMixin: + def _create_session( + self, + op: onnx.ModelProto, # type:ignore + providers: Optional[list[str]] = None, + session_options: Optional[ort.InferenceSession] = None, # type:ignore + ) -> ort.InferenceSession: # type:ignore + """Create an optimized ONNXRuntime InferenceSession for the combined model. + + Args: + op: Onnx operation. + providers: + Execution providers for ONNXRuntime (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']). + session_options: + Optional ONNXRuntime session options for session configuration and optimizations. + + Returns: + ort.InferenceSession: The ONNXRuntime session optimized for inference. + + """ + if session_options is None: + sess_options = ort.SessionOptions() # type:ignore + sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED # type:ignore + session = ort.InferenceSession( # type:ignore + op.SerializeToString(), + sess_options=sess_options, + providers=providers or ["CPUExecutionProvider"], + ) + return session + + def set_session(self, session: ort.InferenceSession) -> None: # type: ignore + """Set a custom ONNXRuntime InferenceSession. + + Args: + session: ort.InferenceSession + The custom ONNXRuntime session to be set for inference. + + """ + self._session = session + + def get_session(self) -> ort.InferenceSession: # type: ignore + """Get the current ONNXRuntime InferenceSession. + + Returns: + ort.InferenceSession: The current ONNXRuntime session. + + """ + return self._session + + def as_cpu(self, **kwargs: Any) -> None: + """Set the session to run on CPU.""" + self._session.set_providers(["CPUExecutionProvider"], provider_options=[{**kwargs}]) + + def as_cuda(self, device_id: int = 0, **kwargs: Any) -> None: + """Set the session to run on CUDA. + + We set the ONNX runtime session to use CUDAExecutionProvider. + For other CUDAExecutionProvider configurations, or CUDA/cuDNN/ONNX version issues, + you may refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html. + + Note: + For using CUDA ONNXRuntime, you need to install `onnxruntime-gpu`. + For handling different CUDA version, you may refer to + https://github.com/microsoft/onnxruntime/issues/21769#issuecomment-2295342211. + + Args: + device_id: Select GPU to execute. + kwargs: Additional arguments for cuda. + + """ + self._session.set_providers(["CUDAExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}]) + + def as_tensorrt(self, device_id: int = 0, **kwargs: Any) -> None: + """Set the session to run on TensorRT. + + We set the ONNX runtime session to use TensorrtExecutionProvider. + For other TensorrtExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues, + you may refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html. + + Args: + device_id: select GPU to execute. + kwargs: additional arguments from TensorRT. + + """ + self._session.set_providers( + ["TensorrtExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}] + ) + + def as_openvino(self, device_type: str = "GPU", **kwargs: Any) -> None: + """Set the session to run on OpenVINO. + + We set the ONNX runtime session to use OpenVINOExecutionProvider. + For other OpenVINOExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues, + you may refer to https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html. + + Args: + device_type: CPU, NPU, GPU, GPU.0, GPU.1 based on the available GPUs, NPU, Any valid Hetero combination, + Any valid Multi or Auto devices combination. + kwargs: Additional arguments for OpenVINO. + + """ + self._session.set_providers( + ["OpenVINOExecutionProvider"], provider_options=[{"device_type": device_type, **kwargs}] + ) + + def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]: # type:ignore + """Perform inference using the combined ONNX model. + + Args: + *inputs: Inputs to the ONNX model. The number of inputs must match the expected inputs of the session. + + Returns: + list: The outputs from the ONNX model inference. + + """ + ort_inputs = self._session.get_inputs() + ort_input_values = {ort_inputs[i].name: inputs[i] for i in range(len(ort_inputs))} + outputs = self._session.run(None, ort_input_values) + + return outputs + + +class ONNXMixin: + def _load_op( + self, + arg: Union[onnx.ModelProto, str], # type:ignore + cache_dir: Optional[str] = None, + ) -> onnx.ModelProto: # type:ignore + """Load an ONNX model, either from a file path or use the provided ONNX ModelProto. + + Args: + arg: Either an ONNX ModelProto object or a file path to an ONNX model. + cache_dir: Where to read onnx objects from if stored on disk. + + Returns: + onnx.ModelProto: The loaded ONNX model. + + """ + if isinstance(arg, str): + return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir) + if isinstance(arg, onnx.ModelProto): # type:ignore + return arg + raise ValueError(f"Invalid argument type. Got {type(arg)}") + + def _load_ops( + self, + *args: Union[onnx.ModelProto, str], # type:ignore + cache_dir: Optional[str] = None, + ) -> list[onnx.ModelProto]: # type:ignore + """Load multiple ONNX models or operators and returns them as a list. + + Args: + *args: A variable number of ONNX models (either ONNX ModelProto objects or file paths). + For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on + https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model. + cache_dir: Where to read operations from if stored on disk. + + Returns: + list[onnx.ModelProto]: The loaded ONNX models as a list of ONNX graphs. + + """ + op_list = [] + for arg in args: + op_list.append(self._load_op(arg, cache_dir=cache_dir)) + return op_list + + def _combine( + self, + *args: list[onnx.ModelProto], # type:ignore + io_maps: Optional[list[tuple[str, str]]] = None, + ) -> onnx.ModelProto: # type:ignore + """Combine the provided ONNX models into a single ONNX graph. + + Optionally, map inputs and outputs between operators using the `io_map`. + + Args: + args: list of onnx operations. + io_maps: + A list of list of tuples representing input-output mappings for combining the models. + Example: [[(model1_output_name, model2_input_name)], [(model2_output_name, model3_input_name)]]. + + Returns: + onnx.ModelProto: The combined ONNX model as a single ONNX graph. + + """ + if len(args) == 0: + raise ValueError("No operators found.") + + combined_op = args[0] + combined_op = onnx.compose.add_prefix(combined_op, prefix=f"K{str(0).zfill(2)}-") # type:ignore + + for i, op in enumerate(args[1:]): + next_op = onnx.compose.add_prefix(op, prefix=f"K{str(i + 1).zfill(2)}-") # type:ignore + if io_maps is None: + io_map = [(f"K{str(i).zfill(2)}-output", f"K{str(i + 1).zfill(2)}-input")] + else: + io_map = [(f"K{str(i).zfill(2)}-{it[0]}", f"K{str(i + 1).zfill(2)}-{it[1]}") for it in io_maps[i]] + combined_op = onnx.compose.merge_models(combined_op, next_op, io_map=io_map) # type:ignore + + return combined_op + + def _export( + self, + op: onnx.ModelProto, # type:ignore + file_path: str, + **kwargs: Any, + ) -> None: + """Export the combined ONNX model to a file. + + Args: + op: onnx operation. + file_path: + The file path to export the combined ONNX model. + kwargs: Additional arguments to save onnx model. + + """ + onnx.save(op, file_path, **kwargs) # type:ignore + + def _add_metadata( + self, + op: onnx.ModelProto, # type:ignore + additional_metadata: Optional[list[tuple[str, str]]] = None, + ) -> onnx.ModelProto: # type:ignore + """Add metadata to the combined ONNX model. + + Args: + op: onnx operation. + additional_metadata: + A list of tuples representing additional metadata to add to the combined ONNX model. + Example: [("version", 0.1)], [("date", 20240909)]. + + """ + op = kornia.onnx.utils.add_metadata(op, additional_metadata) + return op + + def _onnx_version_conversion( + self, + op: onnx.ModelProto, # type:ignore + target_ir_version: Optional[int] = None, + target_opset_version: Optional[int] = None, + ) -> onnx.ModelProto: # type:ignore + """Automatic conversion of the model's IR/OPSET version to the given target version. + + Args: + op: onnx operation. + target_ir_version: The target IR version to convert to. + target_opset_version: The target OPSET version to convert to. + + """ + if op.ir_version != target_ir_version or op.opset_import[0].version != target_opset_version: + # Check if all ops are supported in the current IR version + model_bytes = io.BytesIO() + onnx.save_model(op, model_bytes) # type:ignore + loaded_model = onnx.load_model_from_string(model_bytes.getvalue()) # type:ignore + if target_opset_version is not None: + loaded_model = onnx.version_converter.convert_version( # type:ignore + loaded_model, target_opset_version + ) + onnx.checker.check_model(loaded_model) # type:ignore + # Set the IR version if it passed the checking + if target_ir_version is not None: + loaded_model.ir_version = target_ir_version + op = loaded_model + return op diff --git a/python_embeded/Lib/site-packages/kornia/core/module.py b/python_embeded/Lib/site-packages/kornia/core/module.py new file mode 100644 index 0000000000000000000000000000000000000000..88cd57077cb39f1e55da9633d56087d9b2a8ac79 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/module.py @@ -0,0 +1,377 @@ +# 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. +# + +from __future__ import annotations + +import datetime +import math +import os +from functools import wraps +from typing import Any, Callable, Optional, Union + +# TODO: not use top level import +import kornia + +from ._backend import Module, Sequential, Tensor, from_numpy +from .external import PILImage as Image +from .external import numpy as np +from .mixin.onnx import ONNXExportMixin + + +class ImageModuleMixIn: + """A MixIn that handles image-based operations. + + This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features. + Note that this MixIn fits the classes that return one image tensor only. + """ + + _output_image: Any + + def convert_input_output( + self, + input_names_to_handle: Optional[list[Any]] = None, + output_type: str = "tensor", + ) -> Callable[[Any], Any]: + """Convert input and output types for a function. + + Args: + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + + Returns: + Callable: Decorated function with converted input and output types. + + """ + + def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Union[Any, list[Any]]: + # If input_names_to_handle is None, handle all inputs + if input_names_to_handle is None: + # Convert all args to tensors + args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args) + # Convert all kwargs to tensors + kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()} + else: + # Convert specified args to tensors + args = list(args) # type:ignore + for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)): + if name in input_names_to_handle: + args[i] = self.to_tensor(arg) # type:ignore + # Convert specified kwargs to tensors + for name, value in kwargs.items(): + if name in input_names_to_handle: + kwargs[name] = self.to_tensor(value) + + # Call the actual forward method + tensor_outputs = func(*args, **kwargs) + + if not isinstance(tensor_outputs, (tuple,)): + tensor_outputs = (tensor_outputs,) + + # Convert outputs to the desired type + outputs = [] + for output in tensor_outputs: + if output_type == "tensor": + outputs.append(output) + elif output_type == "numpy": + outputs.append(self.to_numpy(output)) + elif output_type == "pil": + outputs.append(self.to_pil(output)) + else: + raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.") + + return outputs if len(outputs) > 1 else outputs[0] + + return wrapper + + return decorator + + def _is_valid_arg(self, arg: Any) -> bool: + """Check if the argument is a valid type for conversion. + + Args: + arg: The argument to check. + + Returns: + bool: True if valid, False otherwise. + + """ + if isinstance(arg, (str,)) and os.path.exists(arg): + return True + if isinstance(arg, (Tensor,)): + return True + # Make sure that the numpy and PIL are not necessarily needed to be imported. + if isinstance(arg, (np.ndarray,)): # type: ignore + return True + if isinstance(arg, (Image.Image)): # type: ignore + return True + return False + + def to_tensor(self, x: Any) -> Tensor: + """Convert input to tensor. + + Supports image path, numpy array, PIL image, and raw tensor. + + Args: + x: The input to convert. + + Returns: + Tensor: The converted tensor. + + """ + if isinstance(x, (str,)): + return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255 + if isinstance(x, (Tensor,)): + return x + if isinstance(x, (np.ndarray,)): # type: ignore + return kornia.utils.image.image_to_tensor(x) / 255 + if isinstance(x, (Image.Image,)): # type: ignore + return from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore + raise TypeError("Input type not supported") + + def to_numpy(self, x: Any) -> np.array: # type: ignore + """Convert input to numpy array. + + Args: + x: The input to convert. + + Returns: + np.array: The converted numpy array. + + """ + if isinstance(x, (Tensor,)): + return x.cpu().detach().numpy() + if isinstance(x, (np.ndarray,)): # type: ignore + return x + if isinstance(x, (Image.Image,)): # type: ignore + return np.array(x) # type: ignore + raise TypeError("Input type not supported") + + def to_pil(self, x: Any) -> Image.Image: # type: ignore + """Convert input to PIL image. + + Args: + x: The input to convert. + + Returns: + Image.Image: The converted PIL image. + + """ + if isinstance(x, (Tensor,)): + x = x.cpu().detach() * 255 + if x.dim() == 3: + x = x.permute(1, 2, 0) + return Image.fromarray(x.byte().numpy()) # type: ignore + elif x.dim() == 4: + x = x.permute(0, 2, 3, 1) + return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore + else: + raise NotImplementedError + if isinstance(x, (np.ndarray,)): # type: ignore + raise NotImplementedError + if isinstance(x, (Image.Image,)): # type: ignore + return x + raise TypeError("Input type not supported") + + def _detach_tensor_to_cpu( + self, output_image: Union[Tensor, list[Tensor], tuple[Tensor]] + ) -> Union[Tensor, list[Tensor], tuple[Tensor]]: + """Detach the input tensor (or list/tuple of tensors) from the GPU and move it to the CPU. + + Args: + output_image (Union[Tensor, list[Tensor], tuple[Tensor]]): The input tensor(s) to be moved. + + Returns: + Union[Tensor, list[Tensor], tuple[Tensor]]: The tensor(s) moved to the CPU and detached from + the computational graph. + """ + if isinstance(output_image, (Tensor,)): + return output_image.detach().cpu() + if isinstance( + output_image, + ( + list, + tuple, + ), + ): + return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore + raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`") + + def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]: + """Return PIL images. + + Args: + n_row: Number of images displayed in each row of the grid. + backend: visualization backend. Only PIL is supported now. + display: whether to display the image. + + """ + if self._output_image is None: + raise ValueError("No pre-computed images found. Needs to execute first.") + + if len(self._output_image.shape) == 3: + out_image = self._output_image + elif len(self._output_image.shape) == 4: + if n_row is None: + n_row = math.ceil(self._output_image.shape[0] ** 0.5) + out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2) + else: + raise ValueError + + if backend == "pil" and display: + Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore + return None + if backend == "pil": + return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore + raise ValueError(f"Unsupported backend `{backend}`.") + + def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None: + """Save the output image(s) to a directory. + + Args: + name: Directory to save the images. + n_row: Number of images displayed in each row of the grid. + + """ + if name is None: + name = f"Kornia-{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}.jpg" + if len(self._output_image.shape) == 3: + out_image = self._output_image + if len(self._output_image.shape) == 4: + if n_row is None: + n_row = math.ceil(self._output_image.shape[0] ** 0.5) + out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2) + kornia.io.write_image(name, out_image.mul(255.0).byte()) + + +class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin): + """Handles image-based operations. + + This modules accepts multiple input and output data types, provides end-to-end + visualization, file saving features. Note that this module fits the classes that + return one image tensor only. + + Note: + The additional add-on features increase the use of memories. To restore the + original behaviour, you may set `disable_features = True`. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._disable_features: bool = False + + @property + def disable_features(self) -> bool: + return self._disable_features + + @disable_features.setter + def disable_features(self, value: bool = True) -> None: + self._disable_features = value + + def __call__( + self, + *inputs: Any, + input_names_to_handle: Optional[list[Any]] = None, + output_type: str = "tensor", + **kwargs: Any, + ) -> Any: + """Overwrite the __call__ function to handle various inputs. + + Args: + inputs: Inputs to operate on. + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + kwargs: Additional arguments. + + Returns: + Callable: Decorated function with converted input and output types. + + """ + # Wrap the forward method with the decorator + if not self._disable_features: + decorated_forward = self.convert_input_output( + input_names_to_handle=input_names_to_handle, output_type=output_type + )(super().__call__) + _output_image = decorated_forward(*inputs, **kwargs) + if output_type == "tensor": + self._output_image = self._detach_tensor_to_cpu(_output_image) + else: + self._output_image = _output_image + else: + _output_image = super().__call__(*inputs, **kwargs) + return _output_image + + +class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin): + """Handles image-based operations as a sequential module. + + This modules accepts multiple input and output data types, provides end-to-end + visualization, file saving features. Note that this module fits the classes that + return one image tensor only. + + Note: + The additional add-on features increase the use of memories. To restore the + original behaviour, you may set `disable_features = True`. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._disable_features: bool = False + + @property + def disable_features(self) -> bool: + return self._disable_features + + @disable_features.setter + def disable_features(self, value: bool = True) -> None: + self._disable_features = value + + def __call__( + self, + *inputs: Any, + input_names_to_handle: Optional[list[Any]] = None, + output_type: str = "tensor", + **kwargs: Any, + ) -> Any: + """Overwrite the __call__ function to handle various inputs. + + Args: + inputs: Inputs to operate on. + input_names_to_handle: List of input names to convert, if None, handle all inputs. + output_type: Desired output type ('tensor', 'numpy', or 'pil'). + kwargs: Additional arguments. + + Returns: + Callable: Decorated function with converted input and output types. + + """ + # Wrap the forward method with the decorator + if not self._disable_features: + decorated_forward = self.convert_input_output( + input_names_to_handle=input_names_to_handle, output_type=output_type + )(super().__call__) + _output_image = decorated_forward(*inputs, **kwargs) + if output_type == "tensor": + self._output_image = self._detach_tensor_to_cpu(_output_image) + else: + self._output_image = _output_image + else: + _output_image = super().__call__(*inputs, **kwargs) + return _output_image diff --git a/python_embeded/Lib/site-packages/kornia/core/tensor_wrapper.py b/python_embeded/Lib/site-packages/kornia/core/tensor_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0e50a15d80f5cbca199d2d74cb8980958488c1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/core/tensor_wrapper.py @@ -0,0 +1,177 @@ +# 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. +# + +# type: ignore +# pytorch tensor wrapper class +# insipired by: +# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748 +import collections + +import torch +from torch import Tensor + + +# TODO: promote to KORNIA_WRAP +def wrap(v, cls): + """Wrap type.""" + # wrap inputs if necessary + if type(v) in {tuple, list}: + return type(v)(wrap(vi, cls) for vi in v) + + return cls(v) if isinstance(v, Tensor) else v + + +# TODO: promote to KORNIA_UNWRAP +def unwrap(v): + """Unwrap nested type.""" + if type(v) in {tuple, list}: + return type(v)(unwrap(vi) for vi in v) + + return v._data if isinstance(v, TensorWrapper) else v + + +class TensorWrapper: + def __init__(self, data: Tensor) -> None: + self.__dict__["_data"] = data + self.__dict__["used_attrs"] = set() + self.__dict__["used_calls"] = set() + + def unwrap(self): + return unwrap(self) + + def __getstate__(self): + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __repr__(self) -> str: + return f"{self._data}" + + def __getattr__(self, name): + if name == "data": + return self._data + elif name in self.__dict__: + return self.__dict__[name] + self.used_attrs.add(name) + + val = getattr(self._data, name) + + # NOTE: not clear is really needed + # If it's a method + # if callable(val): + # c = getattr(type(self._data), name) + # # Don't append self to args if classmethod/staticmethod + # if c is val: + # return lambda *a, **kw: wrap(self.__torch_function__(c, (type(self),), args=a, kwargs=kw), type(self)) + # # Otherwise append self to args + # return lambda *a, **kw: wrap( + # #self.__torch_function__(c, (type(self),), args=(self,) + a, kwargs=kw), type(self) + # ) + + return wrap(val, type(self)) + + def __setattr__(self, name, value) -> None: + if name in self.__dict__: + self.__dict__[name] = value + + self.used_attrs.add(name) + setattr(self._data, name, value) + + def __setitem__(self, key, value) -> None: + self._data[key] = value + + def __getitem__(self, key): + return wrap(self._data[key], type(self)) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + # Find an instance of this class in the arguments + args_of_this_cls = [] + for a in args: + if isinstance(a, cls): + args_of_this_cls.append(a) + elif isinstance(a, collections.abc.Sequence): + args_of_this_cls.extend(el for el in a if isinstance(el, cls)) + # assert len(args_of_this_cls) > 0 + for a in args_of_this_cls: + a.used_calls.add(func) + args = unwrap(tuple(args)) + kwargs = {k: unwrap(v) for k, v in kwargs.items()} + + return wrap(func(*args, **kwargs), cls) + + # TODO: `def __add__(self, other) -> Self:` when mypy release >0.991 + def __add__(self, other): + return self.__unary_op__(torch.add, other) + + def __radd__(self, other): + return self.__unary_op__(torch.add, other) + + def __mul__(self, other): + return self.__unary_op__(torch.mul, other) + + def __rmul__(self, other): + return self.__unary_op__(torch.mul, other) + + def __sub__(self, other): + return self.__unary_op__(torch.sub, other) + + def __rsub__(self, other): + return self.__unary_op__(torch.sub, other) + + def __truediv__(self, other): + return self.__unary_op__(torch.true_divide, other) + + def __floordiv__(self, other): + return self.__unary_op__(torch.floor_divide, other) + + def __ge__(self, other): + return self.__unary_op__(torch.ge, other) + + def __gt__(self, other): + return self.__unary_op__(torch.gt, other) + + def __lt__(self, other): + return self.__unary_op__(torch.lt, other) + + def __le__(self, other): + return self.__unary_op__(torch.le, other) + + def __eq__(self, other): + return self.__unary_op__(torch.eq, other) + + def __ne__(self, other): + return self.__unary_op__(torch.ne, other) + + def __bool__(self) -> bool: + return self.__unary_op__(Tensor.__bool__) + + def __int__(self) -> int: + return self.__unary_op__(Tensor.__int__) + + def __neg__(self): + return self.__unary_op__(Tensor.negative) + + def __unary_op__(self, func, other=None): + args = (self, other) if other is not None else (self,) + return self.__torch_function__(func, (type(self),), args) + + def __len__(self) -> int: + return len(self._data) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/__init__.py b/python_embeded/Lib/site-packages/kornia/enhance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0729a6b5bc605f2d9db430cdc7dbad23707a7373 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/__init__.py @@ -0,0 +1,113 @@ +# 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. +# + +from .adjust import ( + AdjustBrightness, + AdjustBrightnessAccumulative, + AdjustContrast, + AdjustContrastWithMeanSubtraction, + AdjustGamma, + AdjustHue, + AdjustLog, + AdjustSaturation, + AdjustSaturationWithGraySubtraction, + AdjustSigmoid, + Invert, + adjust_brightness, + adjust_brightness_accumulative, + adjust_contrast, + adjust_contrast_with_mean_subtraction, + adjust_gamma, + adjust_hue, + adjust_hue_raw, + adjust_log, + adjust_saturation, + adjust_saturation_raw, + adjust_saturation_with_gray_subtraction, + adjust_sigmoid, + equalize, + equalize3d, + invert, + posterize, + sharpness, + solarize, +) +from .core import AddWeighted, add_weighted +from .equalization import equalize_clahe +from .histogram import histogram, histogram2d, image_histogram2d +from .integral import IntegralImage, IntegralTensor, integral_image, integral_tensor +from .jpeg import JPEGCodecDifferentiable, jpeg_codec_differentiable +from .normalize import Denormalize, Normalize, denormalize, normalize, normalize_min_max +from .rescale import Rescale +from .shift_rgb import shift_rgb +from .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten + +__all__ = [ + "AddWeighted", + "AdjustBrightness", + "AdjustBrightnessAccumulative", + "AdjustContrast", + "AdjustContrastWithMeanSubtraction", + "AdjustGamma", + "AdjustHue", + "AdjustLog", + "AdjustSaturation", + "AdjustSaturationWithGraySubtraction", + "AdjustSigmoid", + "Denormalize", + "IntegralImage", + "IntegralTensor", + "Invert", + "JPEGCodecDifferentiable", + "JPEGCodecDifferentiable", + "Normalize", + "Rescale", + "ZCAWhitening", + "add_weighted", + "adjust_brightness", + "adjust_brightness_accumulative", + "adjust_contrast", + "adjust_contrast_with_mean_subtraction", + "adjust_gamma", + "adjust_hue", + "adjust_hue_raw", + "adjust_log", + "adjust_saturation", + "adjust_saturation_raw", + "adjust_saturation_with_gray_subtraction", + "adjust_sigmoid", + "denormalize", + "equalize", + "equalize3d", + "equalize_clahe", + "histogram", + "histogram2d", + "image_histogram2d", + "integral_image", + "integral_tensor", + "invert", + "jpeg_codec_differentiable", + "linear_transform", + "normalize", + "normalize_min_max", + "posterize", + "sharpness", + "shift_rgb", + "solarize", + "zca_mean", + "zca_whiten", +] diff --git a/python_embeded/Lib/site-packages/kornia/enhance/adjust.py b/python_embeded/Lib/site-packages/kornia/enhance/adjust.py new file mode 100644 index 0000000000000000000000000000000000000000..93a533a380a9d66a9c002a6f281b69681bf6b69b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/adjust.py @@ -0,0 +1,1492 @@ +# 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. +# + +from __future__ import annotations + +from math import pi +from typing import ClassVar, Optional, Union + +import torch + +from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv +from kornia.core import ImageModule as Module +from kornia.core import Parameter, Tensor, tensor +from kornia.core.check import ( + KORNIA_CHECK, + KORNIA_CHECK_IS_COLOR_OR_GRAY, + KORNIA_CHECK_IS_TENSOR, +) +from kornia.utils.helpers import _torch_histc_cast +from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video + + +def adjust_saturation_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust color saturation of an image. + + Expecting image to be in hsv format already. + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + # unpack the hsv values + h, s, v = torch.chunk(image, chunks=3, dim=-3) + + # transform the hue value and appl module + s_out: Tensor = torch.clamp(s * factor, min=0, max=1) + + # pack back back the corrected hue + out: Tensor = torch.cat([h, s_out, v], dim=-3) + + return out + + +def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust color saturation of an image by blending the image with its grayscaled version. + + The image is expected to be an RGB image or a gray image in the range of [0, 1]. + If it is an RGB image, returns blending of the image with its grayscaled version. + If it is a gray image, returns the image. + + .. note:: + this is just a convenience function to have compatibility with Pil + + Args: + image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`. + factor: How much to adjust the saturation. 0 will give a black + and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. + + Return: + Adjusted image in the shape of :math:`(*, 3, H, W)`. + + Example: + >>> x = torch.ones(1, 3, 3, 3) + >>> adjust_saturation_with_gray_subtraction(x, 2.).shape + torch.Size([1, 3, 3, 3]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.tensor([1., 2.]) + >>> adjust_saturation_with_gray_subtraction(x, y).shape + torch.Size([2, 3, 3, 3]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + KORNIA_CHECK_IS_COLOR_OR_GRAY(image, "Image should be an RGB or gray image") + + if image.shape[-3] == 1: + return image + + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + x_other: Tensor = rgb_to_grayscale(image) + + # blend the image with the grayscaled image + x_adjusted: Tensor = (1 - factor) * x_other + factor * image + + # clamp the output + out: Tensor = torch.clamp(x_adjusted, 0.0, 1.0) + + return out + + +def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust color saturation of an image. + + .. image:: _static/img/adjust_saturation.png + + The image is expected to be an RGB image in the range of [0, 1]. + + Args: + image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`. + factor: How much to adjust the saturation. 0 will give a black + and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. + saturation_mode: The mode to adjust saturation. + + Return: + Adjusted image in the shape of :math:`(*, 3, H, W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> x = torch.ones(1, 3, 3, 3) + >>> adjust_saturation(x, 2.).shape + torch.Size([1, 3, 3, 3]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.tensor([1., 2.]) + >>> adjust_saturation(x, y).shape + torch.Size([2, 3, 3, 3]) + + """ + # convert the rgb image to hsv + x_hsv: Tensor = rgb_to_hsv(image) + + # perform the conversion + x_adjusted: Tensor = adjust_saturation_raw(x_hsv, factor) + + # convert back to rgb + out: Tensor = hsv_to_rgb(x_adjusted) + + return out + + +def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust hue of an image. + + Expecting image to be in hsv format already. + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK( + isinstance(factor, (float, Tensor)), + f"The factor should be a float number or Tensor in the range between [-PI, PI]. Got {type(factor)}", + ) + + if isinstance(factor, float): + factor = torch.as_tensor(factor) + + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + # unpack the hsv values + h, s, v = torch.chunk(image, chunks=3, dim=-3) + + # transform the hue value and appl module + divisor: float = 2 * pi + h_out: Tensor = torch.fmod(h + factor, divisor) + + # pack back back the corrected hue + out: Tensor = torch.cat([h_out, s, v], dim=-3) + + return out + + +def adjust_hue(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust hue of an image. + + .. image:: _static/img/adjust_hue.png + + The image is expected to be an RGB image in the range of [0, 1]. + + Args: + image: Image to be adjusted in the shape of :math:`(*, 3, H, W)`. + factor: How much to shift the hue channel. Should be in [-PI, PI]. PI + and -PI give complete reversal of hue channel in HSV space in positive and negative + direction respectively. 0 means no shift. Therefore, both -PI and PI will give an + image with complementary colors while 0 gives the original image. + + Return: + Adjusted image in the shape of :math:`(*, 3, H, W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> x = torch.ones(1, 3, 2, 2) + >>> adjust_hue(x, 3.141516).shape + torch.Size([1, 3, 2, 2]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.ones(2) * 3.141516 + >>> adjust_hue(x, y).shape + torch.Size([2, 3, 3, 3]) + + """ + # convert the rgb image to hsv + x_hsv: Tensor = rgb_to_hsv(image) + + # perform the conversion + x_adjusted: Tensor = adjust_hue_raw(x_hsv, factor) + + # convert back to rgb + out: Tensor = hsv_to_rgb(x_adjusted) + + return out + + +def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float, Tensor] = 1.0) -> Tensor: + r"""Perform gamma correction on an image. + + .. image:: _static/img/adjust_contrast.png + + The input image is expected to be in the range of [0, 1]. + + Args: + input: Image to be adjusted in the shape of :math:`(*, H, W)`. + gamma: Non negative real number, same as y\gammay in the equation. + gamma larger than 1 make the shadows darker, while gamma smaller than 1 make + dark regions lighter. + gain: The constant multiplier. + + Return: + Adjusted image in the shape of :math:`(*, H, W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_gamma(x, 1.0, 2.0) + tensor([[[[1., 1.], + [1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y1 = torch.ones(2) * 1.0 + >>> y2 = torch.ones(2) * 2.0 + >>> adjust_gamma(x, y1, y2).shape + torch.Size([2, 5, 3, 3]) + + """ + if not isinstance(input, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if not isinstance(gamma, (float, Tensor)): + raise TypeError(f"The gamma should be a positive float or Tensor. Got {type(gamma)}") + + if not isinstance(gain, (float, Tensor)): + raise TypeError(f"The gain should be a positive float or Tensor. Got {type(gain)}") + + if isinstance(gamma, float): + gamma = Tensor([gamma]) + + if isinstance(gain, float): + gain = Tensor([gain]) + + gamma = gamma.to(input.device).to(input.dtype) + gain = gain.to(input.device).to(input.dtype) + + if (gamma < 0.0).any(): + raise ValueError(f"Gamma must be non-negative. Got {gamma}") + + if (gain < 0.0).any(): + raise ValueError(f"Gain must be non-negative. Got {gain}") + + for _ in range(len(input.shape) - len(gamma.shape)): + gamma = torch.unsqueeze(gamma, dim=-1) + + for _ in range(len(input.shape) - len(gain.shape)): + gain = torch.unsqueeze(gain, dim=-1) + + # Apply the gamma correction + x_adjust: Tensor = gain * torch.pow(input, gamma) + + # Truncate between pixel values + out: Tensor = torch.clamp(x_adjust, 0.0, 1.0) + + return out + + +def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor: + r"""Adjust the contrast of an image tensor. + + .. image:: _static/img/adjust_contrast.png + + This implementation follows Szeliski's book convention, where contrast is defined as + a `multiplicative` operation directly to raw pixel values. Beware that other frameworks + might use different conventions which can be difficult to reproduce exact results. + + The input image and factor is expected to be in the range of [0, 1]. + + .. tip:: + This is not the preferred way to adjust the contrast of an image. Ideally one must + implement :func:`kornia.enhance.adjust_gamma`. More details in the following link: + https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_log_gamma.html#sphx-glr-auto-examples-color-exposure-plot-log-gamma-py + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + factor: Contrast adjust factor per element + in the batch. 0 generates a completely black image, 1 does not modify + the input image while any other non-negative number modify the + brightness by this factor. + clip_output: whether to clip the output image with range of [0, 1]. + + Return: + Adjusted image in the shape of :math:`(*, H, W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> import torch + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_contrast(x, 0.5) + tensor([[[[0.5000, 0.5000], + [0.5000, 0.5000]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.tensor([0.65, 0.50]) + >>> adjust_contrast(x, y).shape + torch.Size([2, 5, 3, 3]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + KORNIA_CHECK(any(factor >= 0), "Contrast factor must be positive.") + + # Apply contrast factor to each channel + img_adjust: Tensor = image * factor + + # Truncate between pixel values + if clip_output: + img_adjust = img_adjust.clamp(min=0.0, max=1.0) + + return img_adjust + + +def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Adjust the contrast of an image tensor by subtracting the mean over channels. + + .. note:: + this is just a convenience function to have compatibility with Pil. For exact + definition of image contrast adjustment consider using :func:`kornia.enhance.adjust_gamma`. + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + factor: Contrast adjust factor per element + in the batch. 0 generates a completely black image, 1 does not modify + the input image while any other non-negative number modify the + brightness by this factor. + + Return: + Adjusted image in the shape of :math:`(*, H, W)`. + + Example: + >>> import torch + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_contrast_with_mean_subtraction(x, 0.5) + tensor([[[[1., 1.], + [1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.tensor([0.65, 0.50]) + >>> adjust_contrast_with_mean_subtraction(x, y).shape + torch.Size([2, 5, 3, 3]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + # KORNIA_CHECK(any(factor >= 0), "Contrast factor must be positive.") + + if image.shape[-3] == 3: + img_mean = rgb_to_grayscale(image).mean((-2, -1), True) + else: + img_mean = image.mean() + + # Apply contrast factor subtracting the mean + img_adjust: Tensor = image * factor + img_mean * (1 - factor) + + img_adjust = img_adjust.clamp(min=0.0, max=1.0) + + return img_adjust + + +def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor: + r"""Adjust the brightness of an image tensor. + + .. image:: _static/img/adjust_brightness.png + + This implementation follows Szeliski's book convention, where brightness is defined as + an `additive` operation directly to raw pixel and shift its values according the applied + factor and range of the image values. Beware that other framework might use different + conventions which can be difficult to reproduce exact results. + + The input image and factor is expected to be in the range of [0, 1]. + + .. tip:: + By applying a large factor might prouce clipping or loss of image detail. We recommenda to + apply small factors to avoid the mentioned issues. Ideally one must implement the adjustment + of image intensity with other techniques suchs as :func:`kornia.enhance.adjust_gamma`. More + details in the following link: + https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_log_gamma.html#sphx-glr-auto-examples-color-exposure-plot-log-gamma-py + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + factor: Brightness adjust factor per element in the batch. It's recommended to + bound the factor by [0, 1]. 0 does not modify the input image while any other + number modify the brightness. + clip_output: Whether to clip output to be in [0,1]. + + Return: + Adjusted tensor in the shape of :math:`(*, H, W)`. + + .. note:: + See a working example `here `__. + + Example: + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_brightness(x, 1.) + tensor([[[[1., 1.], + [1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.tensor([0.25, 0.50]) + >>> adjust_brightness(x, y).shape + torch.Size([2, 5, 3, 3]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + + # convert factor to a tensor + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + # shift pixel values + img_adjust: Tensor = image + factor + + # truncate between pixel values + if clip_output: + img_adjust = img_adjust.clamp(min=0.0, max=1.0) + + return img_adjust + + +def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor: + r"""Adjust the brightness accumulatively of an image tensor. + + This implementation follows PIL convention. + + The input image and factor is expected to be in the range of [0, 1]. + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + factor: Brightness adjust factor per element in the batch. It's recommended to + bound the factor by [0, 1]. 0 does not modify the input image while any other + number modify the brightness. + clip_output: Whether to clip output to be in [0,1]. + + Return: + Adjusted tensor in the shape of :math:`(*, H, W)`. + + Example: + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_brightness_accumulative(x, 1.) + tensor([[[[1., 1.], + [1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.tensor([0.25, 0.50]) + >>> adjust_brightness_accumulative(x, y).shape + torch.Size([2, 5, 3, 3]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.") + + # convert factor to a tensor + if isinstance(factor, float): + # TODO: figure out how to create later a tensor without importing torch + factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype) + elif isinstance(factor, Tensor): + factor = factor.to(image.device, image.dtype) + + # make factor broadcastable + while len(factor.shape) != len(image.shape): + factor = factor[..., None] + + # shift pixel values + img_adjust: Tensor = image * factor + + # truncate between pixel values + if clip_output: + img_adjust = img_adjust.clamp(min=0.0, max=1.0) + + return img_adjust + + +def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> Tensor: + """Adjust sigmoid correction on the input image tensor. + + The input image is expected to be in the range of [0, 1]. + + Reference: + [1]: Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions", + http://markfairchild.org/PDFs/PAP07.pdf + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + cutoff: The cutoff of sigmoid function. + gain: The multiplier of sigmoid function. + inv: If is set to True the function will return the inverse sigmoid correction. + + Returns: + Adjusted tensor in the shape of :math:`(*, H, W)`. + + Example: + >>> x = torch.ones(1, 1, 2, 2) + >>> adjust_sigmoid(x, gain=0) + tensor([[[[0.5000, 0.5000], + [0.5000, 0.5000]]]]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + + if inv: + img_adjust = 1 - 1 / (1 + (gain * (cutoff - image)).exp()) + else: + img_adjust = 1 / (1 + (gain * (cutoff - image)).exp()) + return img_adjust + + +def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: bool = True) -> Tensor: + """Adjust log correction on the input image tensor. + + The input image is expected to be in the range of [0, 1]. + + Reference: + [1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + gain: The multiplier of logarithmic function. + inv: If is set to True the function will return the inverse logarithmic correction. + clip_output: Whether to clip the output image with range of [0, 1]. + + Returns: + Adjusted tensor in the shape of :math:`(*, H, W)`. + + Example: + >>> x = torch.zeros(1, 1, 2, 2) + >>> adjust_log(x, inv=True) + tensor([[[[0., 0.], + [0., 0.]]]]) + + """ + KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)") + + if inv: + img_adjust = (2**image - 1) * gain + else: + img_adjust = (1 + image).log2() * gain + + # truncate between pixel values + if clip_output: + img_adjust = img_adjust.clamp(min=0.0, max=1.0) + + return img_adjust + + +def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor: + r"""For each pixel in the image, select the pixel if the value is less than the threshold. + + Otherwise, subtract 1.0 from the pixel. + + Args: + input: image or batched images to solarize. + thresholds: solarize thresholds. + If int or one element tensor, input will be solarized across the whole batch. + If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input). + + Returns: + Solarized images. + + """ + if not isinstance(input, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if not isinstance(thresholds, (float, Tensor)): + raise TypeError(f"The factor should be either a float or Tensor. Got {type(thresholds)}") + + if isinstance(thresholds, Tensor) and len(thresholds.shape) != 0: + if not (input.size(0) == len(thresholds) and len(thresholds.shape) == 1): + raise AssertionError(f"thresholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}") + # TODO: I am not happy about this line, but no easy to do batch-wise operation + thresholds = thresholds.to(input.device).to(input.dtype) + thresholds = torch.stack([x.expand(*input.shape[-3:]) for x in thresholds]) + + return torch.where(input < thresholds, input, 1.0 - input) + + +def solarize( + input: Tensor, + thresholds: Union[float, Tensor] = 0.5, + additions: Optional[Union[float, Tensor]] = None, +) -> Tensor: + r"""For each pixel in the image less than threshold. + + .. image:: _static/img/solarize.png + + We add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0. + The value of 'addition' is between -0.5 and 0.5. + + Args: + input: image tensor with shapes like :math:`(*, C, H, W)` to solarize. + thresholds: solarize thresholds. + If int or one element tensor, input will be solarized across the whole batch. + If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input). + additions: between -0.5 and 0.5. + If None, no addition will be performed. + If int or one element tensor, same addition will be added across the whole batch. + If 1-d tensor, additions will be added element-wisely, len(additions) == len(input). + + Returns: + The solarized images with shape :math:`(*, C, H, W)`. + + Example: + >>> x = torch.rand(1, 4, 3, 3) + >>> out = solarize(x, thresholds=0.5, additions=0.) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + >>> x = torch.rand(2, 4, 3, 3) + >>> thresholds = torch.tensor([0.8, 0.5]) + >>> additions = torch.tensor([-0.25, 0.25]) + >>> solarize(x, thresholds, additions).shape + torch.Size([2, 4, 3, 3]) + + """ + if not isinstance(input, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if not isinstance(thresholds, (float, Tensor)): + raise TypeError(f"The factor should be either a float or Tensor. Got {type(thresholds)}") + + if isinstance(thresholds, float): + thresholds = torch.as_tensor(thresholds) + + if additions is not None: + if not isinstance(additions, (float, Tensor)): + raise TypeError(f"The factor should be either a float or Tensor. Got {type(additions)}") + + if isinstance(additions, float): + additions = torch.as_tensor(additions) + + if not torch.all((additions < 0.5) * (additions > -0.5)): + raise AssertionError(f"The value of 'addition' is between -0.5 and 0.5. Got {additions}.") + + if isinstance(additions, Tensor) and len(additions.shape) != 0: + if not (input.size(0) == len(additions) and len(additions.shape) == 1): + raise AssertionError(f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}") + # TODO: I am not happy about this line, but no easy to do batch-wise operation + additions = additions.to(input.device).to(input.dtype) + additions = torch.stack([x.expand(*input.shape[-3:]) for x in additions]) + input = input + additions + input = input.clamp(0.0, 1.0) + + return _solarize(input, thresholds) + + +@perform_keep_shape_image +def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor: + r"""Reduce the number of bits for each color channel. + + .. image:: _static/img/posterize.png + + Non-differentiable function, ``torch.uint8`` involved. + + Args: + input: image tensor with shape :math:`(*, C, H, W)` to posterize. + bits: number of high bits. Must be in range [0, 8]. + If int or one element tensor, input will be posterized by this bits. + If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[-3]. + If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)] + + Returns: + Image with reduced color channels with shape :math:`(*, C, H, W)`. + + Example: + >>> x = torch.rand(1, 6, 3, 3) + >>> out = posterize(x, bits=8) + >>> torch.testing.assert_close(x, out) + + >>> x = torch.rand(2, 6, 3, 3) + >>> bits = torch.tensor([4, 2]) + >>> posterize(x, bits).shape + torch.Size([2, 6, 3, 3]) + + """ + if not isinstance(input, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(input)}") + + if not isinstance(bits, (int, Tensor)): + raise TypeError(f"bits type is not an int or Tensor. Got {type(bits)}") + + if isinstance(bits, int): + bits = torch.as_tensor(bits) + + # TODO: find a better way to check boundaries on tensors + # if not torch.all((bits >= 0) * (bits <= 8)) and bits.dtype == torch.int: + # raise ValueError(f"bits must be integers within range [0, 8]. Got {bits}.") + + # TODO: Make a differentiable version + # Current version: + # Ref: https://github.com/open-mmlab/mmcv/pull/132/files#diff-309c9320c7f71bedffe89a70ccff7f3bR19 + # Ref: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L222 + # Potential approach: implementing kornia.LUT with floating points + # https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472 + def _left_shift(input: Tensor, shift: Tensor) -> Tensor: + return ((input * 255).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.0 + + def _right_shift(input: Tensor, shift: Tensor) -> Tensor: + return (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0 + + def _posterize_one(input: Tensor, bits: Tensor) -> Tensor: + # Single bits value condition + if bits == 0: + return torch.zeros_like(input) + if bits == 8: + return input.clone() + bits = 8 - bits + return _left_shift(_right_shift(input, bits), bits) + + if len(bits.shape) == 0 or (len(bits.shape) == 1 and len(bits) == 1): + return _posterize_one(input, bits) + + res = [] + if len(bits.shape) == 1: + if bits.shape[0] != input.shape[0]: + raise AssertionError( + f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}." + ) + + for i in range(input.shape[0]): + res.append(_posterize_one(input[i], bits[i])) + return torch.stack(res, dim=0) + + if bits.shape != input.shape[: len(bits.shape)]: + raise AssertionError( + "Batch and channel must be equal between bits and input. " + f"Got {bits.shape}, {input.shape[: len(bits.shape)]}." + ) + _input = input.view(-1, *input.shape[len(bits.shape) :]) + _bits = bits.flatten() + for i in range(input.shape[0]): + res.append(_posterize_one(_input[i], _bits[i])) + return torch.stack(res, dim=0).reshape(*input.shape) + + +@perform_keep_shape_image +def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor: + r"""Apply sharpness to the input tensor. + + .. image:: _static/img/sharpness.png + + Implemented Sharpness function from PIL using torch ops. This implementation refers to: + https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326 + + Args: + input: image tensor with shape :math:`(*, C, H, W)` to sharpen. + factor: factor of sharpness strength. Must be above 0. + If float or one element tensor, input will be sharpened by the same factor across the whole batch. + If 1-d tensor, input will be sharpened element-wisely, len(factor) == len(input). + + Returns: + Sharpened image or images with shape :math:`(*, C, H, W)`. + + Example: + >>> x = torch.rand(1, 1, 5, 5) + >>> sharpness(x, 0.5).shape + torch.Size([1, 1, 5, 5]) + + """ + if not isinstance(factor, Tensor): + factor = torch.as_tensor(factor, device=input.device, dtype=input.dtype) + + if len(factor.size()) != 0 and factor.shape != torch.Size([input.size(0)]): + raise AssertionError( + "Input batch size shall match with factor size if factor is not a 0-dim tensor. " + f"Got {input.size(0)} and {factor.shape}" + ) + + kernel = ( + torch.as_tensor([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=input.dtype, device=input.device) + .view(1, 1, 3, 3) + .repeat(input.size(1), 1, 1, 1) + / 13 + ) + + # This shall be equivalent to depthwise conv2d: + # Ref: https://discuss.pytorch.org/t/depthwise-and-separable-convolutions-in-pytorch/7315/2 + degenerate = torch.nn.functional.conv2d(input, kernel, bias=None, stride=1, groups=input.size(1)) + degenerate = torch.clamp(degenerate, 0.0, 1.0) + + # For the borders of the resulting image, fill in the values of the original image. + mask = torch.ones_like(degenerate) + padded_mask = torch.nn.functional.pad(mask, [1, 1, 1, 1]) + padded_degenerate = torch.nn.functional.pad(degenerate, [1, 1, 1, 1]) + result = torch.where(padded_mask == 1, padded_degenerate, input) + + if len(factor.size()) == 0: + return _blend_one(result, input, factor) + return torch.stack([_blend_one(result[i], input[i], factor[i]) for i in range(len(factor))]) + + +def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor: + r"""Blend two images into one. + + Args: + input1: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`. + input2: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`. + factor: factor 0-dim tensor. + + Returns: + : image tensor with the batch in the zero position. + + """ + if not isinstance(input1, Tensor): + raise AssertionError(f"`input1` must be a tensor. Got {input1}.") + if not isinstance(input2, Tensor): + raise AssertionError(f"`input1` must be a tensor. Got {input2}.") + + if isinstance(factor, Tensor) and len(factor.size()) != 0: + raise AssertionError(f"Factor shall be a float or single element tensor. Got {factor}.") + if factor == 0.0: + return input1 + if factor == 1.0: + return input2 + diff = (input2 - input1) * factor + res = input1 + diff + if factor > 0.0 and factor < 1.0: + return res + return torch.clamp(res, 0, 1) + + +def _build_lut(histo: Tensor, step: Tensor) -> Tensor: + # Compute the cumulative sum, shifting by step // 2 + # and then normalization by step. + step_trunc = torch.div(step, 2, rounding_mode="trunc") + lut = torch.div(torch.cumsum(histo, 0) + step_trunc, step, rounding_mode="trunc") + # Shift lut, prepending with 0. + lut = torch.cat([torch.zeros(1, device=lut.device, dtype=lut.dtype), lut[:-1]]) + # Clip the counts to be in range. This is done + # in the C code for image.point. + return torch.clamp(lut, 0, 255) + + +# Code taken from: https://github.com/pytorch/vision/pull/796 +def _scale_channel(im: Tensor) -> Tensor: + r"""Scale the data in the channel to implement equalize. + + Args: + im: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`. + + Returns: + image tensor with the batch in the zero position. + + """ + min_ = im.min() + max_ = im.max() + + if min_.item() < 0.0 and not torch.isclose(min_, torch.as_tensor(0.0, dtype=min_.dtype)): + raise ValueError(f"Values in the input tensor must greater or equal to 0.0. Found {min_.item()}.") + + if max_.item() > 1.0 and not torch.isclose(max_, torch.as_tensor(1.0, dtype=max_.dtype)): + raise ValueError(f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}.") + + ndims = len(im.shape) + if ndims not in (2, 3): + raise TypeError(f"Input tensor must have 2 or 3 dimensions. Found {ndims}.") + + im = im * 255.0 + # Compute the histogram of the image channel. + histo = _torch_histc_cast(im, bins=256, min=0, max=255) + # For the purposes of computing the step, filter out the nonzeros. + nonzero_histo = torch.reshape(histo[histo != 0], [-1]) + step = torch.div(torch.sum(nonzero_histo) - nonzero_histo[-1], 255, rounding_mode="trunc") + + # If step is zero, return the original image. Otherwise, build + # lut from the full histogram and step and then index from it. + if step == 0: + result = im + else: + # can't index using 2d index. Have to flatten and then reshape + result = torch.gather(_build_lut(histo, step), 0, im.flatten().long()) + result = result.reshape_as(im) + + return result / 255.0 + + +@perform_keep_shape_image +def equalize(input: Tensor) -> Tensor: + r"""Apply equalize on the input tensor. + + .. image:: _static/img/equalize.png + + Implements Equalize function from PIL using PyTorch ops based on uint8 format: + https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355 + + Args: + input: image tensor to equalize with shape :math:`(*, C, H, W)`. + + Returns: + Equalized image tensor with shape :math:`(*, C, H, W)`. + + Example: + >>> x = torch.rand(1, 2, 3, 3) + >>> equalize(x).shape + torch.Size([1, 2, 3, 3]) + + """ + res = [] + for image in input: + # Assumes RGB for now. Scales each channel independently + # and then stacks the result. + scaled_image = torch.stack([_scale_channel(image[i, :, :]) for i in range(len(image))]) + res.append(scaled_image) + return torch.stack(res) + + +@perform_keep_shape_video +def equalize3d(input: Tensor) -> Tensor: + r"""Equalize the values for a 3D volumetric tensor. + + Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format: + https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352 + + Args: + input: image tensor with shape :math:`(*, C, D, H, W)` to equalize. + + Returns: + Equalized volume with shape :math:`(B, C, D, H, W)`. + + """ + res = [] + for volume in input: + # Assumes RGB for now. Scales each channel independently + # and then stacks the result. + scaled_input = torch.stack([_scale_channel(volume[i, :, :, :]) for i in range(len(volume))]) + res.append(scaled_input) + + return torch.stack(res) + + +def invert(image: Tensor, max_val: Optional[Tensor] = None) -> Tensor: + r"""Invert the values of an input image tensor by its maximum value. + + .. image:: _static/img/invert.png + + Args: + image: The input tensor to invert with an arbitatry shape. + max_val: The expected maximum value in the input tensor. The shape has to + according to the input tensor shape, or at least has to work with broadcasting. + + Example: + >>> img = torch.rand(1, 2, 4, 4) + >>> invert(img).shape + torch.Size([1, 2, 4, 4]) + + >>> img = 255. * torch.rand(1, 2, 3, 4, 4) + >>> invert(img, torch.as_tensor(255.)).shape + torch.Size([1, 2, 3, 4, 4]) + + >>> img = torch.rand(1, 3, 4, 4) + >>> invert(img, torch.as_tensor([[[[1.]]]])).shape + torch.Size([1, 3, 4, 4]) + + """ + if not isinstance(image, Tensor): + raise AssertionError(f"Input is not a Tensor. Got: {type(input)}") + + if max_val is None: + _max_val = tensor([1.0]) + else: + _max_val = max_val + if not isinstance(_max_val, Tensor): + raise AssertionError(f"max_val is not a Tensor. Got: {type(_max_val)}") + + return _max_val.to(image) - image + + +class AdjustSaturation(Module): + r"""Adjust color saturation of an image. + + The input image is expected to be an RGB image in the range of [0, 1]. + + Args: + saturation_factor: How much to adjust the saturation. 0 will give a black + and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. + saturation_mode: The mode to adjust saturation. + + Shape: + - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`. + - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`. + + Example: + >>> x = torch.ones(1, 3, 3, 3) + >>> AdjustSaturation(2.)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.ones(2) + >>> out = AdjustSaturation(y)(x) + >>> torch.nn.functional.mse_loss(x, out) + tensor(0.) + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def __init__(self, saturation_factor: Union[float, Tensor]) -> None: + super().__init__() + self.saturation_factor: Union[float, Tensor] = saturation_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_saturation(input, self.saturation_factor) + + +class AdjustSaturationWithGraySubtraction(Module): + r"""Adjust color saturation of an image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + The input image is expected to be in the range of [0, 1]. + + The input image is expected to be an RGB or gray image in the range of [0, 1]. + + Args: + saturation_factor: How much to adjust the saturation. 0 will give a black + and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. + saturation_mode: The mode to adjust saturation. + + Shape: + - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`. + - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`. + + Example: + >>> x = torch.ones(1, 3, 3, 3) + >>> AdjustSaturationWithGraySubtraction(2.)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.ones(2) + >>> out = AdjustSaturationWithGraySubtraction(y)(x) + >>> torch.nn.functional.mse_loss(x, out) + tensor(0.) + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def __init__(self, saturation_factor: Union[float, Tensor]) -> None: + super().__init__() + self.saturation_factor: Union[float, Tensor] = saturation_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_saturation_with_gray_subtraction(input, self.saturation_factor) + + +class AdjustHue(Module): + r"""Adjust hue of an image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + The input image is expected to be in the range of [0, 1]. + + The input image is expected to be an RGB image in the range of [0, 1]. + + Args: + hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI + and -PI give complete reversal of hue channel in HSV space in positive and negative + direction respectively. 0 means no shift. Therefore, both -PI and PI will give an + image with complementary colors while 0 gives the original image. + + Shape: + - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`. + - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`. + + Example: + >>> x = torch.ones(1, 3, 3, 3) + >>> AdjustHue(3.141516)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]], + + [[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 3, 3, 3) + >>> y = torch.ones(2) * 3.141516 + >>> AdjustHue(y)(x).shape + torch.Size([2, 3, 3, 3]) + + """ + + ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1] + + def __init__(self, hue_factor: Union[float, Tensor]) -> None: + super().__init__() + self.hue_factor: Union[float, Tensor] = hue_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_hue(input, self.hue_factor) + + +class AdjustGamma(Module): + r"""Perform gamma correction on an image. + + The input image is expected to be in the range of [0, 1]. + + Args: + gamma: Non negative real number, same as y\gammay in the equation. + gamma larger than 1 make the shadows darker, while gamma smaller than 1 make + dark regions lighter. + gain: The constant multiplier. + + Shape: + - Input: Image to be adjusted in the shape of :math:`(*, N)`. + - Output: Adjusted image in the shape of :math:`(*, N)`. + + Example: + >>> x = torch.ones(1, 1, 3, 3) + >>> AdjustGamma(1.0, 2.0)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y1 = torch.ones(2) * 1.0 + >>> y2 = torch.ones(2) * 2.0 + >>> AdjustGamma(y1, y2)(x).shape + torch.Size([2, 5, 3, 3]) + + """ + + def __init__(self, gamma: Union[float, Tensor], gain: Union[float, Tensor] = 1.0) -> None: + super().__init__() + self.gamma: Union[float, Tensor] = gamma + self.gain: Union[float, Tensor] = gain + + def forward(self, input: Tensor) -> Tensor: + return adjust_gamma(input, self.gamma, self.gain) + + +class AdjustContrast(Module): + r"""Adjust Contrast of an image. + + This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision. + The input image is expected to be in the range of [0, 1]. + + Args: + contrast_factor: Contrast adjust factor per element + in the batch. 0 generates a completely black image, 1 does not modify + the input image while any other non-negative number modify the + brightness by this factor. + + Shape: + - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`. + - Output: Adjusted image in the shape of :math:`(*, N)`. + + Example: + >>> x = torch.ones(1, 1, 3, 3) + >>> AdjustContrast(0.5)(x) + tensor([[[[0.5000, 0.5000, 0.5000], + [0.5000, 0.5000, 0.5000], + [0.5000, 0.5000, 0.5000]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.ones(2) + >>> AdjustContrast(y)(x).shape + torch.Size([2, 5, 3, 3]) + + """ + + def __init__(self, contrast_factor: Union[float, Tensor]) -> None: + super().__init__() + self.contrast_factor: Union[float, Tensor] = contrast_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_contrast(input, self.contrast_factor) + + +class AdjustContrastWithMeanSubtraction(Module): + r"""Adjust Contrast of an image. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + The input image is expected to be in the range of [0, 1]. + + Args: + contrast_factor: Contrast adjust factor per element + in the batch by subtracting its mean grayscaled version. + 0 generates a completely black image, 1 does not modify + the input image while any other non-negative number modify the + brightness by this factor. + + Shape: + - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`. + - Output: Adjusted image in the shape of :math:`(*, N)`. + + Example: + >>> x = torch.ones(1, 1, 3, 3) + >>> AdjustContrastWithMeanSubtraction(0.5)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.ones(2) + >>> AdjustContrastWithMeanSubtraction(y)(x).shape + torch.Size([2, 5, 3, 3]) + + """ + + def __init__(self, contrast_factor: Union[float, Tensor]) -> None: + super().__init__() + self.contrast_factor: Union[float, Tensor] = contrast_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_contrast_with_mean_subtraction(input, self.contrast_factor) + + +class AdjustBrightness(Module): + r"""Adjust Brightness of an image. + + This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision. + The input image is expected to be in the range of [0, 1]. + + Args: + brightness_factor: Brightness adjust factor per element + in the batch. 0 does not modify the input image while any other number modify the + brightness. + + Shape: + - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`. + - Output: Adjusted image in the shape of :math:`(*, N)`. + + Example: + >>> x = torch.ones(1, 1, 3, 3) + >>> AdjustBrightness(1.)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.ones(2) + >>> AdjustBrightness(y)(x).shape + torch.Size([2, 5, 3, 3]) + + """ + + def __init__(self, brightness_factor: Union[float, Tensor]) -> None: + super().__init__() + self.brightness_factor: Union[float, Tensor] = brightness_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_brightness(input, self.brightness_factor) + + +class AdjustSigmoid(Module): + r"""Adjust the contrast of an image tensor or performs sigmoid correction on the input image tensor. + + The input image is expected to be in the range of [0, 1]. + + Reference: + [1]: Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions", + http://markfairchild.org/PDFs/PAP07.pdf + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + cutoff: The cutoff of sigmoid function. + gain: The multiplier of sigmoid function. + inv: If is set to True the function will return the negative sigmoid correction. + + Example: + >>> x = torch.ones(1, 1, 2, 2) + >>> AdjustSigmoid(gain=0)(x) + tensor([[[[0.5000, 0.5000], + [0.5000, 0.5000]]]]) + + """ + + def __init__(self, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> None: + super().__init__() + self.cutoff: float = cutoff + self.gain: float = gain + self.inv: bool = inv + + def forward(self, image: Tensor) -> Tensor: + return adjust_sigmoid(image, cutoff=self.cutoff, gain=self.gain, inv=self.inv) + + +class AdjustLog(Module): + """Adjust log correction on the input image tensor. + + The input image is expected to be in the range of [0, 1]. + + Reference: + [1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf + + Args: + image: Image to be adjusted in the shape of :math:`(*, H, W)`. + gain: The multiplier of logarithmic function. + inv: If is set to True the function will return the inverse logarithmic correction. + clip_output: Whether to clip the output image with range of [0, 1]. + + Example: + >>> x = torch.zeros(1, 1, 2, 2) + >>> AdjustLog(inv=True)(x) + tensor([[[[0., 0.], + [0., 0.]]]]) + + """ + + def __init__(self, gain: float = 1, inv: bool = False, clip_output: bool = True) -> None: + super().__init__() + self.gain: float = gain + self.inv: bool = inv + self.clip_output: bool = clip_output + + def forward(self, image: Tensor) -> Tensor: + return adjust_log(image, gain=self.gain, inv=self.inv, clip_output=self.clip_output) + + +class AdjustBrightnessAccumulative(Module): + r"""Adjust Brightness of an image accumulatively. + + This implementation aligns PIL. Hence, the output is close to TorchVision. + The input image is expected to be in the range of [0, 1]. + + Args: + brightness_factor: Brightness adjust factor per element + in the batch. 0 does not modify the input image while any other number modify the + brightness. + + Shape: + - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`. + - Output: Adjusted image in the shape of :math:`(*, N)`. + + Example: + >>> x = torch.ones(1, 1, 3, 3) + >>> AdjustBrightnessAccumulative(1.)(x) + tensor([[[[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]]]) + + >>> x = torch.ones(2, 5, 3, 3) + >>> y = torch.ones(2) + >>> AdjustBrightnessAccumulative(y)(x).shape + torch.Size([2, 5, 3, 3]) + + """ + + def __init__(self, brightness_factor: Union[float, Tensor]) -> None: + super().__init__() + self.brightness_factor: Union[float, Tensor] = brightness_factor + + def forward(self, input: Tensor) -> Tensor: + return adjust_brightness_accumulative(input, self.brightness_factor) + + +class Invert(Module): + r"""Invert the values of an input tensor by its maximum value. + + Args: + input: The input tensor to invert with an arbitatry shape. + max_val: The expected maximum value in the input tensor. The shape has to + according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0. + + Example: + >>> img = torch.rand(1, 2, 4, 4) + >>> Invert()(img).shape + torch.Size([1, 2, 4, 4]) + + >>> img = 255. * torch.rand(1, 2, 3, 4, 4) + >>> Invert(torch.as_tensor(255.))(img).shape + torch.Size([1, 2, 3, 4, 4]) + + >>> img = torch.rand(1, 3, 4, 4) + >>> Invert(torch.as_tensor([[[[1.]]]]))(img).shape + torch.Size([1, 3, 4, 4]) + + """ + + def __init__(self, max_val: Optional[Tensor] = None) -> None: + super().__init__() + if max_val is None: + max_val = torch.tensor(1.0) + if not isinstance(max_val, Parameter): + self.register_buffer("max_val", max_val) + else: + self.max_val = max_val + + def forward(self, input: Tensor) -> Tensor: + return invert(input, self.max_val) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/core.py b/python_embeded/Lib/site-packages/kornia/enhance/core.py new file mode 100644 index 0000000000000000000000000000000000000000..bbbb5a8699955ff1f48643f62c7fc8e422609fb5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/core.py @@ -0,0 +1,117 @@ +# 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. +# + +from typing import Union + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR + + +def add_weighted( + src1: Tensor, alpha: Union[float, Tensor], src2: Tensor, beta: Union[float, Tensor], gamma: Union[float, Tensor] +) -> Tensor: + r"""Calculate the weighted sum of two Tensors. + + .. image:: _static/img/add_weighted.png + + The function calculates the weighted sum of two Tensors as follows: + + .. math:: + out = src1 * alpha + src2 * beta + gamma + + Args: + src1: Tensor with an arbitrary shape, equal to shape of src2. + alpha: weight of the src1 elements as Union[float, Tensor]. + src2: Tensor with an arbitrary shape, equal to shape of src1. + beta: weight of the src2 elements as Union[float, Tensor]. + gamma: scalar added to each sum as Union[float, Tensor]. + + Returns: + Weighted Tensor with shape equal to src1 and src2 shapes. + + Example: + >>> input1 = torch.rand(1, 1, 5, 5) + >>> input2 = torch.rand(1, 1, 5, 5) + >>> output = add_weighted(input1, 0.5, input2, 0.5, 1.0) + >>> output.shape + torch.Size([1, 1, 5, 5]) + + Notes: + Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes. + + """ + KORNIA_CHECK_IS_TENSOR(src1) + KORNIA_CHECK_IS_TENSOR(src2) + KORNIA_CHECK(src1.shape == src2.shape, f"src1 and src2 have different shapes. Got {src1.shape} and {src2.shape}") + + if isinstance(alpha, Tensor): + KORNIA_CHECK(src1.shape == alpha.shape, "alpha has a different shape than src.") + else: + alpha = tensor(alpha, dtype=src1.dtype, device=src1.device) + + if isinstance(beta, Tensor): + KORNIA_CHECK(src1.shape == beta.shape, "beta has a different shape than src.") + else: + beta = tensor(beta, dtype=src1.dtype, device=src1.device) + + if isinstance(gamma, Tensor): + KORNIA_CHECK(src1.shape == gamma.shape, "gamma has a different shape than src.") + else: + gamma = tensor(gamma, dtype=src1.dtype, device=src1.device) + + return src1 * alpha + src2 * beta + gamma + + +class AddWeighted(Module): + r"""Calculate the weighted sum of two Tensors. + + The function calculates the weighted sum of two Tensors as follows: + + .. math:: + out = src1 * alpha + src2 * beta + gamma + + Args: + alpha: weight of the src1 elements as Union[float, Tensor]. + beta: weight of the src2 elements as Union[float, Tensor]. + gamma: scalar added to each sum as Union[float, Tensor]. + + Shape: + - Input1: Tensor with an arbitrary shape, equal to shape of Input2. + - Input2: Tensor with an arbitrary shape, equal to shape of Input1. + - Output: Weighted tensor with shape equal to src1 and src2 shapes. + + Example: + >>> input1 = torch.rand(1, 1, 5, 5) + >>> input2 = torch.rand(1, 1, 5, 5) + >>> output = AddWeighted(0.5, 0.5, 1.0)(input1, input2) + >>> output.shape + torch.Size([1, 1, 5, 5]) + + Notes: + Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes. + + """ + + def __init__(self, alpha: Union[float, Tensor], beta: Union[float, Tensor], gamma: Union[float, Tensor]) -> None: + super().__init__() + self.alpha = alpha + self.beta = beta + self.gamma = gamma + + def forward(self, src1: Tensor, src2: Tensor) -> Tensor: + return add_weighted(src1, self.alpha, src2, self.beta, self.gamma) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/equalization.py b/python_embeded/Lib/site-packages/kornia/enhance/equalization.py new file mode 100644 index 0000000000000000000000000000000000000000..9c59ff1ef1c53659bc2804c45ae271d17cfde60e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/equalization.py @@ -0,0 +1,403 @@ +# 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. +# + +"""In this module several equalization methods are exposed: he, ahe, clahe.""" + +import math +from typing import Tuple + +import torch +import torch.nn.functional as F + +from kornia.utils.helpers import _torch_histc_cast +from kornia.utils.image import perform_keep_shape_image + +from .histogram import histogram + + +def _compute_tiles( + imgs: torch.Tensor, grid_size: Tuple[int, int], even_tile_size: bool = False +) -> Tuple[torch.Tensor, torch.Tensor]: + r"""Compute tiles on an image according to a grid size. + + Note that padding can be added to the image in order to crop properly the image. + So, the grid_size (GH, GW) x tile_size (TH, TW) >= image_size (H, W) + + Args: + imgs: batch of 2D images with shape (B, C, H, W) or (C, H, W). + grid_size: number of tiles to be cropped in each direction (GH, GW) + even_tile_size: Determine if the width and height of the tiles must be even. + + Returns: + tensor with tiles (B, GH, GW, C, TH, TW). B = 1 in case of a single image is provided. + tensor with the padded batch of 2D imageswith shape (B, C, H', W'). + + """ + batch: torch.Tensor = imgs # B x C x H x W + + # compute stride and kernel size + h, w = batch.shape[-2:] + kernel_vert: int = math.ceil(h / grid_size[0]) + kernel_horz: int = math.ceil(w / grid_size[1]) + + if even_tile_size: + kernel_vert += 1 if kernel_vert % 2 else 0 + kernel_horz += 1 if kernel_horz % 2 else 0 + + # add padding (with that kernel size we could need some extra cols and rows...) + pad_vert = kernel_vert * grid_size[0] - h + pad_horz = kernel_horz * grid_size[1] - w + + # add the padding in the last coluns and rows + if pad_vert > batch.shape[-2] or pad_horz > batch.shape[-1]: + raise ValueError("Cannot compute tiles on the image according to the given grid size") + + if pad_vert > 0 or pad_horz > 0: + batch = F.pad(batch, [0, pad_horz, 0, pad_vert], mode="reflect") # B x C x H' x W' + + # compute tiles + c: int = batch.shape[-3] + tiles: torch.Tensor = ( + batch.unfold(1, c, c) # unfold(dimension, size, step) + .unfold(2, kernel_vert, kernel_vert) + .unfold(3, kernel_horz, kernel_horz) + .squeeze(1) + ).contiguous() # GH x GW x C x TH x TW + + if tiles.shape[-5] != grid_size[0]: + raise AssertionError + + if tiles.shape[-4] != grid_size[1]: + raise AssertionError + + return tiles, batch + + +def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int, int]) -> torch.Tensor: + r"""Compute interpolation tiles on a properly padded set of images. + + Note that images must be padded. So, the tile_size (TH, TW) * grid_size (GH, GW) = image_size (H, W) + + Args: + padded_imgs: batch of 2D images with shape (B, C, H, W) already padded to extract tiles + of size (TH, TW). + tile_size: shape of the current tiles (TH, TW). + + Returns: + tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2). + + """ + if padded_imgs.dim() != 4: + raise AssertionError("Images Tensor must be 4D.") + + if padded_imgs.shape[-2] % tile_size[0] != 0: + raise AssertionError("Images are not correctly padded.") + + if padded_imgs.shape[-1] % tile_size[1] != 0: + raise AssertionError("Images are not correctly padded.") + + # tiles to be interpolated are built by dividing in 4 each already existing + interp_kernel_vert: int = tile_size[0] // 2 + interp_kernel_horz: int = tile_size[1] // 2 + + c: int = padded_imgs.shape[-3] + interp_tiles: torch.Tensor = ( + padded_imgs.unfold(1, c, c) + .unfold(2, interp_kernel_vert, interp_kernel_vert) + .unfold(3, interp_kernel_horz, interp_kernel_horz) + .squeeze(1) + ).contiguous() # 2GH x 2GW x C x TH/2 x TW/2 + + if interp_tiles.shape[-3] != c: + raise AssertionError + + if interp_tiles.shape[-2] != tile_size[0] / 2: + raise AssertionError + + if interp_tiles.shape[-1] != tile_size[1] / 2: + raise AssertionError + + return interp_tiles + + +def _my_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor: + return _torch_histc_cast(tiles, bins=bins, min=0, max=1) + + +def _compute_luts( + tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 40.0, diff: bool = False +) -> torch.Tensor: + r"""Compute luts for a batched set of tiles. + + Same approach as in OpenCV (https://github.com/opencv/opencv/blob/master/modules/imgproc/src/clahe.cpp) + + Args: + tiles_x_im: set of tiles per image to apply the lut. (B, GH, GW, C, TH, TW) + num_bins: number of bins. default: 256 + clip: threshold value for contrast limiting. If it is 0 then the clipping is disabled. + diff: denote if the differentiable histagram will be used. Default: False + + Returns: + Lut for each tile (B, GH, GW, C, 256). + + """ + if tiles_x_im.dim() != 6: + raise AssertionError("Tensor must be 6D.") + + b, gh, gw, c, th, tw = tiles_x_im.shape + pixels: int = th * tw + tiles: torch.Tensor = tiles_x_im.view(-1, pixels) # test with view # T x (THxTW) + if not diff: + if torch.jit.is_scripting(): + histos = torch.stack([_torch_histc_cast(tile, bins=num_bins, min=0, max=1) for tile in tiles]) + else: + histos = torch.stack(list(map(_my_histc, tiles, [num_bins] * len(tiles)))) + else: + bins: torch.Tensor = torch.linspace(0, 1, num_bins, device=tiles.device) + histos = histogram(tiles, bins, torch.tensor(0.001)).squeeze() + histos *= pixels + + if clip > 0.0: + max_val: float = max(clip * pixels // num_bins, 1) + histos.clamp_(max=max_val) + clipped: torch.Tensor = pixels - histos.sum(1) + residual: torch.Tensor = torch.remainder(clipped, num_bins) + redist: torch.Tensor = (clipped - residual).div(num_bins) + histos += redist[None].transpose(0, 1) + # trick to avoid using a loop to assign the residual + v_range: torch.Tensor = torch.arange(num_bins, device=histos.device) + mat_range: torch.Tensor = v_range.repeat(histos.shape[0], 1) + histos += mat_range < residual[None].transpose(0, 1) + + lut_scale: float = (num_bins - 1) / pixels + luts: torch.Tensor = torch.cumsum(histos, 1) * lut_scale + luts = luts.clamp(0, num_bins - 1) + if not diff: + luts = luts.floor() # to get the same values as converting to int maintaining the type + luts = luts.view((b, gh, gw, c, num_bins)) + return luts + + +def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor: + r"""Assign the required luts to each tile. + + Args: + interp_tiles: set of interpolation tiles. (B, 2GH, 2GW, C, TH/2, TW/2) + luts: luts for each one of the original tiles. (B, GH, GW, C, 256) + + Returns: + mapped luts (B, 2GH, 2GW, 4, C, 256) + + """ + if interp_tiles.dim() != 6: + raise AssertionError("interp_tiles tensor must be 6D.") + + if luts.dim() != 5: + raise AssertionError("luts tensor must be 5D.") + + # gh, gw -> 2x the number of tiles used to compute the histograms + # th, tw -> /2 the sizes of the tiles used to compute the histograms + num_imgs, gh, gw, c, _, _ = interp_tiles.shape + + # precompute idxs for non corner regions (doing it in cpu seems slightly faster) + j_idxs = torch.empty(0, 4, dtype=torch.long) + if gh > 2: + j_floor = torch.arange(1, gh - 1).view(gh - 2, 1).div(2, rounding_mode="trunc") + j_idxs = torch.tensor([[0, 0, 1, 1], [-1, -1, 0, 0]] * ((gh - 2) // 2)) # reminder + j_idxs[:, 0:2] -= 1 + j_idxs += j_floor + + i_idxs = torch.empty(0, 4, dtype=torch.long) + if gw > 2: + i_floor = torch.arange(1, gw - 1).view(gw - 2, 1).div(2, rounding_mode="trunc") + i_idxs = torch.tensor([[0, 1, 0, 1], [-1, 0, -1, 0]] * ((gw - 2) // 2)) # reminder + i_idxs[:, [0, 2]] -= 1 + i_idxs += i_floor + + # selection of luts to interpolate each patch + # create a tensor with dims: interp_patches height and width x 4 x num channels x bins in the histograms + # the tensor is init to -1 to denote non init hists + luts_x_interp_tiles: torch.Tensor = torch.full( # B x GH x GW x 4 x C x 256 + (num_imgs, gh, gw, 4, c, luts.shape[-1]), -1, dtype=interp_tiles.dtype, device=interp_tiles.device + ) + # corner regions + luts_x_interp_tiles[:, 0 :: gh - 1, 0 :: gw - 1, 0] = luts[:, 0 :: max(gh // 2 - 1, 1), 0 :: max(gw // 2 - 1, 1)] + # border region (h) + luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 0] = luts[:, j_idxs[:, 0], 0 :: max(gw // 2 - 1, 1)] + luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 1] = luts[:, j_idxs[:, 2], 0 :: max(gw // 2 - 1, 1)] + # border region (w) + luts_x_interp_tiles[:, 0 :: gh - 1, 1:-1, 0] = luts[:, 0 :: max(gh // 2 - 1, 1), i_idxs[:, 0]] + luts_x_interp_tiles[:, 0 :: gh - 1, 1:-1, 1] = luts[:, 0 :: max(gh // 2 - 1, 1), i_idxs[:, 1]] + # internal region + luts_x_interp_tiles[:, 1:-1, 1:-1, :] = luts[ + :, j_idxs.repeat(max(gh - 2, 1), 1, 1).permute(1, 0, 2), i_idxs.repeat(max(gw - 2, 1), 1, 1) + ] + + return luts_x_interp_tiles + + +def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor: + r"""Equalize the tiles. + + Args: + interp_tiles: set of interpolation tiles, values must be in the range [0, 1]. + (B, 2GH, 2GW, C, TH/2, TW/2) + luts: luts for each one of the original tiles. (B, GH, GW, C, 256) + + Returns: + equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2) + + """ + if interp_tiles.dim() != 6: + raise AssertionError("interp_tiles tensor must be 6D.") + + if luts.dim() != 5: + raise AssertionError("luts tensor must be 5D.") + + mapped_luts: torch.Tensor = _map_luts(interp_tiles, luts) # Bx2GHx2GWx4xCx256 + + # gh, gw -> 2x the number of tiles used to compute the histograms + # th, tw -> /2 the sizes of the tiles used to compute the histograms + num_imgs, gh, gw, c, th, tw = interp_tiles.shape + + # equalize tiles + flatten_interp_tiles: torch.Tensor = (interp_tiles * 255).long().flatten(-2, -1) # B x GH x GW x 4 x C x (THxTW) + flatten_interp_tiles = flatten_interp_tiles.unsqueeze(-3).expand(num_imgs, gh, gw, 4, c, th * tw) + preinterp_tiles_equalized = ( + torch.gather(mapped_luts, 5, flatten_interp_tiles) # B x GH x GW x 4 x C x TH x TW + .to(interp_tiles) + .reshape(num_imgs, gh, gw, 4, c, th, tw) + ) + + # interp tiles + tiles_equalized: torch.Tensor = torch.zeros_like(interp_tiles) + + # compute the interpolation weights (shapes are 2 x TH x TW because they must be applied to 2 interp tiles) + ih = ( + torch.arange(2 * th - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device) + .div(2.0 * th - 1)[None] + .transpose(-2, -1) + .expand(2 * th, tw) + ) + ih = ih.unfold(0, th, th).unfold(1, tw, tw) # 2 x 1 x TH x TW + iw = ( + torch.arange(2 * tw - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device) + .div(2.0 * tw - 1) + .expand(th, 2 * tw) + ) + iw = iw.unfold(0, th, th).unfold(1, tw, tw) # 1 x 2 x TH x TW + + # compute row and column interpolation weights + tiw = iw.expand((gw - 2) // 2, 2, th, tw).reshape(gw - 2, 1, th, tw).unsqueeze(0) # 1 x GW-2 x 1 x TH x TW + tih = ih.repeat((gh - 2) // 2, 1, 1, 1).unsqueeze(1) # GH-2 x 1 x 1 x TH x TW + + # internal regions + tl, tr, bl, br = preinterp_tiles_equalized[:, 1:-1, 1:-1].unbind(3) + t = torch.addcmul(tr, tiw, torch.sub(tl, tr)) + b = torch.addcmul(br, tiw, torch.sub(bl, br)) + tiles_equalized[:, 1:-1, 1:-1] = torch.addcmul(b, tih, torch.sub(t, b)) + + # corner regions + tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1] = preinterp_tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1, 0] + + # border region (h) + t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, 0].unbind(2) + tiles_equalized[:, 1:-1, 0] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b)) + t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, gh - 1].unbind(2) + tiles_equalized[:, 1:-1, gh - 1] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b)) + + # border region (w) + left, right, _, _ = preinterp_tiles_equalized[:, 0, 1:-1].unbind(2) + tiles_equalized[:, 0, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right)) + left, right, _, _ = preinterp_tiles_equalized[:, gw - 1, 1:-1].unbind(2) + tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right)) + + # same type as the input + return tiles_equalized.div(255.0) + + +@perform_keep_shape_image +def equalize_clahe( + input: torch.Tensor, + clip_limit: float = 40.0, + grid_size: Tuple[int, int] = (8, 8), + slow_and_differentiable: bool = False, +) -> torch.Tensor: + r"""Apply clahe equalization on the input tensor. + + .. image:: _static/img/equalize_clahe.png + + NOTE: Lut computation uses the same approach as in OpenCV, in next versions this can change. + + Args: + input: images tensor to equalize with values in the range [0, 1] and shape :math:`(*, C, H, W)`. + clip_limit: threshold value for contrast limiting. If 0 clipping is disabled. + grid_size: number of tiles to be cropped in each direction (GH, GW). + slow_and_differentiable: flag to select implementation + + Returns: + Equalized image or images with shape as the input. + + Examples: + >>> img = torch.rand(1, 10, 20) + >>> res = equalize_clahe(img) + >>> res.shape + torch.Size([1, 10, 20]) + + >>> img = torch.rand(2, 3, 10, 20) + >>> res = equalize_clahe(img) + >>> res.shape + torch.Size([2, 3, 10, 20]) + + """ + if not isinstance(clip_limit, float): + raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}") + + if not isinstance(grid_size, tuple): + raise TypeError(f"Input grid_size type is not Tuple. Got {type(grid_size)}") + + if len(grid_size) != 2: + raise TypeError(f"Input grid_size is not a Tuple with 2 elements. Got {len(grid_size)}") + + if isinstance(grid_size[0], float) or isinstance(grid_size[1], float): + raise TypeError("Input grid_size type is not valid, must be a Tuple[int, int].") + + if grid_size[0] <= 0 or grid_size[1] <= 0: + raise ValueError(f"Input grid_size elements must be positive. Got {grid_size}") + + imgs: torch.Tensor = input # B x C x H x W + + # hist_tiles: torch.Tensor # B x GH x GW x C x TH x TW # not supported by JIT + # img_padded: torch.Tensor # B x C x H' x W' # not supported by JIT + # the size of the tiles must be even in order to divide them into 4 tiles for the interpolation + hist_tiles, img_padded = _compute_tiles(imgs, grid_size, True) + tile_size: Tuple[int, int] = (hist_tiles.shape[-2], hist_tiles.shape[-1]) + interp_tiles: torch.Tensor = _compute_interpolation_tiles(img_padded, tile_size) # B x 2GH x 2GW x C x TH/2 x TW/2 + luts: torch.Tensor = _compute_luts( + hist_tiles, clip=clip_limit, diff=slow_and_differentiable + ) # B x GH x GW x C x 256 + equalized_tiles: torch.Tensor = _compute_equalized_tiles(interp_tiles, luts) # B x 2GH x 2GW x C x TH/2 x TW/2 + + # reconstruct the images form the tiles + # try permute + contiguous + view + eq_imgs: torch.Tensor = equalized_tiles.permute(0, 3, 1, 4, 2, 5).reshape_as(img_padded) + h, w = imgs.shape[-2:] + eq_imgs = eq_imgs[..., :h, :w] # crop imgs if they were padded + + # remove batch if the input was not in batch form + if input.dim() != eq_imgs.dim(): + eq_imgs = eq_imgs.squeeze(0) + + return eq_imgs diff --git a/python_embeded/Lib/site-packages/kornia/enhance/histogram.py b/python_embeded/Lib/site-packages/kornia/enhance/histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..1fda149e0ae7edd07a7c38f1a48b6867622c1aac --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/histogram.py @@ -0,0 +1,271 @@ +# 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. +# + +from typing import Optional, Tuple + +import torch + +from kornia.core import Tensor + + +def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1e-10) -> Tuple[Tensor, Tensor]: + """Calculate the marginal probability distribution function of the input based on the number of histogram bins. + + Args: + values: shape [BxNx1]. + bins: shape [NUM_BINS]. + sigma: shape [1], gaussian smoothing factor. + epsilon: scalar, for numerical stability. + + Returns: + Tuple[Tensor, Tensor]: + - Tensor: shape [BxN]. + - Tensor: shape [BxNxNUM_BINS]. + + """ + if not isinstance(values, Tensor): + raise TypeError(f"Input values type is not a Tensor. Got {type(values)}") + + if not isinstance(bins, Tensor): + raise TypeError(f"Input bins type is not a Tensor. Got {type(bins)}") + + if not isinstance(sigma, Tensor): + raise TypeError(f"Input sigma type is not a Tensor. Got {type(sigma)}") + + if not values.dim() == 3: + raise ValueError(f"Input values must be a of the shape BxNx1. Got {values.shape}") + + if not bins.dim() == 1: + raise ValueError(f"Input bins must be a of the shape NUM_BINS. Got {bins.shape}") + + if not sigma.dim() == 0: + raise ValueError(f"Input sigma must be a of the shape 1. Got {sigma.shape}") + + residuals = values - bins.unsqueeze(0).unsqueeze(0) + kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2)) + + pdf = torch.mean(kernel_values, dim=1) + normalization = torch.sum(pdf, dim=1).unsqueeze(1) + epsilon + pdf = pdf / normalization + + return pdf, kernel_values + + +def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1e-10) -> Tensor: + """Calculate the joint probability distribution function of the input tensors based on the number of histogram bins. + + Args: + kernel_values1: shape [BxNxNUM_BINS]. + kernel_values2: shape [BxNxNUM_BINS]. + epsilon: scalar, for numerical stability. + + Returns: + shape [BxNUM_BINSxNUM_BINS]. + + """ + if not isinstance(kernel_values1, Tensor): + raise TypeError(f"Input kernel_values1 type is not a Tensor. Got {type(kernel_values1)}") + + if not isinstance(kernel_values2, Tensor): + raise TypeError(f"Input kernel_values2 type is not a Tensor. Got {type(kernel_values2)}") + + if not kernel_values1.dim() == 3: + raise ValueError(f"Input kernel_values1 must be a of the shape BxN. Got {kernel_values1.shape}") + + if not kernel_values2.dim() == 3: + raise ValueError(f"Input kernel_values2 must be a of the shape BxN. Got {kernel_values2.shape}") + + if kernel_values1.shape != kernel_values2.shape: + raise ValueError( + "Inputs kernel_values1 and kernel_values2 must have the same shape." + f" Got {kernel_values1.shape} and {kernel_values2.shape}" + ) + + joint_kernel_values = torch.matmul(kernel_values1.transpose(1, 2), kernel_values2) + normalization = torch.sum(joint_kernel_values, dim=(1, 2)).view(-1, 1, 1) + epsilon + pdf = joint_kernel_values / normalization + + return pdf + + +def histogram(x: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor: + """Estimate the histogram of the input tensor. + + The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter. + + Args: + x: Input tensor to compute the histogram with shape :math:`(B, D)`. + bins: The number of bins to use the histogram :math:`(N_{bins})`. + bandwidth: Gaussian smoothing factor with shape shape [1]. + epsilon: A scalar, for numerical stability. + + Returns: + Computed histogram of shape :math:`(B, N_{bins})`. + + Examples: + >>> x = torch.rand(1, 10) + >>> bins = torch.torch.linspace(0, 255, 128) + >>> hist = histogram(x, bins, bandwidth=torch.tensor(0.9)) + >>> hist.shape + torch.Size([1, 128]) + + """ + pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon) + + return pdf + + +def histogram2d(x1: Tensor, x2: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor: + """Estimate the 2d histogram of the input tensor. + + The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter. + + Args: + x1: Input tensor to compute the histogram with shape :math:`(B, D1)`. + x2: Input tensor to compute the histogram with shape :math:`(B, D2)`. + bins: The number of bins to use the histogram :math:`(N_{bins})`. + bandwidth: Gaussian smoothing factor with shape shape [1]. + epsilon: A scalar, for numerical stability. Default: 1e-10. + + Returns: + Computed histogram of shape :math:`(B, N_{bins}), N_{bins})`. + + Examples: + >>> x1 = torch.rand(2, 32) + >>> x2 = torch.rand(2, 32) + >>> bins = torch.torch.linspace(0, 255, 128) + >>> hist = histogram2d(x1, x2, bins, bandwidth=torch.tensor(0.9)) + >>> hist.shape + torch.Size([2, 128, 128]) + + """ + _, kernel_values1 = marginal_pdf(x1.unsqueeze(2), bins, bandwidth, epsilon) + _, kernel_values2 = marginal_pdf(x2.unsqueeze(2), bins, bandwidth, epsilon) + + pdf = joint_pdf(kernel_values1, kernel_values2) + + return pdf + + +def image_histogram2d( + image: Tensor, + min: float = 0.0, + max: float = 255.0, + n_bins: int = 256, + bandwidth: Optional[float] = None, + centers: Optional[Tensor] = None, + return_pdf: bool = False, + kernel: str = "triangular", + eps: float = 1e-10, +) -> Tuple[Tensor, Tensor]: + """Estimate the histogram of the input image(s). + + The calculation uses triangular kernel density estimation. + + Args: + image: Input tensor to compute the histogram with shape + :math:`(H, W)`, :math:`(C, H, W)` or :math:`(B, C, H, W)`. + min: Lower end of the interval (inclusive). + max: Upper end of the interval (inclusive). Ignored when + :attr:`centers` is specified. + n_bins: The number of histogram bins. Ignored when + :attr:`centers` is specified. + bandwidth: Smoothing factor. If not specified or equal to -1, + :math:`(bandwidth = (max - min) / n_bins)`. + centers: Centers of the bins with shape :math:`(n_bins,)`. + If not specified or empty, it is calculated as centers of + equal width bins of [min, max] range. + return_pdf: If True, also return probability densities for + each bin. + kernel: kernel to perform kernel density estimation + ``(`triangular`, `gaussian`, `uniform`, `epanechnikov`)``. + eps: epsilon for numerical stability. + + Returns: + Computed histogram of shape :math:`(bins)`, :math:`(C, bins)`, + :math:`(B, C, bins)`. + Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`, + :math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shape + of the histogram otherwise. + + """ + if image is not None and not isinstance(image, Tensor): + raise TypeError(f"Input image type is not a Tensor. Got {type(image)}.") + + if centers is not None and not isinstance(centers, Tensor): + raise TypeError(f"Bins' centers type is not a Tensor. Got {type(centers)}.") + + if centers is not None and len(centers.shape) > 0 and centers.dim() != 1: + raise ValueError(f"Bins' centers must be a Tensor of the shape (n_bins,). Got {centers.shape}.") + + if not isinstance(min, float): + raise TypeError(f"Type of lower end of the range is not a float. Got {type(min)}.") + + if not isinstance(max, float): + raise TypeError(f"Type of upper end of the range is not a float. Got {type(min)}.") + + if not isinstance(n_bins, int): + raise TypeError(f"Type of number of bins is not an int. Got {type(n_bins)}.") + + if bandwidth is not None and not isinstance(bandwidth, float): + raise TypeError(f"Bandwidth type is not a float. Got {type(bandwidth)}.") + + if not isinstance(return_pdf, bool): + raise TypeError(f"Return_pdf type is not a bool. Got {type(return_pdf)}.") + + if bandwidth is None: + bandwidth = (max - min) / n_bins + + if centers is None: + centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=image.dtype) + 0.5) + centers = centers.reshape(-1, 1, 1, 1, 1) + + u = torch.abs(image.unsqueeze(0) - centers) / bandwidth + + if kernel == "gaussian": + kernel_values = torch.exp(-0.5 * u**2) + elif kernel in ("triangular", "uniform", "epanechnikov"): + # compute the mask and cast to floating point + mask = (u <= 1).to(u.dtype) + if kernel == "triangular": + kernel_values = (1.0 - u) * mask + elif kernel == "uniform": + kernel_values = mask + else: # kernel == "epanechnikov" + kernel_values = (1.0 - u**2) * mask + else: + raise ValueError(f"Kernel must be 'triangular', 'gaussian', 'uniform' or 'epanechnikov'. Got {kernel}.") + + hist = torch.sum(kernel_values, dim=(-2, -1)).permute(1, 2, 0) + + if return_pdf: + normalization = torch.sum(hist, dim=-1, keepdim=True) + eps + pdf = hist / normalization + if image.dim() == 2: + hist = hist.squeeze() + pdf = pdf.squeeze() + elif image.dim() == 3: + hist = hist.squeeze(0) + pdf = pdf.squeeze(0) + return hist, pdf + + if image.dim() == 2: + hist = hist.squeeze() + elif image.dim() == 3: + hist = hist.squeeze(0) + + return hist, torch.zeros_like(hist) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/integral.py b/python_embeded/Lib/site-packages/kornia/enhance/integral.py new file mode 100644 index 0000000000000000000000000000000000000000..272711445b3124a90a6471d6008adc7d43450350 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/integral.py @@ -0,0 +1,150 @@ +# 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. +# + +from typing import Optional, Tuple + +from kornia.core import ImageModule as Module +from kornia.core import Tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE + + +def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Tensor: + """Calculate integral of the input tensor. + + The algorithm computes the integral image by summing over the specified dimensions. + + In case dim is specified, the contained dimensions must be unique and sorted in ascending order + and not exceed the number of dimensions of the input tensor. + + Args: + input: the input tensor with shape :math:`(*, D)`. Where D is the number of dimensions. + dim: the dimension to be summed. + + Returns: + Integral tensor for the input tensor with shape :math:`(*, D)`. + + Examples: + >>> input = torch.ones(3, 5) + >>> output = integral_tensor(input, (-2, -1)) + >>> output + tensor([[ 1., 2., 3., 4., 5.], + [ 2., 4., 6., 8., 10.], + [ 3., 6., 9., 12., 15.]]) + + """ + KORNIA_CHECK_SHAPE(input, ["*", "D"]) + + if dim is None: + dim = (-1,) + + KORNIA_CHECK(len(dim) > 0, "dim must be a non-empty tuple.") + KORNIA_CHECK(len(dim) <= len(input.shape), "dim must be a tuple of length <= input.shape.") + + output = input + for i in dim: + output = output.cumsum(i) + return output + + +def integral_image(image: Tensor) -> Tensor: + r"""Calculate integral of the input image tensor. + + This particular version sums over the last two dimensions. + + Args: + image: the input image tensor with shape :math:`(*, H, W)`. + + Returns: + Integral tensor for the input image tensor with shape :math:`(*, H, W)`. + + Examples: + >>> input = torch.ones(1, 5, 5) + >>> output = integral_image(input) + >>> output + tensor([[[ 1., 2., 3., 4., 5.], + [ 2., 4., 6., 8., 10.], + [ 3., 6., 9., 12., 15.], + [ 4., 8., 12., 16., 20.], + [ 5., 10., 15., 20., 25.]]]) + + """ + KORNIA_CHECK_SHAPE(image, ["*", "H", "W"]) + + return integral_tensor(image, (-2, -1)) + + +class IntegralTensor(Module): + r"""Calculates integral of the input tensor. + + Args: + image: the input tensor with shape :math:`(B,C,H,W)`. + + Returns: + Integral tensor for the input tensor with shape :math:`(B,C,H,W)`. + + Shape: + - Input: :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + Examples: + >>> input = torch.ones(3, 5) + >>> dim = (-2, -1) + >>> output = IntegralTensor(dim)(input) + >>> output + tensor([[ 1., 2., 3., 4., 5.], + [ 2., 4., 6., 8., 10.], + [ 3., 6., 9., 12., 15.]]) + + """ + + def __init__(self, dim: Optional[Tuple[int, ...]] = None) -> None: + super().__init__() + self.dim = dim + + def forward(self, input: Tensor) -> Tensor: + return integral_tensor(input, self.dim) + + +class IntegralImage(Module): + """Calculates integral of the input image tensor. + + This particular version sums over the last two dimensions. + + Args: + image: the input image tensor with shape :math:`(B,C,H,W)`. + + Returns: + Integral tensor for the input image tensor with shape :math:`(B,C,H,W)`. + + Shape: + - Input: :math:`(B, C, H, W)` + - Output: :math:`(B, C, H, W)` + + Examples: + >>> input = torch.ones(1, 5, 5) + >>> output = IntegralImage()(input) + >>> output + tensor([[[ 1., 2., 3., 4., 5.], + [ 2., 4., 6., 8., 10.], + [ 3., 6., 9., 12., 15.], + [ 4., 8., 12., 16., 20.], + [ 5., 10., 15., 20., 25.]]]) + + """ + + def forward(self, input: Tensor) -> Tensor: + return integral_image(input) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/jpeg.py b/python_embeded/Lib/site-packages/kornia/enhance/jpeg.py new file mode 100644 index 0000000000000000000000000000000000000000..86e9233f63f7c5bc187893a6a36307f9fe7ab0b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/jpeg.py @@ -0,0 +1,687 @@ +# 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. +# + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F + +from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb +from kornia.constants import pi +from kornia.core import Device, Dtype, Parameter, Tensor +from kornia.core import ImageModule as Module +from kornia.core.check import ( + KORNIA_CHECK, + KORNIA_CHECK_IS_TENSOR, + KORNIA_CHECK_SHAPE, +) +from kornia.geometry.transform.affwarp import rescale +from kornia.utils.image import perform_keep_shape_image +from kornia.utils.misc import ( + differentiable_clipping, + differentiable_polynomial_floor, + differentiable_polynomial_rounding, +) + +__all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"] + + +def _get_default_qt_y(device: Device, dtype: Dtype) -> Tensor: + """Generate default Quantization table of Y channel.""" + return torch.tensor( + [ + [16, 11, 10, 16, 24, 40, 51, 61], + [12, 12, 14, 19, 26, 58, 60, 55], + [14, 13, 16, 24, 40, 57, 69, 56], + [14, 17, 22, 29, 51, 87, 80, 62], + [18, 22, 37, 56, 68, 109, 103, 77], + [24, 35, 55, 64, 81, 104, 113, 92], + [49, 64, 78, 87, 103, 121, 120, 101], + [72, 92, 95, 98, 112, 100, 103, 99], + ], + device=device, + dtype=dtype, + ) + + +def _get_default_qt_c(device: Device, dtype: Dtype) -> Tensor: + """Generate default Quantization table of C channels.""" + return torch.tensor( + [ + [17, 18, 24, 47, 99, 99, 99, 99], + [18, 21, 26, 66, 99, 99, 99, 99], + [24, 26, 56, 99, 99, 99, 99, 99], + [47, 66, 99, 99, 99, 99, 99, 99], + [99, 99, 99, 99, 99, 99, 99, 99], + [99, 99, 99, 99, 99, 99, 99, 99], + [99, 99, 99, 99, 99, 99, 99, 99], + [99, 99, 99, 99, 99, 99, 99, 99], + ], + device=device, + dtype=dtype, + ) + + +def _patchify_8x8(input: Tensor) -> Tensor: + """Extract non-overlapping 8 x 8 patches from the given input image. + + Args: + input (Tensor): Input image of the shape :math:`(B, H, W)`. + + Returns: + output (Tensor): Image patchify of the shape :math:`(B, N, 8, 8)`. + + """ + # Get input shape + B, H, W = input.shape + # Patchify to shape [B, N, H // 8, W // 8] + output: Tensor = input.view(B, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4).reshape(B, -1, 8, 8) + return output + + +def _unpatchify_8x8(input: Tensor, H: int, W: int) -> Tensor: + """Reverse non-overlapping 8 x 8 patching. + + Args: + input (Tensor): Input image of the shape :math:`(B, N, 8, 8)`. + H: height of resulting tensor. + W: width of resulting tensor. + + Returns: + output (Tensor): Image patchify of the shape :math:`(B, H, W)`. + + """ + # Get input shape + B, N = input.shape[:2] + # Unpatch to [B, H, W] + output: Tensor = input.view(B, H // 8, W // 8, 8, 8).permute(0, 1, 3, 2, 4).reshape(B, H, W) + return output + + +def _dct_8x8(input: Tensor) -> Tensor: + """Perform an 8 x 8 discrete cosine transform. + + Args: + input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`. + + Returns: + output (Tensor): DCT output tensor of the shape :math:`(B, N, 8, 8)`. + + """ + # Get dtype and device + dtype: Dtype = input.dtype + device: Device = input.device + # Make DCT tensor and scaling + index: Tensor = torch.arange(8, dtype=dtype, device=device) + x, y, u, v = torch.meshgrid(index, index, index, index) + dct_tensor: Tensor = ((2.0 * x + 1.0) * u * pi / 16.0).cos() * ((2.0 * y + 1.0) * v * pi / 16.0).cos() + alpha: Tensor = torch.ones(8, dtype=dtype, device=device) + alpha[0] = 1.0 / (2**0.5) + dct_scale: Tensor = torch.einsum("i, j -> ij", alpha, alpha) * 0.25 + # Apply DCT + output: Tensor = dct_scale[None, None] * torch.tensordot(input - 128.0, dct_tensor) + return output + + +def _idct_8x8(input: Tensor) -> Tensor: + """Perform an 8 x 8 discrete cosine transform. + + Args: + input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`. + + Returns: + output (Tensor): DCT output tensor of the shape :math:`(B, N, 8, 8)`. + + """ + # Get dtype and device + dtype: Dtype = input.dtype + device: Device = input.device + # Make and apply scaling + alpha: Tensor = torch.ones(8, dtype=dtype, device=device) + alpha[0] = 1.0 / (2**0.5) + dct_scale: Tensor = torch.outer(alpha, alpha) + input = input * dct_scale[None, None] + # Make DCT tensor and scaling + index: Tensor = torch.arange(8, dtype=dtype, device=device) + x, y, u, v = torch.meshgrid(index, index, index, index) + idct_tensor: Tensor = ((2.0 * u + 1.0) * x * pi / 16.0).cos() * ((2.0 * v + 1.0) * y * pi / 16.0).cos() + # Apply DCT + output: Tensor = 0.25 * torch.tensordot(input, idct_tensor, dims=2) + 128.0 + return output + + +def _jpeg_quality_to_scale( + compression_strength: Tensor, +) -> Tensor: + """Convert a given JPEG quality to the scaling factor. + + Args: + compression_strength (Tensor): Compression strength ranging from 0 to 100. Any shape is supported. + + Returns: + scale (Tensor): Scaling factor to be applied to quantization matrix. Same shape as input. + + """ + # Get scale + scale: Tensor = differentiable_polynomial_floor( + torch.where( + compression_strength < 50, + 5000.0 / compression_strength, + 200.0 - 2.0 * compression_strength, + ) + ) + return scale + + +def _quantize( + input: Tensor, + jpeg_quality: Tensor, + quantization_table: Tensor, +) -> Tensor: + """Perform quantization. + + Args: + input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`. + jpeg_quality (Tensor): Compression strength to be applied, shape is :math:`(B)`. + quantization_table (Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`. + + Returns: + output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`. + + """ + # Scale quantization table + quantization_table_scaled: Tensor = ( + quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None] + ) + # Perform scaling + quantization_table = differentiable_polynomial_floor( + differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255) + ) + output: Tensor = input / quantization_table + # Perform rounding + output = differentiable_polynomial_rounding(output) + return output + + +def _dequantize( + input: Tensor, + jpeg_quality: Tensor, + quantization_table: Tensor, +) -> Tensor: + """Perform dequantization. + + Args: + input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`. + jpeg_quality (Tensor): Compression strength to be applied, shape is :math:`(B)`. + quantization_table (Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`. + + Returns: + output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`. + + """ + # Scale quantization table + quantization_table_scaled: Tensor = ( + quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None] + ) + # Perform scaling + output: Tensor = input * differentiable_polynomial_floor( + differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255) + ) + return output + + +def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Implement chroma subsampling. + + Args: + input_ycbcr (Tensor): YCbCr input tensor of the shape :math:`(B, 3, H, W)`. + + Returns: + output_y (Tensor): Y component (not-subsampled), shape is :math:`(B, H, W)`. + output_cb (Tensor): Cb component (subsampled), shape is :math:`(B, H // 2, W // 2)`. + output_cr (Tensor): Cr component (subsampled), shape is :math:`(B, H // 2, W // 2)`. + + """ + # Get components + output_y: Tensor = input_ycbcr[:, 0] + output_cb: Tensor = input_ycbcr[:, 1] + output_cr: Tensor = input_ycbcr[:, 2] + # Perform average pooling of Cb and Cr channels + output_cb = rescale( + output_cb[:, None], + factor=0.5, + interpolation="bilinear", + align_corners=False, + antialias=True, + ) + output_cr = rescale( + output_cr[:, None], + factor=0.5, + interpolation="bilinear", + align_corners=False, + antialias=True, + ) + return output_y, output_cb[:, 0], output_cr[:, 0] + + +def _chroma_upsampling(input_c: Tensor) -> Tensor: + """Perform chroma upsampling. + + Args: + input_c (Tensor): Cb or Cr component to be upsampled of the shape :math:`(B, H, W)`. + + Returns: + output_c (Tensor): Upsampled C(b or r) component of the shape :math:`(B, H * 2, W * 2)`. + + """ + # Upsample component + output_c: Tensor = rescale( + input_c[:, None], + factor=2.0, + interpolation="bilinear", + align_corners=False, + antialias=False, + ) + return output_c[:, 0] + + +def _jpeg_encode( + image_rgb: Tensor, + jpeg_quality: Tensor, + quantization_table_y: Tensor, + quantization_table_c: Tensor, +) -> tuple[Tensor, Tensor, Tensor]: + """Perform JPEG encoding. + + Args: + image_rgb (Tensor): RGB input images of the shape :math:`(B, 3, H, W)`. + jpeg_quality (Tensor): Compression strength of the shape :math:`(B)`. + quantization_table_y (Tensor): Quantization table for Y channel. + quantization_table_c (Tensor): Quantization table for C channels. + + Returns: + y_encoded (Tensor): Encoded Y component of the shape :math:`(B, N, 8, 8)`. + cb_encoded (Tensor): Encoded Cb component of the shape :math:`(B, N, 8, 8)`. + cr_encoded (Tensor): Encoded Cr component of the shape :math:`(B, N, 8, 8)`. + + """ + # Convert RGB image to YCbCr. + image_ycbcr: Tensor = rgb_to_ycbcr(image_rgb) + # Scale pixel-range to [0, 255] + image_ycbcr = 255.0 * image_ycbcr + # Perform chroma subsampling + input_y, input_cb, input_cr = _chroma_subsampling(image_ycbcr) + # Patchify, DCT, and rounding + input_y, input_cb, input_cr = ( + _patchify_8x8(input_y), + _patchify_8x8(input_cb), + _patchify_8x8(input_cr), + ) + dct_y = _dct_8x8(input_y) + dct_cb_cr = _dct_8x8(torch.cat((input_cb, input_cr), dim=1)) + y_encoded: Tensor = _quantize( + dct_y, + jpeg_quality, + quantization_table_y, + ) + cb_encoded, cr_encoded = _quantize( + dct_cb_cr, + jpeg_quality, + quantization_table_c, + ).chunk(2, dim=1) + return y_encoded, cb_encoded, cr_encoded + + +def _jpeg_decode( + input_y: Tensor, + input_cb: Tensor, + input_cr: Tensor, + jpeg_quality: Tensor, + H: int, + W: int, + quantization_table_y: Tensor, + quantization_table_c: Tensor, +) -> Tensor: + """Perform JPEG decoding. + + Args: + input_y (Tensor): Compressed Y component of the shape :math:`(B, N, 8, 8)`. + input_cb (Tensor): Compressed Cb component of the shape :math:`(B, N, 8, 8)`. + input_cr (Tensor): Compressed Cr component of the shape :math:`(B, N, 8, 8)`. + jpeg_quality (Tensor): Compression strength of the shape :math:`(B)`. + H (int): Original image height. + W (int): Original image width. + quantization_table_y (Tensor): Quantization table for Y channel. + quantization_table_c (Tensor): Quantization table for C channels. + + Returns: + rgb_decoded (Tensor): Decompressed RGB image of the shape :math:`(B, 3, H, W)`. + + """ + # Dequantize inputs + input_y = _dequantize( + input_y, + jpeg_quality, + quantization_table_y, + ) + input_cb_cr = _dequantize( + torch.cat((input_cb, input_cr), dim=1), + jpeg_quality, + quantization_table_c, + ) + # Perform inverse DCT + idct_y: Tensor = _idct_8x8(input_y) + idct_cb, idct_cr = _idct_8x8(input_cb_cr).chunk(2, dim=1) + # Reverse patching + image_y: Tensor = _unpatchify_8x8(idct_y, H, W) + image_cb: Tensor = _unpatchify_8x8(idct_cb, H // 2, W // 2) + image_cr: Tensor = _unpatchify_8x8(idct_cr, H // 2, W // 2) + # Perform chroma upsampling + image_cb = _chroma_upsampling(image_cb) + image_cr = _chroma_upsampling(image_cr) + # Back to [0, 1] pixel-range + image_ycbcr: Tensor = torch.stack((image_y, image_cb, image_cr), dim=1) / 255.0 + # Convert back to RGB space. + rgb_decoded: Tensor = ycbcr_to_rgb(image_ycbcr) + return rgb_decoded + + +def _perform_padding(image: Tensor) -> tuple[Tensor, int, int]: + """Pad a given image to be dividable by 16. + + Args: + image: Image of the shape :math:`(*, 3, H, W)`. + + Returns: + image_padded: Padded image of the shape :math:`(*, 3, H_{new}, W_{new})`. + h_pad: Padded pixels along the horizontal axis. + w_pad: Padded pixels along the vertical axis. + + """ + # Get spatial dimensions of the image + H, W = image.shape[-2:] + # Compute horizontal and vertical padding + h_pad: int = math.ceil(H / 16) * 16 - H + w_pad: int = math.ceil(W / 16) * 16 - W + # Perform padding (we follow JPEG and pad only the bottom and right side of the image) + image_padded: Tensor = F.pad(image, (0, w_pad, 0, h_pad), "replicate") + return image_padded, h_pad, w_pad + + +@perform_keep_shape_image +def jpeg_codec_differentiable( + image_rgb: Tensor, + jpeg_quality: Tensor, + quantization_table_y: Tensor | None = None, + quantization_table_c: Tensor | None = None, +) -> Tensor: + r"""Differentiable JPEG encoding-decoding module. + + Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows: + + .. image:: _static/img/jpeg_codec_differentiable.png + + .. math:: + + \text{JPEG}_{\text{diff}}(I, q, QT_{y}, QT_{c}) = \hat{I} + + Where: + - :math:`I` is the original image to be coded. + - :math:`q` is the JPEG quality controlling the compression strength. + - :math:`QT_{y}` is the luma quantization table. + - :math:`QT_{c}` is the chroma quantization table. + - :math:`\hat{I}` is the resulting JPEG encoded-decoded image. + + .. note::: + The input (and output) pixel range is :math:`[0, 1]`. In case you want to handle normalized images you are + required to first perform denormalization followed by normalizing the output images again. + + Note, that this implementation models the encoding-decoding mapping of JPEG in a differentiable setting, + however, does not allow the excess of the JPEG-coded byte file itself. + For more details please refer to :cite:`reich2024`. + + This implementation is not meant for data loading. For loading JPEG images please refer to `kornia.io`. + There we provide an optimized Rust implementation for fast JPEG loading. + + Args: + image_rgb: the RGB image to be coded. + jpeg_quality: JPEG quality in the range :math:`[0, 100]` controlling the compression strength. + quantization_table_y: quantization table for Y channel. Default: `None`, which will load the standard + quantization table. + quantization_table_c: quantization table for C channels. Default: `None`, which will load the standard + quantization table. + + Shape: + - image_rgb: :math:`(*, 3, H, W)`. + - jpeg_quality: :math:`(1)` or :math:`(B)` (if used batch dim. needs to match w/ image_rgb). + - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb). + - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb). + + Return: + JPEG coded image of the shape :math:`(B, 3, H, W)` + + Example: + To perform JPEG coding with the standard quantization tables just provide a JPEG quality + + >>> img = torch.rand(3, 3, 64, 64, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.tensor((99.0, 25.0, 1.0), requires_grad=True) + >>> img_jpeg = jpeg_codec_differentiable(img, jpeg_quality) + >>> img_jpeg.sum().backward() + + You also have the option to provide custom quantization tables + + >>> img = torch.rand(3, 3, 64, 64, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.tensor((99.0, 25.0, 1.0), requires_grad=True) + >>> quantization_table_y = torch.randint(1, 256, size=(3, 8, 8), dtype=torch.float) + >>> quantization_table_c = torch.randint(1, 256, size=(3, 8, 8), dtype=torch.float) + >>> img_jpeg = jpeg_codec_differentiable(img, jpeg_quality, quantization_table_y, quantization_table_c) + >>> img_jpeg.sum().backward() + + In case you want to control the quantization purly base on the quantization tables use a JPEG quality of 99.5. + Setting the JPEG quality to 99.5 leads to a QT scaling of 1, see Eq. 2 of :cite:`reich2024` for details. + + >>> img = torch.rand(3, 3, 64, 64, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.ones(3) * 99.5 + >>> quantization_table_y = torch.randint(1, 256, size=(3, 8, 8), dtype=torch.float) + >>> quantization_table_c = torch.randint(1, 256, size=(3, 8, 8), dtype=torch.float) + >>> img_jpeg = jpeg_codec_differentiable(img, jpeg_quality, quantization_table_y, quantization_table_c) + >>> img_jpeg.sum().backward() + + """ + # Check that inputs are tensors + KORNIA_CHECK_IS_TENSOR(image_rgb) + KORNIA_CHECK_IS_TENSOR(jpeg_quality) + # Get device and dtype + dtype: Dtype = image_rgb.dtype + device: Device = image_rgb.device + # Use default QT if QT is not given + quantization_table_y = _get_default_qt_y(device, dtype) if quantization_table_y is None else quantization_table_y + quantization_table_c = _get_default_qt_c(device, dtype) if quantization_table_c is None else quantization_table_c + KORNIA_CHECK_IS_TENSOR(quantization_table_y) + KORNIA_CHECK_IS_TENSOR(quantization_table_c) + # Check shape of inputs + KORNIA_CHECK_SHAPE(image_rgb, ["*", "3", "H", "W"]) + KORNIA_CHECK_SHAPE(jpeg_quality, ["B"]) + # Add batch dimension to quantization tables if needed + if quantization_table_y.ndim == 2: + quantization_table_y = quantization_table_y.unsqueeze(dim=0) + if quantization_table_c.ndim == 2: + quantization_table_c = quantization_table_c.unsqueeze(dim=0) + # Check resulting shape of quantization tables + KORNIA_CHECK_SHAPE(quantization_table_y, ["B", "8", "8"]) + KORNIA_CHECK_SHAPE(quantization_table_c, ["B", "8", "8"]) + # Check value range of JPEG quality + KORNIA_CHECK( + (jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0), + f"JPEG quality is out of range. Expected range is [0, 100], " + f"got [{jpeg_quality.amin().item()}, {jpeg_quality.amax().item()}]. Consider clipping jpeg_quality.", + ) + # Pad the image to a shape dividable by 16 + image_rgb, h_pad, w_pad = _perform_padding(image_rgb) + # Get height and shape + H, W = image_rgb.shape[-2:] + # Check matching batch dimensions + if quantization_table_y.shape[0] != 1: + KORNIA_CHECK( + quantization_table_y.shape[0] == image_rgb.shape[0], + f"Batch dimensions do not match. " + f"Got {image_rgb.shape[0]} images and {quantization_table_y.shape[0]} quantization tables (Y).", + ) + if quantization_table_c.shape[0] != 1: + KORNIA_CHECK( + quantization_table_c.shape[0] == image_rgb.shape[0], + f"Batch dimensions do not match. " + f"Got {image_rgb.shape[0]} images and {quantization_table_c.shape[0]} quantization tables (C).", + ) + if jpeg_quality.shape[0] != 1: + KORNIA_CHECK( + jpeg_quality.shape[0] == image_rgb.shape[0], + f"Batch dimensions do not match. " + f"Got {image_rgb.shape[0]} images and {jpeg_quality.shape[0]} JPEG qualities.", + ) + # Quantization tables to same device and dtype as input image + quantization_table_y = quantization_table_y.to(device, dtype) + quantization_table_c = quantization_table_c.to(device, dtype) + # Perform encoding + y_encoded, cb_encoded, cr_encoded = _jpeg_encode( + image_rgb=image_rgb, + jpeg_quality=jpeg_quality, + quantization_table_c=quantization_table_c, + quantization_table_y=quantization_table_y, + ) + image_rgb_jpeg: Tensor = _jpeg_decode( + input_y=y_encoded, + input_cb=cb_encoded, + input_cr=cr_encoded, + jpeg_quality=jpeg_quality, + H=H, + W=W, + quantization_table_c=quantization_table_c, + quantization_table_y=quantization_table_y, + ) + # Clip coded image + image_rgb_jpeg = differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0) + # Crop the image again to the original shape + image_rgb_jpeg = image_rgb_jpeg[..., : H - h_pad, : W - w_pad] + return image_rgb_jpeg + + +class JPEGCodecDifferentiable(Module): + r"""Differentiable JPEG encoding-decoding module. + + Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows: + + .. math:: + + \text{JPEG}_{\text{diff}}(I, q, QT_{y}, QT_{c}) = \hat{I} + + Where: + - :math:`I` is the original image to be coded. + - :math:`q` is the JPEG quality controlling the compression strength. + - :math:`QT_{y}` is the luma quantization table. + - :math:`QT_{c}` is the chroma quantization table. + - :math:`\hat{I}` is the resulting JPEG encoded-decoded image. + + .. image:: _static/img/jpeg_codec_differentiable.png + + .. note:: + The input (and output) pixel range is :math:`[0, 1]`. In case you want to handle normalized images you are + required to first perform denormalization followed by normalizing the output images again. + + Note, that this implementation models the encoding-decoding mapping of JPEG in a differentiable setting, + however, does not allow the excess of the JPEG-coded byte file itself. + For more details please refer to :cite:`reich2024`. + + This implementation is not meant for data loading. For loading JPEG images please refer to `kornia.io`. + There we provide an optimized Rust implementation for fast JPEG loading. + + Args: + quantization_table_y: quantization table for Y channel. Default: `None`, which will load the standard + quantization table. + quantization_table_c: quantization table for C channels. Default: `None`, which will load the standard + quantization table. + + Shape: + - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb). + - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb). + - image_rgb: :math:`(*, 3, H, W)`. + - jpeg_quality: :math:`(1)` or :math:`(B)` (if used batch dim. needs to match w/ image_rgb). + + Example: + You can use the differentiable JPEG module with standard quantization tables by + + >>> diff_jpeg_module = JPEGCodecDifferentiable() + >>> img = torch.rand(2, 3, 32, 32, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.tensor((99.0, 1.0), requires_grad=True) + >>> img_jpeg = diff_jpeg_module(img, jpeg_quality) + >>> img_jpeg.sum().backward() + + You can also specify custom quantization tables to be used by + + >>> quantization_table_y = torch.randint(1, 256, size=(2, 8, 8), dtype=torch.float) + >>> quantization_table_c = torch.randint(1, 256, size=(2, 8, 8), dtype=torch.float) + >>> diff_jpeg_module = JPEGCodecDifferentiable(quantization_table_y, quantization_table_c) + >>> img = torch.rand(2, 3, 32, 32, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.tensor((99.0, 1.0), requires_grad=True) + >>> img_jpeg = diff_jpeg_module(img, jpeg_quality) + >>> img_jpeg.sum().backward() + + In case you want to learn the quantization tables just pass parameters `nn.Parameter` + + >>> quantization_table_y = torch.nn.Parameter(torch.randint(1, 256, size=(2, 8, 8), dtype=torch.float)) + >>> quantization_table_c = torch.nn.Parameter(torch.randint(1, 256, size=(2, 8, 8), dtype=torch.float)) + >>> diff_jpeg_module = JPEGCodecDifferentiable(quantization_table_y, quantization_table_c) + >>> img = torch.rand(2, 3, 32, 32, requires_grad=True, dtype=torch.float) + >>> jpeg_quality = torch.tensor((99.0, 1.0), requires_grad=True) + >>> img_jpeg = diff_jpeg_module(img, jpeg_quality) + >>> img_jpeg.sum().backward() + + """ + + def __init__( + self, + quantization_table_y: Tensor | Parameter | None = None, + quantization_table_c: Tensor | Parameter | None = None, + ) -> None: + super().__init__() + # Get default quantization tables if needed + quantization_table_y = _get_default_qt_y(None, None) if quantization_table_y is None else quantization_table_y + quantization_table_c = _get_default_qt_c(None, None) if quantization_table_c is None else quantization_table_c + if isinstance(quantization_table_y, Parameter): + self.register_parameter("quantization_table_y", quantization_table_y) + else: + self.register_buffer("quantization_table_y", quantization_table_y) + if isinstance(quantization_table_c, Parameter): + self.register_parameter("quantization_table_c", quantization_table_c) + else: + self.register_buffer("quantization_table_c", quantization_table_c) + + def forward( + self, + image_rgb: Tensor, + jpeg_quality: Tensor, + ) -> Tensor: + # Perform encoding-decoding + image_rgb_jpeg: Tensor = jpeg_codec_differentiable( + image_rgb, + jpeg_quality=jpeg_quality, + quantization_table_c=self.quantization_table_c, + quantization_table_y=self.quantization_table_y, + ) + return image_rgb_jpeg diff --git a/python_embeded/Lib/site-packages/kornia/enhance/normalize.py b/python_embeded/Lib/site-packages/kornia/enhance/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..0bdc5d752f75755ff5d28eac629cea5569913852 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/normalize.py @@ -0,0 +1,316 @@ +# 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. +# + +"""Module containing functionals for intensity normalisation.""" + +from typing import List, Tuple, Union + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor + +__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"] + + +class Normalize(Module): + r"""Normalize a tensor image with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] - mean[channel]) / std[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + mean: Mean for each channel. + std: Standard deviations for each channel. + + Shape: + - Input: Image tensor of size :math:`(*, C, ...)`. + - Output: Normalised tensor with same size as input :math:`(*, C, ...)`. + + Examples: + >>> x = torch.rand(1, 4, 3, 3) + >>> out = Normalize(0.0, 255.)(x) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + >>> x = torch.rand(1, 4, 3, 3) + >>> mean = torch.zeros(4) + >>> std = 255. * torch.ones(4) + >>> out = Normalize(mean, std)(x) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + """ + + def __init__( + self, + mean: Union[Tensor, Tuple[float], List[float], float], + std: Union[Tensor, Tuple[float], List[float], float], + ) -> None: + super().__init__() + + if isinstance(mean, (int, float)): + mean = torch.tensor([mean]) + + if isinstance(std, (int, float)): + std = torch.tensor([std]) + + if isinstance(mean, (tuple, list)): + mean = torch.tensor(mean)[None] + + if isinstance(std, (tuple, list)): + std = torch.tensor(std)[None] + + self.mean = mean + self.std = std + + def forward(self, input: Tensor) -> Tensor: + return normalize(input, self.mean, self.std) + + def __repr__(self) -> str: + repr = f"(mean={self.mean}, std={self.std})" + return self.__class__.__name__ + repr + + +def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor: + r"""Normalize an image/video tensor with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] - mean[channel]) / std[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + data: Image tensor of size :math:`(B, C, *)`. + mean: Mean for each channel. + std: Standard deviations for each channel. + + Return: + Normalised tensor with same size as input :math:`(B, C, *)`. + + Examples: + >>> x = torch.rand(1, 4, 3, 3) + >>> out = normalize(x, torch.tensor([0.0]), torch.tensor([255.])) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + >>> x = torch.rand(1, 4, 3, 3) + >>> mean = torch.zeros(4) + >>> std = 255. * torch.ones(4) + >>> out = normalize(x, mean, std) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + """ + shape = data.shape + + if torch.onnx.is_in_onnx_export(): + if not isinstance(mean, Tensor) or not isinstance(std, Tensor): + raise ValueError("Only tensor is accepted when converting to ONNX.") + if mean.shape[0] != 1 or std.shape[0] != 1: + raise ValueError( + "Batch dimension must be one for broadcasting when converting to ONNX." + f"Try changing mean shape and std shape from ({mean.shape}, {std.shape}) to (1, C) or (1, C, 1, 1)." + ) + else: + if isinstance(mean, float): + mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype) + + if isinstance(std, float): + std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype) + + # Allow broadcast on channel dimension + if mean.shape and mean.shape[0] != 1: + if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]: + raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.") + + # Allow broadcast on channel dimension + if std.shape and std.shape[0] != 1: + if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]: + raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.") + + mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype) + std = torch.as_tensor(std, device=data.device, dtype=data.dtype) + + mean = mean[..., None] + std = std[..., None] + + out: Tensor = (data.view(shape[0], shape[1], -1) - mean) / std + + return out.view(shape) + + +class Denormalize(Module): + r"""Denormalize a tensor image with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] * std[channel]) + mean[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + mean: Mean for each channel. + std: Standard deviations for each channel. + + Shape: + - Input: Image tensor of size :math:`(*, C, ...)`. + - Output: Denormalised tensor with same size as input :math:`(*, C, ...)`. + + Examples: + >>> x = torch.rand(1, 4, 3, 3) + >>> out = Denormalize(0.0, 255.)(x) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + >>> x = torch.rand(1, 4, 3, 3, 3) + >>> mean = torch.zeros(1, 4) + >>> std = 255. * torch.ones(1, 4) + >>> out = Denormalize(mean, std)(x) + >>> out.shape + torch.Size([1, 4, 3, 3, 3]) + + """ + + def __init__(self, mean: Union[Tensor, float], std: Union[Tensor, float]) -> None: + super().__init__() + + self.mean = mean + self.std = std + + def forward(self, input: Tensor) -> Tensor: + return denormalize(input, self.mean, self.std) + + def __repr__(self) -> str: + repr = f"(mean={self.mean}, std={self.std})" + return self.__class__.__name__ + repr + + +def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, float]) -> Tensor: + r"""Denormalize an image/video tensor with mean and standard deviation. + + .. math:: + \text{input[channel] = (input[channel] * std[channel]) + mean[channel]} + + Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels, + + Args: + data: Image tensor of size :math:`(B, C, *)`. + mean: Mean for each channel. + std: Standard deviations for each channel. + + Return: + Denormalised tensor with same size as input :math:`(B, C, *)`. + + Examples: + >>> x = torch.rand(1, 4, 3, 3) + >>> out = denormalize(x, 0.0, 255.) + >>> out.shape + torch.Size([1, 4, 3, 3]) + + >>> x = torch.rand(1, 4, 3, 3, 3) + >>> mean = torch.zeros(1, 4) + >>> std = 255. * torch.ones(1, 4) + >>> out = denormalize(x, mean, std) + >>> out.shape + torch.Size([1, 4, 3, 3, 3]) + + """ + shape = data.shape + + if torch.onnx.is_in_onnx_export(): + if not isinstance(mean, Tensor) or not isinstance(std, Tensor): + raise ValueError("Only tensor is accepted when converting to ONNX.") + if mean.shape[0] != 1 or std.shape[0] != 1: + raise ValueError("Batch dimension must be one for broadcasting when converting to ONNX.") + else: + if isinstance(mean, float): + mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype) + + if isinstance(std, float): + std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype) + + # Allow broadcast on channel dimension + if mean.shape and mean.shape[0] != 1: + if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]: + raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.") + + # Allow broadcast on channel dimension + if std.shape and std.shape[0] != 1: + if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]: + raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.") + + mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype) + std = torch.as_tensor(std, device=data.device, dtype=data.dtype) + + mean = mean[..., None] + std = std[..., None] + + out: Tensor = (data.view(shape[0], shape[1], -1) * std) + mean + + return out.view(shape) + + +def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> Tensor: + r"""Normalise an image/video tensor by MinMax and re-scales the value between a range. + + The data is normalised using the following formulation: + + .. math:: + y_i = (b - a) * \frac{x_i - \text{min}(x)}{\text{max}(x) - \text{min}(x)} + a + + where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`. + + Args: + x: The image tensor to be normalised with shape :math:`(B, C, *)`. + min_val: The minimum value for the new range. + max_val: The maximum value for the new range. + eps: Float number to avoid zero division. + + Returns: + The normalised image tensor with same shape as input :math:`(B, C, *)`. + + Example: + >>> x = torch.rand(1, 5, 3, 3) + >>> x_norm = normalize_min_max(x, min_val=-1., max_val=1.) + >>> x_norm.min() + tensor(-1.) + >>> x_norm.max() + tensor(1.0000) + + """ + if not isinstance(x, Tensor): + raise TypeError(f"data should be a tensor. Got: {type(x)}.") + + if not isinstance(min_val, float): + raise TypeError(f"'min_val' should be a float. Got: {type(min_val)}.") + + if not isinstance(max_val, float): + raise TypeError(f"'b' should be a float. Got: {type(max_val)}.") + + if len(x.shape) < 3: + raise ValueError(f"Input shape must be at least a 3d tensor. Got: {x.shape}.") + + shape = x.shape + B, C = shape[0], shape[1] + + x_min: Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1) + x_max: Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1) + + x_out: Tensor = (max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_val + return x_out.view(shape) diff --git a/python_embeded/Lib/site-packages/kornia/enhance/rescale.py b/python_embeded/Lib/site-packages/kornia/enhance/rescale.py new file mode 100644 index 0000000000000000000000000000000000000000..b22e353e38c0e132c283c0026daa2bb8d2a0a7d1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/rescale.py @@ -0,0 +1,42 @@ +# 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. +# + +from typing import Union + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, tensor + + +class Rescale(Module): + r"""Initialize the Rescale operator. + + Args: + factor: The scaling factor. Could be a float or a 0-d tensor. + + """ + + def __init__(self, factor: Union[float, Tensor]) -> None: + super().__init__() + if isinstance(factor, float): + self.factor = tensor(factor) + else: + if not isinstance(factor, Tensor) or factor.ndim != 0: + raise TypeError(f"Expected factor to be a float or a 0-d tensor, got {factor}.") + self.factor = factor + + def forward(self, input: Tensor) -> Tensor: + return input * self.factor diff --git a/python_embeded/Lib/site-packages/kornia/enhance/shift_rgb.py b/python_embeded/Lib/site-packages/kornia/enhance/shift_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..e392eb64ca49c141adff8afb165f57732a214e39 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/shift_rgb.py @@ -0,0 +1,34 @@ +# 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. +# + +from kornia.core import Tensor, stack +from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR + + +def shift_rgb(image: Tensor, r_shift: Tensor, g_shift: Tensor, b_shift: Tensor) -> Tensor: + """Shift rgb channels. + + Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels. + """ + KORNIA_CHECK_IS_TENSOR(image) + KORNIA_CHECK_IS_COLOR(image, f"with shape {image.shape}") + + shifts = [r_shift, g_shift, b_shift] + + shifted = (image + stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1) + + return shifted diff --git a/python_embeded/Lib/site-packages/kornia/enhance/zca.py b/python_embeded/Lib/site-packages/kornia/enhance/zca.py new file mode 100644 index 0000000000000000000000000000000000000000..8c47377130c89246d28f8dcc21601f54ba826b23 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/enhance/zca.py @@ -0,0 +1,393 @@ +# 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. +# + +from typing import List, Optional, Tuple + +import torch + +from kornia.core import ImageModule as Module +from kornia.core import Tensor, concatenate, tensor + +__all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"] + + +class ZCAWhitening(Module): + r"""Compute the ZCA whitening matrix transform and the mean vector and applies the transform to the data. + + The data tensor is flattened, and the mean :math:`\mathbf{\mu}` + and covariance matrix :math:`\mathbf{\Sigma}` are computed from + the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, where + :math:`N` is the sample size and :math:`D` is flattened dimensionality + (e.g. for a tensor with size 5x3x2x2 :math:`N = 5` and :math:`D = 12`). The ZCA whitening + transform is given by: + + .. math:: + + \mathbf{X}_{\text{zca}} = (\mathbf{X - \mu})(US^{-\frac{1}{2}}U^T)^T + + where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding + eigenvalues of :math:`\Sigma`. After the transform is applied, the output is reshaped to same shape. + + Args: + dim: Determines the dimension that represents the samples axis. + eps: a small number used for numerical stability. + unbiased: Whether to use the biased estimate of the covariance matrix. + compute_inv: Compute the inverse transform matrix. + detach_transforms: Detaches gradient from the ZCA fitting. + + shape: + - x: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors. + - x_whiten: :math:`(D_0,...,D_{\text{dim}},...,D_N)` same shape as input. + + .. note:: + See a working example `here `__. + + Examples: + >>> x = torch.tensor([[0,1],[1,0],[-1,0],[0,-1]], dtype = torch.float32) + >>> zca = ZCAWhitening().fit(x) + >>> x_whiten = zca(x) + >>> zca = ZCAWhitening() + >>> x_whiten = zca(x, include_fit = True) # Includes the fitting step + >>> x_whiten = zca(x) # Can run now without the fitting set + >>> # Enable backprop through ZCA fitting process + >>> zca = ZCAWhitening(detach_transforms = False) + >>> x_whiten = zca(x, include_fit = True) # Includes the fitting step + + Note: + This implementation uses :py:meth:`~torch.svd` which yields NaNs in the backwards step + if the singular values are not unique. See `here `_ for + more information. + + References: + [1] `Stanford PCA & ZCA whitening tutorial `_ + + """ + + def __init__( + self, + dim: int = 0, + eps: float = 1e-6, + unbiased: bool = True, + detach_transforms: bool = True, + compute_inv: bool = False, + ) -> None: + super().__init__() + + self.dim = dim + self.eps = eps + self.unbiased = unbiased + self.detach_transforms = detach_transforms + self.compute_inv = compute_inv + + self.fitted = False + + self.mean_vector: Tensor + self.transform_matrix: Tensor + self.transform_inv: Optional[Tensor] + + def fit(self, x: Tensor) -> "ZCAWhitening": + r"""Fit ZCA whitening matrices to the data. + + Args: + x: Input data. + + Returns: + Returns a fitted ZCAWhiten object instance. + + """ + T, mean, T_inv = zca_mean(x, self.dim, self.unbiased, self.eps, self.compute_inv) + + self.mean_vector = mean + self.transform_matrix = T + if T_inv is None: + self.transform_inv = torch.empty([0]) + else: + self.transform_inv = T_inv + + if self.detach_transforms: + self.mean_vector = self.mean_vector.detach() + self.transform_matrix = self.transform_matrix.detach() + self.transform_inv = self.transform_inv.detach() + + self.fitted = True + + return self + + def forward(self, x: Tensor, include_fit: bool = False) -> Tensor: + r"""Apply the whitening transform to the data. + + Args: + x: Input data. + include_fit: Indicates whether to fit the data as part of the forward pass. + + Returns: + The transformed data. + + """ + if include_fit: + self.fit(x) + + if not self.fitted: + raise RuntimeError("Needs to be fitted first before running. Please call fit or set include_fit to True.") + + x_whiten = linear_transform(x, self.transform_matrix, self.mean_vector, self.dim) + + return x_whiten + + def inverse_transform(self, x: Tensor) -> Tensor: + r"""Apply the inverse transform to the whitened data. + + Args: + x: Whitened data. + + Returns: + Original data. + + """ + if not self.fitted: + raise RuntimeError("Needs to be fitted first before running. Please call fit or set include_fit to True.") + + if not self.compute_inv: + raise RuntimeError("Did not compute inverse ZCA. Please set compute_inv to True") + + if self.transform_inv is None: + raise TypeError("The transform inverse should be a Tensor. Gotcha None.") + + mean_inv: Tensor = -self.mean_vector.mm(self.transform_matrix) + + y = linear_transform(x, self.transform_inv, mean_inv) + + return y + + +def zca_mean( + inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False +) -> Tuple[Tensor, Tensor, Optional[Tensor]]: + r"""Compute the ZCA whitening matrix and mean vector. + + The output can be used with :py:meth:`~kornia.color.linear_transform`. + See :class:`~kornia.color.ZCAWhitening` for details. + + Args: + inp: input data tensor. + dim: Specifies the dimension that serves as the samples dimension. + unbiased: Whether to use the unbiased estimate of the covariance matrix. + eps: a small number used for numerical stability. + return_inverse: Whether to return the inverse ZCA transform. + + Shapes: + - inp: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors. + - transform_matrix: :math:`(\Pi_{d=0,d\neq \text{dim}}^N D_d, \Pi_{d=0,d\neq \text{dim}}^N D_d)` + - mean_vector: :math:`(1, \Pi_{d=0,d\neq \text{dim}}^N D_d)` + - inv_transform: same shape as the transform matrix + + Returns: + A tuple containing the ZCA matrix and the mean vector. If return_inverse is set to True, + then it returns the inverse ZCA matrix, otherwise it returns None. + + .. note:: + See a working example `here `__. + + Examples: + >>> x = torch.tensor([[0,1],[1,0],[-1,0],[0,-1]], dtype = torch.float32) + >>> transform_matrix, mean_vector,_ = zca_mean(x) # Returns transformation matrix and data mean + >>> x = torch.rand(3,20,2,2) + >>> transform_matrix, mean_vector, inv_transform = zca_mean(x, dim = 1, return_inverse = True) + >>> # transform_matrix.size() equals (12,12) and the mean vector.size equal (1,12) + + """ + if not isinstance(inp, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(inp)}") + + if not isinstance(eps, float): + raise TypeError(f"eps type is not a float. Got{type(eps)}") + + if not isinstance(unbiased, bool): + raise TypeError(f"unbiased type is not bool. Got{type(unbiased)}") + + if not isinstance(dim, int): + raise TypeError(f"Argument 'dim' must be of type int. Got {type(dim)}") + + if not isinstance(return_inverse, bool): + raise TypeError(f"Argument return_inverse must be of type bool {type(return_inverse)}") + + inp_size = inp.size() + + if dim >= len(inp_size) or dim < -len(inp_size): + raise IndexError( + f"Dimension out of range (expected to be in range of [{-len(inp_size)},{len(inp_size) - 1}], but got {dim}" + ) + + if dim < 0: + dim = len(inp_size) + dim + + feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))]) + + new_order: List[int] = concatenate([tensor([dim]), feat_dims]).tolist() + + inp_permute = inp.permute(new_order) + + N = inp_size[dim] + feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :]) + num_features: int = int(torch.prod(feature_sizes).item()) + + mean: Tensor = torch.mean(inp_permute, dim=0, keepdim=True) + + mean = mean.reshape((1, num_features)) + + inp_center_flat: Tensor = inp_permute.reshape((N, num_features)) - mean + + cov = inp_center_flat.t().mm(inp_center_flat) + + if unbiased: + cov = cov / float(N - 1) + else: + cov = cov / float(N) + + U, S, _ = torch.linalg.svd(cov) + + S = S.reshape(-1, 1) + S_inv_root: Tensor = torch.rsqrt(S + eps) + T: Tensor = (U).mm(S_inv_root * U.t()) + + T_inv: Optional[Tensor] = None + if return_inverse: + T_inv = (U).mm(torch.sqrt(S + eps) * U.t()) + + return T, mean, T_inv + + +def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> Tensor: + r"""Apply ZCA whitening transform. + + See :class:`~kornia.color.ZCAWhitening` for details. + + Args: + inp: input data tensor. + dim: Specifies the dimension that serves as the samples dimension. + unbiased: Whether to use the unbiased estimate of the covariance matrix. + eps: a small number used for numerical stability. + + Returns: + Whiten Input data. + + .. note:: + See a working example `here `__. + + Examples: + >>> x = torch.tensor([[0,1],[1,0],[-1,0]], dtype = torch.float32) + >>> zca_whiten(x) + tensor([[ 0.0000, 1.1547], + [ 1.0000, -0.5773], + [-1.0000, -0.5773]]) + + """ + if not isinstance(inp, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(inp)}") + + if not isinstance(eps, float): + raise TypeError(f"eps type is not a float. Got{type(eps)}") + + if not isinstance(unbiased, bool): + raise TypeError(f"unbiased type is not bool. Got{type(unbiased)}") + + if not isinstance(dim, int): + raise TypeError(f"Argument 'dim' must be of type int. Got {type(dim)}") + + transform, mean, _ = zca_mean(inp, dim, unbiased, eps, False) + + inp_whiten = linear_transform(inp, transform, mean, dim) + + return inp_whiten + + +def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor, dim: int = 0) -> Tensor: + r"""Given a transformation matrix and a mean vector, this function will flatten the input tensor along the given + dimension and subtract the mean vector from it. Then the dot product with the transformation matrix will be + computed and then the resulting tensor is reshaped to the original input shape. + + .. math:: + + \mathbf{X}_{T} = (\mathbf{X - \mu})(T) + + Args: + inp: Input data :math:`X`. + transform_matrix: Transform matrix :math:`T`. + mean_vector: mean vector :math:`\mu`. + dim: Batch dimension. + + Shapes: + - inp: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors. + - transform_matrix: :math:`(\Pi_{d=0,d\neq \text{dim}}^N D_d, \Pi_{d=0,d\neq \text{dim}}^N D_d)` + - mean_vector: :math:`(1, \Pi_{d=0,d\neq \text{dim}}^N D_d)` + + Returns: + Transformed data. + + Example: + >>> # Example where dim = 3 + >>> inp = torch.ones((10,3,4,5)) + >>> transform_mat = torch.ones((10*3*4,10*3*4)) + >>> mean = 2*torch.ones((1,10*3*4)) + >>> out = linear_transform(inp, transform_mat, mean, 3) + >>> print(out.shape, out.unique()) # Should a be (10,3,4,5) tensor of -120s + torch.Size([10, 3, 4, 5]) tensor([-120.]) + + >>> # Example where dim = 0 + >>> inp = torch.ones((10,2)) + >>> transform_mat = torch.ones((2,2)) + >>> mean = torch.zeros((1,2)) + >>> out = linear_transform(inp, transform_mat, mean) + >>> print(out.shape, out.unique()) # Should a be (10,2) tensor of 2s + torch.Size([10, 2]) tensor([2.]) + + """ # noqa: D205 + inp_size = inp.size() + + if dim >= len(inp_size) or dim < -len(inp_size): + raise IndexError( + f"Dimension out of range (expected to be in range of [{-len(inp_size)},{len(inp_size) - 1}], but got {dim}" + ) + + if dim < 0: + dim = len(inp_size) + dim + + feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))]) + + perm = concatenate([tensor([dim]), feat_dims]) + perm_inv = torch.argsort(perm) + + new_order: List[int] = perm.tolist() + inv_order: List[int] = perm_inv.tolist() + + feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :]) + num_features: int = int(torch.prod(feature_sizes).item()) + + inp_permute = inp.permute(new_order) + inp_flat = inp_permute.reshape((-1, num_features)) + + inp_center = inp_flat - mean_vector + inp_transformed = inp_center.mm(transform_matrix) + + inp_transformed = inp_transformed.reshape(inp_permute.size()) + + inp_transformed = inp_transformed.permute(inv_order) + + return inp_transformed diff --git a/python_embeded/Lib/site-packages/kornia/feature/affine_shape.py b/python_embeded/Lib/site-packages/kornia/feature/affine_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d3f7eae63fdb2e28d44b3ba319297820c0996a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/affine_shape.py @@ -0,0 +1,264 @@ +# 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. +# + +import math +import warnings +from typing import Dict, Optional + +import torch +from torch import nn + +from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE +from kornia.filters.kernels import get_gaussian_kernel2d +from kornia.filters.sobel import SpatialGradient + +from .laf import ( + ellipse_to_laf, + extract_patches_from_pyramid, + get_laf_orientation, + get_laf_scale, + make_upright, + scale_laf, + set_laf_orientation, +) + +urls: Dict[str, str] = {} +urls["affnet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth" + + +class PatchAffineShapeEstimator(nn.Module): + r"""Module, which estimates the second moment matrix of the patch gradients. + + The method determines the affine shape of the local feature as in :cite:`baumberg2000`. + + Args: + patch_size: the input image patch size. + eps: for safe division. + + """ + + def __init__(self, patch_size: int = 19, eps: float = 1e-10) -> None: + super().__init__() + self.patch_size: int = patch_size + self.gradient: nn.Module = SpatialGradient("sobel", 1) + self.eps: float = eps + sigma: float = float(self.patch_size) / math.sqrt(2.0) + self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(patch_size={self.patch_size}, eps={self.eps})" + + def forward(self, patch: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + patch: :math:`(B, 1, H, W)` + + Returns: + torch.Tensor: ellipse_shape :math:`(B, 1, 3)` + + """ + KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"]) + self.weighting = self.weighting.to(patch.dtype).to(patch.device) + grads: torch.Tensor = self.gradient(patch) * self.weighting + # unpack the edges + gx: torch.Tensor = grads[:, :, 0] + gy: torch.Tensor = grads[:, :, 1] + # abc == 1st axis, mixture, 2nd axis. Ellipse_shape is a 2nd moment matrix. + ellipse_shape = torch.cat( + [ + gx.pow(2).mean(dim=2).mean(dim=2, keepdim=True), + (gx * gy).mean(dim=2).mean(dim=2, keepdim=True), + gy.pow(2).mean(dim=2).mean(dim=2, keepdim=True), + ], + dim=2, + ) + + # Now lets detect degenerate cases: when 2 or 3 elements are close to zero (e.g. if patch is completely black + bad_mask = ((ellipse_shape < self.eps).float().sum(dim=2, keepdim=True) >= 2).to(ellipse_shape.dtype) + # We will replace degenerate shape with circular shapes. + circular_shape = torch.tensor([1.0, 0.0, 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3) + ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask + # normalization + ellipse_shape = ellipse_shape / ellipse_shape.max(dim=2, keepdim=True)[0] + return ellipse_shape + + +class LAFAffineShapeEstimator(nn.Module): + """Module, which extracts patches using input images and local affine frames (LAFs). + + Then runs :class:`~kornia.feature.PatchAffineShapeEstimator` on patches to estimate LAFs shape. + + Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved, + so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter, + + + Args: + patch_size: the input image patch size. + affine_shape_detector: Patch affine shape estimator, :class:`~kornia.feature.PatchAffineShapeEstimator`. + preserve_orientation: if True, the original orientation is preserved. + + """ # pylint: disable + + def __init__( + self, patch_size: int = 32, affine_shape_detector: Optional[nn.Module] = None, preserve_orientation: bool = True + ) -> None: + super().__init__() + self.patch_size = patch_size + self.affine_shape_detector = affine_shape_detector or PatchAffineShapeEstimator(self.patch_size) + self.preserve_orientation = preserve_orientation + if preserve_orientation: + warnings.warn( + "`LAFAffineShapeEstimator` default behaviour is changed " + "and now it does preserve original LAF orientation. " + "Make sure your code accounts for this.", + DeprecationWarning, + stacklevel=2, + ) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(patch_size={self.patch_size}, " + f"affine_shape_detector={self.affine_shape_detector}, " + f"preserve_orientation={self.preserve_orientation})" + ) + + def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + laf: :math:`(B, N, 2, 3)` + img: :math:`(B, 1, H, W)` + + Returns: + LAF_out: :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_LAF(laf) + KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"]) + B, N = laf.shape[:2] + PS: int = self.patch_size + patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS) + ellipse_shape: torch.Tensor = self.affine_shape_detector(patches) + ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5) + scale_orig = get_laf_scale(laf) + if self.preserve_orientation: + ori_orig = get_laf_orientation(laf) + laf_out = ellipse_to_laf(ellipses) + ellipse_scale = get_laf_scale(laf_out) + laf_out = scale_laf(laf_out, scale_orig / ellipse_scale) + if self.preserve_orientation: + laf_out = set_laf_orientation(laf_out, ori_orig) + return laf_out + + +class LAFAffNetShapeEstimator(nn.Module): + """Module, which extracts patches using input images and local affine frames (LAFs). + + Then runs AffNet on patches to estimate LAFs shape. This is based on the original code from paper + "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"". + See :cite:`AffNet2018` for more details. + + Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved, + so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter. + + Args: + pretrained: Download and set pretrained weights to the model. + + """ + + def __init__(self, pretrained: bool = False, preserve_orientation: bool = True) -> None: + super().__init__() + self.features = nn.Sequential( + nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(16, affine=False), + nn.ReLU(), + nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(16, affine=False), + nn.ReLU(), + nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Dropout(0.25), + nn.Conv2d(64, 3, kernel_size=8, stride=1, padding=0, bias=True), + nn.Tanh(), + nn.AdaptiveAvgPool2d(1), + ) + self.patch_size = 32 + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["affnet"], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict["state_dict"], strict=False) + self.preserve_orientation = preserve_orientation + if preserve_orientation: + warnings.warn( + "`LAFAffNetShapeEstimator` default behaviour is changed " + "and now it does preserve original LAF orientation. " + "Make sure your code accounts for this.", + DeprecationWarning, + stacklevel=2, + ) + self.eval() + + @staticmethod + def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: + """Normalize the input by batch.""" + sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True) + # WARNING: we need to .detach() input, otherwise the gradients produced by + # the patches extractor with F.grid_sample are very noisy, making the detector + # training totally unstable. + return (x - mp.detach()) / (sp.detach() + eps) + + def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + laf: :math:`(B, N, 2, 3)` + img: :math:`(B, 1, H, W)` + + Returns: + LAF_out: :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_LAF(laf) + KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"]) + B, N = laf.shape[:2] + PS: int = self.patch_size + patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS) + xy = self.features(self._normalize_input(patches)).view(-1, 3) + a1 = torch.cat([1.0 + xy[:, 0].reshape(-1, 1, 1), 0 * xy[:, 0].reshape(-1, 1, 1)], dim=2) + a2 = torch.cat([xy[:, 1].reshape(-1, 1, 1), 1.0 + xy[:, 2].reshape(-1, 1, 1)], dim=2) + new_laf_no_center = torch.cat([a1, a2], dim=1).reshape(B, N, 2, 2) + new_laf = torch.cat([new_laf_no_center, laf[:, :, :, 2:3]], dim=3) + scale_orig = get_laf_scale(laf) + if self.preserve_orientation: + ori_orig = get_laf_orientation(laf) + ellipse_scale = get_laf_scale(new_laf) + laf_out = scale_laf(make_upright(new_laf), scale_orig / ellipse_scale) + if self.preserve_orientation: + laf_out = set_laf_orientation(laf_out, ori_orig) + return laf_out diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8068840c79d8679249cef9150c5188a8a948bb --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/__init__.py @@ -0,0 +1,20 @@ +# 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. +# + +from .dedode import DeDoDe + +__all__ = ["DeDoDe"] diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5b6e681d65ea122a6c2656031bd0da683ad82f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/__init__.py @@ -0,0 +1,22 @@ +# 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. +# + +from .dinov2 import vit_large + +__all__ = [ + "vit_large", +] diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/dinov2.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/dinov2.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b52dd1d570de316a5e8ea4a55b867bd4d6cd2e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/dinov2.py @@ -0,0 +1,381 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import math +from functools import partial +from typing import Callable, Sequence, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn.init import trunc_normal_ + +from kornia.core.check import KORNIA_CHECK + +from .layers import MemEffAttention, Mlp, PatchEmbed, SwiGLUFFNFused +from .layers import NestedTensorBlock as Block + + +def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module: + """Apply named function to module.""" + if not depth_first and include_root: + fn(module=module, name=name) + for child_name, child_module in module.named_children(): + child_name = ".".join((name, child_name)) if name else child_name + named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True) + if depth_first and include_root: + fn(module=module, name=name) + return module + + +class BlockChunk(nn.ModuleList): + def forward(self, x): + for b in self: + x = b(x) + return x + + +class DinoVisionTransformer(nn.Module): + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + ffn_bias=True, + proj_bias=True, + drop_path_rate=0.0, + drop_path_uniform=False, + init_values=None, # for layerscale: None or 0 => no layerscale + embed_layer=PatchEmbed, + act_layer=nn.GELU, + block_fn=Block, + ffn_layer="mlp", + block_chunks=1, + ): + """Construct dino vision transformer. + + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + proj_bias (bool): enable bias for proj in attn if True + ffn_bias (bool): enable bias for ffn if True + drop_path_rate (float): stochastic depth rate + drop_path_uniform (bool): apply uniform drop rate across blocks + weight_init (str): weight init scheme + init_values (float): layer-scale init values + embed_layer (nn.Module): patch embedding layer + act_layer (nn.Module): MLP activation layer + block_fn (nn.Module): transformer block class + ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" + block_chunks: (int) split block sequence into block_chunks units for FSDP wrap + + """ + super().__init__() + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + self.num_tokens = 1 + self.n_blocks = depth + self.num_heads = num_heads + self.patch_size = patch_size + + self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) + + if drop_path_uniform is True: + dpr = [drop_path_rate] * depth + else: + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + if ffn_layer == "mlp": + ffn_layer = Mlp + elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": + ffn_layer = SwiGLUFFNFused + elif ffn_layer == "identity": + + def f(*args, **kwargs): + return nn.Identity() + + ffn_layer = f + else: + raise NotImplementedError + + blocks_list = [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + ffn_layer=ffn_layer, + init_values=init_values, + ) + for i in range(depth) + ] + if block_chunks > 0: + self.chunked_blocks = True + chunked_blocks = [] + chunksize = depth // block_chunks + for i in range(0, depth, chunksize): + # this is to keep the block index consistent if we chunk the block list + chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) + self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) + else: + self.chunked_blocks = False + self.blocks = nn.ModuleList(blocks_list) + + self.norm = norm_layer(embed_dim) + self.head = nn.Identity() + + self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) + + self.init_weights() + for param in self.parameters(): + param.requires_grad = False + + @property + def device(self): + return self.cls_token.device + + def init_weights(self): + trunc_normal_(self.pos_embed, std=0.02) + nn.init.normal_(self.cls_token, std=1e-6) + named_apply(init_weights_vit_timm, self) + + def interpolate_pos_encoding(self, x, w, h): + previous_dtype = x.dtype + npatch = x.shape[1] - 1 + N = self.pos_embed.shape[1] - 1 + if npatch == N and w == h: + return self.pos_embed + pos_embed = self.pos_embed.float() + class_pos_embed = pos_embed[:, 0] + patch_pos_embed = pos_embed[:, 1:] + dim = x.shape[-1] + w0 = w // self.patch_size + h0 = h // self.patch_size + # we add a small number to avoid floating point error in the interpolation + # see discussion at https://github.com/facebookresearch/dino/issues/8 + w0, h0 = w0 + 0.1, h0 + 0.1 + + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), + scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), + mode="bicubic", + ) + KORNIA_CHECK(int(w0) == patch_pos_embed.shape[-2]) + KORNIA_CHECK(int(h0) == patch_pos_embed.shape[-1]) + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype) + + def prepare_tokens_with_masks(self, x, masks=None): + B, nc, w, h = x.shape + x = self.patch_embed(x) + if masks is not None: + x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x) + + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + x = x + self.interpolate_pos_encoding(x, w, h) + + return x + + def forward_features_list(self, x_list, masks_list): + x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)] + for blk in self.blocks: + x = blk(x) + + all_x = x + output = [] + for x, masks in zip(all_x, masks_list): + x_norm = self.norm(x) + output.append( + { + "x_norm_clstoken": x_norm[:, 0], + "x_norm_patchtokens": x_norm[:, 1:], + "x_prenorm": x, + "masks": masks, + } + ) + return output + + def forward_features(self, x, masks=None): + if isinstance(x, list): + return self.forward_features_list(x, masks) + + x = self.prepare_tokens_with_masks(x, masks) + + for blk in self.blocks: + x = blk(x) + + x_norm = self.norm(x) + return { + "x_norm_clstoken": x_norm[:, 0], + "x_norm_patchtokens": x_norm[:, 1:], + "x_prenorm": x, + "masks": masks, + } + + def _get_intermediate_layers_not_chunked(self, x, n=1): + x = self.prepare_tokens_with_masks(x) + # If n is an int, take the n last blocks. If it's a list, take them + output, total_block_len = [], len(self.blocks) + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for i, blk in enumerate(self.blocks): + x = blk(x) + if i in blocks_to_take: + output.append(x) + KORNIA_CHECK(len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found") + return output + + def _get_intermediate_layers_chunked(self, x, n=1): + x = self.prepare_tokens_with_masks(x) + output, i, total_block_len = [], 0, len(self.blocks[-1]) + # If n is an int, take the n last blocks. If it's a list, take them + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for block_chunk in self.blocks: + for blk in block_chunk[i:]: # Passing the nn.Identity() + x = blk(x) + if i in blocks_to_take: + output.append(x) + i += 1 + KORNIA_CHECK(len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found") + return output + + def get_intermediate_layers( + self, + x: torch.Tensor, + n: Union[int, Sequence] = 1, # Layers or n last layers to take + reshape: bool = False, + return_class_token: bool = False, + norm=True, + ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: + if self.chunked_blocks: + outputs = self._get_intermediate_layers_chunked(x, n) + else: + outputs = self._get_intermediate_layers_not_chunked(x, n) + if norm: + outputs = [self.norm(out) for out in outputs] + class_tokens = [out[:, 0] for out in outputs] + outputs = [out[:, 1:] for out in outputs] + if reshape: + B, _, w, h = x.shape + outputs = [ + out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() + for out in outputs + ] + if return_class_token: + return tuple(zip(outputs, class_tokens)) + return tuple(outputs) + + def forward(self, *args, is_training=False, **kwargs): + ret = self.forward_features(*args, **kwargs) + if is_training: + return ret + else: + return self.head(ret["x_norm_clstoken"]) + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility).""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + +def vit_small(patch_size=16, **kwargs) -> DinoVisionTransformer: + """Return ViT Small.""" + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + **kwargs, + ) + return model + + +def vit_base(patch_size=16, **kwargs) -> DinoVisionTransformer: + """Return ViT Base.""" + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + **kwargs, + ) + return model + + +def vit_large(patch_size=16, **kwargs) -> DinoVisionTransformer: + """Return ViT Large.""" + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + **kwargs, + ) + return model + + +def vit_giant2(patch_size=16, **kwargs): + """Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64.""" + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1536, + depth=40, + num_heads=24, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + **kwargs, + ) + return model diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27b26dc51ab42f4eb6caa91e711722fbbceb63cc --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/__init__.py @@ -0,0 +1,29 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .attention import MemEffAttention +from .block import NestedTensorBlock +from .dino_head import DINOHead +from .mlp import Mlp +from .patch_embed import PatchEmbed +from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/attention.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8206dab313ff02041892b03483ba6f2f48ff20 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/attention.py @@ -0,0 +1,96 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import logging + +from torch import Tensor, nn + +logger = logging.getLogger("dinov2") + + +try: + from xformers.ops import fmha, memory_efficient_attention, unbind + + XFORMERS_AVAILABLE = True +except ImportError: + XFORMERS_AVAILABLE = False + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ) -> None: + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: Tensor) -> Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + + q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] + attn = q @ k.transpose(-2, -1) + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class MemEffAttention(Attention): + def forward(self, x: Tensor, attn_bias=None) -> Tensor: # type: ignore[no-untyped-def] + if not XFORMERS_AVAILABLE: + if attn_bias is not None: + raise ValueError("xFormers is required for nested tensors usage") + return super().forward(x) + + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + q, k, v = unbind(qkv, 2) + + x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) + x = x.reshape([B, N, C]) + + x = self.proj(x) + x = self.proj_drop(x) + return x diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/block.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/block.py new file mode 100644 index 0000000000000000000000000000000000000000..66643dc8c837374cbfdd865953cc83ba305f8e6c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/block.py @@ -0,0 +1,269 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +import logging +from typing import Any, Callable, Dict, List, Tuple + +import torch +from torch import Tensor, nn + +from kornia.core.check import KORNIA_CHECK + +from .attention import Attention, MemEffAttention +from .drop_path import DropPath +from .layer_scale import LayerScale +from .mlp import Mlp + +logger = logging.getLogger("dinov2") + + +try: + from xformers.ops import fmha, index_select_cat, scaled_index_add + + XFORMERS_AVAILABLE = True +except ImportError: + logger.warning("xFormers not available") + XFORMERS_AVAILABLE = False + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = False, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = Attention, + ffn_layer: Callable[..., nn.Module] = Mlp, + ) -> None: + super().__init__() + # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") + self.norm1 = norm_layer(dim) + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + ) + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + ) + self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.sample_drop_ratio = drop_path + + def forward(self, x: Tensor) -> Tensor: + def attn_residual_func(x: Tensor) -> Tensor: + return self.ls1(self.attn(self.norm1(x))) + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + if self.training and self.sample_drop_ratio > 0.1: + # the overhead is compensated only for a drop path rate larger than 0.1 + x = drop_add_residual_stochastic_depth( + x, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + x = drop_add_residual_stochastic_depth( + x, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + elif self.training and self.sample_drop_ratio > 0.0: + x = x + self.drop_path1(attn_residual_func(x)) + x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 + else: + x = x + attn_residual_func(x) + x = x + ffn_residual_func(x) + return x + + +def drop_add_residual_stochastic_depth( + x: Tensor, + residual_func: Callable[[Tensor], Tensor], + sample_drop_ratio: float = 0.0, +) -> Tensor: + """Add residual connection.""" + # 1) extract subset using permutation + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + x_subset = x[brange] + + # 2) apply residual_func to get residual + residual = residual_func(x_subset) + + x_flat = x.flatten(1) + residual = residual.flatten(1) + + residual_scale_factor = b / sample_subset_size + + # 3) add the residual + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + return x_plus_residual.view_as(x) + + +def get_branges_scales(x, sample_drop_ratio=0.0): + """Add bernoulli sampled range and scale.""" + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + residual_scale_factor = b / sample_subset_size + return brange, residual_scale_factor + + +def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): + """Add residual connections.""" + if scaling_vector is None: + x_flat = x.flatten(1) + residual = residual.flatten(1) + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + else: + x_plus_residual = scaled_index_add( + x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor + ) + return x_plus_residual + + +attn_bias_cache: Dict[Tuple, Any] = {} + + +def get_attn_bias_and_cat(x_list, branges=None): + """Perform the index select, cat the tensors, and provide the attn_bias from cache.""" + batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] + all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) + if all_shapes not in attn_bias_cache.keys(): + seqlens = [] + for b, x in zip(batch_sizes, x_list): + for _ in range(b): + seqlens.append(x.shape[1]) + attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) + attn_bias._batch_sizes = batch_sizes + attn_bias_cache[all_shapes] = attn_bias + + if branges is not None: + cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) + else: + tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) + cat_tensors = torch.cat(tensors_bs1, dim=1) + + return attn_bias_cache[all_shapes], cat_tensors + + +def drop_add_residual_stochastic_depth_list( + x_list: List[Tensor], + residual_func: Callable[[Tensor, Any], Tensor], + sample_drop_ratio: float = 0.0, + scaling_vector=None, +) -> Tensor: + """Add residual connections to a list of tensors.""" + # 1) generate random set of indices for dropping samples in the batch + branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list] + branges = [s[0] for s in branges_scales] + residual_scale_factors = [s[1] for s in branges_scales] + + # 2) get attention bias and index+concat the tensors + attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges) + + # 3) apply residual_func to get residual, and split the result + residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore + + outputs = [] + for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors): + outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x)) + return outputs + + +class NestedTensorBlock(Block): + def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: + """x_list contains a list of tensors to nest together and run.""" + KORNIA_CHECK(isinstance(self.attn, MemEffAttention)) + + if self.training and self.sample_drop_ratio > 0.0: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.attn(self.norm1(x), attn_bias=attn_bias) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.mlp(self.norm2(x)) + + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, + ) + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, + ) + return x_list + else: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + attn_bias, x = get_attn_bias_and_cat(x_list) + x = x + attn_residual_func(x, attn_bias=attn_bias) + x = x + ffn_residual_func(x) + return attn_bias.split(x) + + def forward(self, x_or_x_list): + if isinstance(x_or_x_list, Tensor): + return super().forward(x_or_x_list) + elif isinstance(x_or_x_list, list): + KORNIA_CHECK(XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage") + return self.forward_nested(x_or_x_list) + else: + raise AssertionError diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/dino_head.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/dino_head.py new file mode 100644 index 0000000000000000000000000000000000000000..00d6090cd62efc79d1893ca4e73518f5053cacd8 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/dino_head.py @@ -0,0 +1,76 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn.init import trunc_normal_ +from torch.nn.utils import weight_norm + + +class DINOHead(nn.Module): + def __init__( + self, + in_dim, + out_dim, + use_bn=False, + nlayers=3, + hidden_dim=2048, + bottleneck_dim=256, + mlp_bias=True, + ): + super().__init__() + nlayers = max(nlayers, 1) + self.mlp = _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=hidden_dim, use_bn=use_bn, bias=mlp_bias) + self.apply(self._init_weights) + self.last_layer = weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False)) + self.last_layer.weight_g.data.fill_(1) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + x = self.mlp(x) + eps = 1e-6 if x.dtype == torch.float16 else 1e-12 + x = nn.functional.normalize(x, dim=-1, p=2, eps=eps) + x = self.last_layer(x) + return x + + +def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True): + if nlayers == 1: + return nn.Linear(in_dim, bottleneck_dim, bias=bias) + else: + layers = [nn.Linear(in_dim, hidden_dim, bias=bias)] + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + for _ in range(nlayers - 2): + layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias)) + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias)) + return nn.Sequential(*layers) diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/drop_path.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5574c313a17a79190cdbc9f1e423bffa530e59 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/drop_path.py @@ -0,0 +1,55 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py +from typing import Optional + +from kornia.core import Module, Tensor + + +def drop_path(x: Tensor, drop_prob: Optional[float] = 0.0, training: bool = False) -> Tensor: + """Apply stochastic depth sampling.""" + if drop_prob is None: + drop_path = 0.0 + if drop_prob == 0.0 or not training: + return x + keep_prob = 1.0 - drop_prob # type: ignore + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob: Optional[float] = None) -> None: + super().__init__() + self.drop_prob = drop_prob + + def forward(self, x: Tensor) -> Tensor: + return drop_path(x, self.drop_prob, self.training) diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/layer_scale.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..90af95de1a35d0de011a2b881bacfbb4e3a8cebd --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/layer_scale.py @@ -0,0 +1,44 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 + +from typing import Union + +import torch +from torch import Tensor, nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/mlp.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..761c3e5287a06aba8d50cec90fd3e611a0ea79d2 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/mlp.py @@ -0,0 +1,58 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py + + +from typing import Callable, Optional + +from torch import Tensor, nn + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/patch_embed.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a1609fd32268c4c1e4ecadae624e28e5abfc8d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/patch_embed.py @@ -0,0 +1,106 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +from typing import Callable, Optional, Tuple, Union + +from torch import Tensor, nn + +from kornia.core.check import KORNIA_CHECK + + +def make_2tuple(x): + """Make a tuple of length 2.""" + if isinstance(x, tuple): + KORNIA_CHECK(len(x) == 2) + return x + KORNIA_CHECK(isinstance(x, int)) + return (x, x) + + +class PatchEmbed(nn.Module): + """2D image to patch embedding: (B,C,H,W) -> (B,N,D). + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[Callable] = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + patch_H, patch_W = self.patch_size + KORNIA_CHECK(H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}") + KORNIA_CHECK(W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}") + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops diff --git a/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/swiglu_ffn.py b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/swiglu_ffn.py new file mode 100644 index 0000000000000000000000000000000000000000..637fb53c356d1c1e871088e2884fcf79164bf93d --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/dedode/transformer/layers/swiglu_ffn.py @@ -0,0 +1,80 @@ +# 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. +# + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable, Optional + +import torch.nn.functional as F +from torch import Tensor, nn + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Optional[Callable[..., nn.Module]] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +try: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Optional[Callable[..., nn.Module]] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) diff --git a/python_embeded/Lib/site-packages/kornia/feature/defmo.py b/python_embeded/Lib/site-packages/kornia/feature/defmo.py new file mode 100644 index 0000000000000000000000000000000000000000..296db7aec92f061db12f5122ee4de8951be70227 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/defmo.py @@ -0,0 +1,321 @@ +# 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. +# + +from typing import Callable, Dict, List, Optional, Type + +import torch +from torch import nn + +from kornia.core import Module, Tensor, concatenate, stack + +urls: Dict[str, str] = {} +urls["defmo_encoder"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt" +urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt" + + +# conv1x1, conv3x3, Bottleneck, ResNet are taken from: +# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py + + +def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: + """1x1 convolution.""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) + + +def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d: + """3x3 convolution with padding.""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=dilation, + groups=groups, + bias=False, + dilation=dilation, + ) + + +class Bottleneck(Module): + # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) + # while original implementation places the stride at the first 1x1 convolution(self.conv1) + # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. + # This variant is also known as ResNet V1.5 and improves accuracy according to + # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. + + expansion: int = 4 + + def __init__( + self, + inplanes: int, + planes: int, + stride: int = 1, + downsample: Optional[Module] = None, + groups: int = 1, + base_width: int = 64, + dilation: int = 1, + norm_layer: Optional[Callable[..., Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + width = int(planes * (base_width / 64.0)) * groups + # Both self.conv2 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv1x1(inplanes, width) + self.bn1 = norm_layer(width) + self.conv2 = conv3x3(width, width, stride, groups, dilation) + self.bn2 = norm_layer(width) + self.conv3 = conv1x1(width, planes * self.expansion) + self.bn3 = norm_layer(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class ResNet(Module): + def __init__( + self, + block: Type[Bottleneck], + layers: List[int], + num_classes: int = 1000, + zero_init_residual: bool = False, + groups: int = 1, + width_per_group: int = 64, + replace_stride_with_dilation: Optional[List[bool]] = None, + norm_layer: Optional[Callable[..., Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + self._norm_layer = norm_layer + + self.inplanes = 64 + self.dilation = 1 + if replace_stride_with_dilation is None: + # each element in the tuple indicates if we should replace + # the 2x2 stride with a dilated convolution instead + replace_stride_with_dilation = [False, False, False] + if len(replace_stride_with_dilation) != 3: + raise ValueError( + f"replace_stride_with_dilation should be None or a 3-element tuple, got {replace_stride_with_dilation}" + ) + self.groups = groups + self.base_width = width_per_group + self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = norm_layer(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) + self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + # Zero-initialize the last BN in each residual branch, + # so that the residual branch starts with zeros, and each residual block behaves like an identity. + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck) and isinstance(m.bn3.weight, Tensor): + nn.init.constant_(m.bn3.weight, 0) + + def _make_layer( + self, block: Type[Bottleneck], planes: int, blocks: int, stride: int = 1, dilate: bool = False + ) -> nn.Sequential: + norm_layer = self._norm_layer + downsample = None + previous_dilation = self.dilation + if dilate: + self.dilation *= stride + stride = 1 + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion) + ) + + layers = [] + layers.append( + block( + self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer + ) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append( + block( + self.inplanes, + planes, + groups=self.groups, + base_width=self.base_width, + dilation=self.dilation, + norm_layer=norm_layer, + ) + ) + + return nn.Sequential(*layers) + + def _forward_impl(self, x: Tensor) -> Tensor: + # See note [TorchScript super()] + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.fc(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +class EncoderDeFMO(Module): + def __init__(self) -> None: + super().__init__() + model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50 + modelc1 = nn.Sequential(*list(model.children())[:3]) + modelc2 = nn.Sequential(*list(model.children())[4:8]) + modelc1[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) + self.net = nn.Sequential(modelc1, modelc2) + + def forward(self, input_data: Tensor) -> Tensor: + return self.net(input_data) + + +class RenderingDeFMO(Module): + def __init__(self) -> None: + super().__init__() + self.tsr_steps: int = 24 + model = nn.Sequential( + nn.Conv2d(2049, 1024, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), + nn.ReLU(inplace=True), + Bottleneck(1024, 256), + nn.PixelShuffle(2), + Bottleneck(256, 64), + nn.PixelShuffle(2), + Bottleneck(64, 16), + nn.PixelShuffle(2), + nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False), + nn.PixelShuffle(2), + nn.Conv2d(4, 4, kernel_size=3, stride=1, padding=1, bias=True), + nn.ReLU(inplace=True), + nn.Conv2d(4, 4, kernel_size=3, stride=1, padding=1, bias=True), + ) + self.net = model + self.times = torch.linspace(0, 1, self.tsr_steps) + + def forward(self, latent: Tensor) -> Tensor: + times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1) + renders = [] + for ki in range(times.shape[1]): + t_tensor = ( + times[list(range(times.shape[0])), ki] + .unsqueeze(-1) + .unsqueeze(-1) + .unsqueeze(-1) + .repeat(1, 1, latent.shape[2], latent.shape[3]) + ) + latenti = concatenate((t_tensor, latent), 1) + result = self.net(latenti) + renders.append(result) + renders_stacked = stack(renders, 1).contiguous() + renders_stacked[:, :, :4] = torch.sigmoid(renders_stacked[:, :, :4]) + return renders_stacked + + +class DeFMO(Module): + """Module that disentangle a fast-moving object from the background and performs deblurring. + + This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery + of Fast Moving Objects". See :cite:`DeFMO2021` for more details. + + Args: + pretrained: Download and set pretrained weights to the model. Default: false. + + Returns: + Temporal super-resolution without background. + Shape: + - Input: (B, 6, H, W) + - Output: (B, S, 4, H, W) + + Examples: + >>> import kornia + >>> input = torch.rand(2, 6, 240, 320) + >>> defmo = kornia.feature.DeFMO() + >>> tsr_nobgr = defmo(input) # 2x24x4x240x320 + + """ + + def __init__(self, pretrained: bool = False) -> None: + super().__init__() + self.encoder = EncoderDeFMO() + self.rendering = RenderingDeFMO() + + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url( + urls["defmo_encoder"], map_location=torch.device("cpu") + ) + self.encoder.load_state_dict(pretrained_dict, strict=True) + pretrained_dict_ren = torch.hub.load_state_dict_from_url( + urls["defmo_rendering"], map_location=torch.device("cpu") + ) + self.rendering.load_state_dict(pretrained_dict_ren, strict=True) + self.eval() + + def forward(self, input_data: Tensor) -> Tensor: + latent = self.encoder(input_data) + x_out = self.rendering(latent) + return x_out diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/disk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1803ffaf62654985ddb239f55f07c1ef4e2f446 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from .disk import DISK +from .structs import DISKFeatures diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e32db6680954112acb795b02e84b5e5105e5014f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/__init__.py @@ -0,0 +1,18 @@ +# 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. +# + +from .unet import Unet diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/blocks.py b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2db31cfb7d9c5e18b9e1643c32c3938db1c494 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/blocks.py @@ -0,0 +1,89 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core import Module, Tensor + + +class TrivialUpsample(Module): + def forward(self, x: Tensor) -> Tensor: + return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False) + + +class TrivialDownsample(Module): + def forward(self, x: Tensor) -> Tensor: + return F.avg_pool2d(x, 2) + + +class Conv(nn.Sequential): + def __init__(self, in_: int, out_: int, size: int, skip_norm_and_gate: bool = False) -> None: + norm: Module + nonl: Module + + if skip_norm_and_gate: + norm = nn.Sequential() + nonl = nn.Sequential() + else: + norm = nn.InstanceNorm2d(in_) + nonl = nn.PReLU(in_) + + dropout = nn.Sequential() + conv = nn.Conv2d(in_, out_, size, padding="same", bias=True) + + super().__init__(norm, nonl, dropout, conv) + + +class ThinUnetDownBlock(nn.Sequential): + def __init__(self, in_: int, out_: int, size: int = 5, is_first: bool = False, setup: Any = None) -> None: + self.in_ = in_ + self.out_ = out_ + + downsample: Module + if is_first: + downsample = nn.Sequential() + conv = Conv(in_, out_, size, skip_norm_and_gate=True) + else: + downsample = TrivialDownsample() + conv = Conv(in_, out_, size) + + super().__init__(downsample, conv) + + +class ThinUnetUpBlock(Module): + def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5, setup: Any = None) -> None: + super().__init__() + + self.bottom_ = bottom_ + self.horizontal_ = horizontal_ + self.cat_ = bottom_ + horizontal_ + self.out_ = out_ + + self.upsample = TrivialUpsample() + self.conv = Conv(self.cat_, self.out_, size) + + def forward(self, bot: Tensor, hor: Tensor) -> Tensor: + bot_big = self.upsample(bot) + combined = torch.cat([bot_big, hor], dim=1) + + return self.conv(combined) diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/unet.py b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..b8926adabb5ad727790a63e3408d0c4b73321bce --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/_unets/unet.py @@ -0,0 +1,86 @@ +# 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. +# + +from __future__ import annotations + +from typing import Optional + +from torch import nn + +from kornia.core import Module, Tensor + +from .blocks import ThinUnetDownBlock, ThinUnetUpBlock + + +class Unet(Module): + def __init__( + self, in_features: int = 1, up: Optional[list[int]] = None, down: Optional[list[int]] = None, size: int = 5 + ) -> None: + super().__init__() + if up is None: + up = [] + self.up = up + if down is None: + down = [] + self.down = down + if not len(down) == len(up) + 1: + raise ValueError("`down` must be 1 item longer than `up`") + + self.in_features = in_features + + down_dims = [in_features, *down] + self.path_down = nn.ModuleList() + for i, (d_in, d_out) in enumerate(zip(down_dims[:-1], down_dims[1:])): + down_block = ThinUnetDownBlock(d_in, d_out, size=size, is_first=i == 0) + self.path_down.append(down_block) + + bot_dims = [down[-1], *up] + hor_dims = down_dims[-2::-1] + self.path_up = nn.ModuleList() + for _, (d_bot, d_hor, d_out) in enumerate(zip(bot_dims, hor_dims, up)): + up_block = ThinUnetUpBlock(d_bot, d_hor, d_out, size=size) + self.path_up.append(up_block) + + self.n_params = 0 + for param in self.parameters(): + self.n_params += param.numel() + + def forward(self, inp: Tensor) -> Tensor: + if inp.size(1) != self.in_features: + fmt = "Expected {} feature channels in input, got {}" + msg = fmt.format(self.in_features, inp.size(1)) + raise ValueError(msg) + + input_size_divisor = 2 ** len(self.up) + if (inp.size(2) % input_size_divisor != 0) or (inp.size(3) % input_size_divisor != 0): + raise ValueError( + f"Input image shape must be divisible by {input_size_divisor} (got {inp.size()}). " + "This is not inherent to DISK, but to the U-Net architecture used in pretrained models. " + "Please pad if necessary." + ) + + features = [inp] + for layer in self.path_down: + features.append(layer(features[-1])) + + f_bot = features[-1] + features_horizontal = features[-2::-1] + + for layer, f_hor in zip(self.path_up, features_horizontal): + f_bot = layer(f_bot, f_hor) + + return f_bot diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/detector.py b/python_embeded/Lib/site-packages/kornia/feature/disk/detector.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9b8a4415a7b3c2095033a194ad873b55460233 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/detector.py @@ -0,0 +1,78 @@ +# 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. +# + +from __future__ import annotations + +from typing import Optional + +import torch +import torch.nn.functional as F + +from kornia.core import Tensor + +from .structs import Keypoints + + +def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor: + """Apply non-maximum suppression.""" + if window_size % 2 != 1: + raise ValueError(f"window_size has to be odd, got {window_size}") + + _, ixs = F.max_pool2d(signal, kernel_size=window_size, stride=1, padding=window_size // 2, return_indices=True) + + h, w = signal.shape[1:] + coords = torch.arange(h * w, device=signal.device).reshape(1, h, w) + nms = ixs == coords + + if cutoff is None: + return nms + else: + return nms & (signal > cutoff) + + +def heatmap_to_keypoints( + heatmap: Tensor, n: Optional[int] = None, window_size: int = 5, score_threshold: float = 0.0 +) -> list[Keypoints]: + """Inference-time nms-based detection protocol.""" + heatmap = heatmap.squeeze(1) + nmsed = nms(heatmap, window_size=window_size, cutoff=score_threshold) + + keypoints = [] + for b in range(heatmap.shape[0]): + yx = nmsed[b].nonzero(as_tuple=False) + detection_logp = heatmap[b][nmsed[b]] + xy = yx.flip((1,)) + + if n is not None: + n_ = min(n + 1, detection_logp.numel()) + # torch.kthvalue picks in ascending order and we want to pick in + # descending order, so we pick n-th smallest among -logp to get + # -threshold + minus_threshold, _indices = torch.kthvalue(-detection_logp, n_) + mask = detection_logp > -minus_threshold + + xy = xy[mask] + detection_logp = detection_logp[mask] + + # it may be that due to numerical saturation on the threshold we have + # more than n keypoints, so we need to clip them + xy = xy[:n] + detection_logp = detection_logp[:n] + + keypoints.append(Keypoints(xy, detection_logp)) + + return keypoints diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/disk.py b/python_embeded/Lib/site-packages/kornia/feature/disk/disk.py new file mode 100644 index 0000000000000000000000000000000000000000..ec380f8b83dfddb337de8278412e24dd99f0376a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/disk.py @@ -0,0 +1,161 @@ +# 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. +# + +from __future__ import annotations + +from typing import Optional + +import torch + +from kornia.core import Module, Tensor + +from ._unets import Unet +from .detector import heatmap_to_keypoints +from .structs import DISKFeatures + + +class DISK(Module): + r"""Module which detects and described local features in an image using the DISK method. + + See :cite:`tyszkiewicz2020disk` for details. + + .. image:: _static/img/disk_outdoor_depth.jpg + + Args: + desc_dim: The dimension of the descriptor. + unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK + so this is only useful when using a custom checkpoint trained using the code released with the paper. + The unet should take as input a tensor of shape :math:`(B, C, H, W)` and output a tensor of shape + :math:`(B, \mathrm{desc\_dim} + 1, H, W)`. + + Example: + >>> disk = DISK.from_pretrained('depth') + >>> images = torch.rand(1, 3, 256, 256) + >>> features = disk(images) + + """ + + def __init__(self, desc_dim: int = 128, unet: None | Module = None) -> None: + super().__init__() + + self.desc_dim = desc_dim + + if unet is None: + unet = Unet(in_features=3, size=5, down=[16, 32, 64, 64, 64], up=[64, 64, 64, desc_dim + 1]) + self.unet = unet + + def heatmap_and_dense_descriptors(self, images: Tensor) -> tuple[Tensor, Tensor]: + """Return the heatmap and the dense descriptors. + + .. image:: _static/img/DISK.png + + Args: + images: The image to detect features in. Shape :math:`(B, 3, H, W)`. + + Returns: + A tuple of dense detection scores and descriptors. + Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, where + :math:`D` is the descriptor dimension. + + """ + unet_output = self.unet(images) + + if unet_output.shape[1] != self.desc_dim + 1: + raise ValueError( + f"U-Net output has {unet_output.shape[1]} channels, but expected self.desc_dim={self.desc_dim} + 1." + ) + + descriptors = unet_output[:, : self.desc_dim] + heatmaps = unet_output[:, self.desc_dim :] + + return heatmaps, descriptors + + def forward( + self, + images: Tensor, + n: Optional[int] = None, + window_size: int = 5, + score_threshold: float = 0.0, + pad_if_not_divisible: bool = False, + ) -> list[DISKFeatures]: + """Detect features in an image, returning keypoint locations, descriptors and detection scores. + + Args: + images: The image to detect features in. Shape :math:`(B, 3, H, W)`. + n: The maximum number of keypoints to detect. If None, all keypoints are returned. + window_size: The size of the non-maxima suppression window used to filter detections. + score_threshold: The minimum score a detection must have to be returned. + See :py:class:`DISKFeatures` for details. + pad_if_not_divisible: if True, the non-16 divisible input is zero-padded to the closest 16-multiply + + Returns: + A list of length :math:`B` containing the detected features. + + """ + B = images.shape[0] + if pad_if_not_divisible: + h, w = images.shape[2:] + pd_h = 16 - h % 16 if h % 16 > 0 else 0 + pd_w = 16 - w % 16 if w % 16 > 0 else 0 + images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0) + + heatmaps, descriptors = self.heatmap_and_dense_descriptors(images) + if pad_if_not_divisible: + heatmaps = heatmaps[..., :h, :w] + descriptors = descriptors[..., :h, :w] + + keypoints = heatmap_to_keypoints(heatmaps, n=n, window_size=window_size, score_threshold=score_threshold) + + features = [] + for i in range(B): + features.append(keypoints[i].merge_with_descriptors(descriptors[i])) + + return features + + @classmethod + def from_pretrained(cls, checkpoint: str = "depth", device: Optional[torch.device] = None) -> DISK: + r"""Load a pretrained model. + + Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints + only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and + is less precise but detects keypoints everywhere where they are matchable. The difference is especially + pronounced on thin structures and on edges of objects. + + Args: + checkpoint: The checkpoint to load. One of 'depth' or 'epipolar'. + device: The device to load the model to. + + Returns: + The pretrained model. + + """ + urls = { + "depth": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth", + "epipolar": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth", + } + + if checkpoint not in urls: + raise ValueError(f"Unknown pretrained model: {checkpoint}") + + if device is None: + device = torch.device("cpu") + pretrained_dict = torch.hub.load_state_dict_from_url(urls[checkpoint], map_location=device) + + model: DISK = cls().to(device) + model.load_state_dict(pretrained_dict["extractor"]) + model.eval() + return model diff --git a/python_embeded/Lib/site-packages/kornia/feature/disk/structs.py b/python_embeded/Lib/site-packages/kornia/feature/disk/structs.py new file mode 100644 index 0000000000000000000000000000000000000000..944acb3c6200b95aeba5687707d81db9ad1dd5c8 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/disk/structs.py @@ -0,0 +1,102 @@ +# 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. +# + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +import torch.nn.functional as F + +from kornia.core import Device, Tensor + + +@dataclass +class DISKFeatures: + r"""A data structure holding DISK keypoints, descriptors and detection scores for an image. + + Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched. + + Args: + keypoints: Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints. + descriptors: Tensor of shape :math:`(N, D)`, where :math:`D` is the descriptor dimension. + detection_scores: Tensor of shape :math:`(N,)` where the detection score can be interpreted as + the log-probability of keeping a keypoint after it has been proposed (see the paper + section *Method → Feature distribution* for details). + + """ + + keypoints: Tensor + descriptors: Tensor + detection_scores: Tensor + + @property + def n(self) -> int: + return self.keypoints.shape[0] + + @property + def device(self) -> Device: + return self.keypoints.device + + @property + def x(self) -> Tensor: + """Accesses the x coordinates of keypoints (along image width).""" + return self.keypoints[:, 0] + + @property + def y(self) -> Tensor: + """Accesses the y coordinates of keypoints (along image height).""" + return self.keypoints[:, 1] + + def to(self, *args: Any, **kwargs: Any) -> DISKFeatures: + """Call :func:`torch.Tensor.to` on each tensor to move the keypoints, descriptors and detection scores to + the specified device and/or data type. + + Args: + *args: Arguments passed to :func:`torch.Tensor.to`. + **kwargs: Keyword arguments passed to :func:`torch.Tensor.to`. + + Returns: + A new DISKFeatures object with tensors of appropriate type and location. + + """ # noqa:D205 + return DISKFeatures( + self.keypoints.to(*args, **kwargs), + self.descriptors.to(*args, **kwargs), + self.detection_scores.to(*args, **kwargs), + ) + + +@dataclass +class Keypoints: + """A temporary struct used to store keypoint detections and their log-probabilities. + + After construction, merge_with_descriptors is used to select corresponding descriptors from unet output. + """ + + xys: Tensor + detection_logp: Tensor + + def merge_with_descriptors(self, descriptors: Tensor) -> DISKFeatures: + """Select descriptors from a dense `descriptors` tensor, at locations given by `self.xys`.""" + dtype = descriptors.dtype + x, y = self.xys.T + + desc = descriptors[:, y, x].T + desc = F.normalize(desc, dim=-1) + + return DISKFeatures(self.xys.to(dtype), desc, self.detection_logp) diff --git a/python_embeded/Lib/site-packages/kornia/feature/hardnet.py b/python_embeded/Lib/site-packages/kornia/feature/hardnet.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa958e738b2e8efa9d405689bb04be9856fe226 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/hardnet.py @@ -0,0 +1,204 @@ +# 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. +# + +from typing import Dict + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core.check import KORNIA_CHECK_SHAPE +from kornia.utils.helpers import is_mps_tensor_safe + +urls: Dict[str, str] = {} +urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth" +urls["liberty_aug"] = ( + "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" +) +urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt" + + +class HardNet(nn.Module): + r"""Module, which computes HardNet descriptors of given grayscale patches of 32x32. + + This is based on the original code from paper "Working hard to know your neighbor's + margins: Local descriptor learning loss". See :cite:`HardNet2017` for more details. + + Args: + pretrained: Download and set pretrained weights to the model. + + Returns: + torch.Tensor: HardNet descriptor of the patches. + + Shape: + - Input: :math:`(B, 1, 32, 32)` + - Output: :math:`(B, 128)` + + Examples: + >>> input = torch.rand(16, 1, 32, 32) + >>> hardnet = HardNet() + >>> descs = hardnet(input) # 16x128 + + """ + + patch_size = 32 + + def __init__(self, pretrained: bool = False) -> None: + super().__init__() + self.features = nn.Sequential( + nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 32, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(128, affine=False), + nn.ReLU(), + nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(128, affine=False), + nn.ReLU(), + nn.Dropout(0.3), + nn.Conv2d(128, 128, kernel_size=8, bias=False), + nn.BatchNorm2d(128, affine=False), + ) + + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty_aug"], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict["state_dict"], strict=True) + self.eval() + + @staticmethod + def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: + """Normalize the input by batch.""" + if not is_mps_tensor_safe(x): + sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True) + else: + mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True) + sp = torch.std(x, dim=(-3, -2, -1), keepdim=True) + # WARNING: we need to .detach() input, otherwise the gradients produced by + # the patches extractor with F.grid_sample are very noisy, making the detector + # training totally unstable. + return (x - mp.detach()) / (sp.detach() + eps) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"]) + x_norm: torch.Tensor = self._normalize_input(input) + x_features: torch.Tensor = self.features(x_norm) + x_out = x_features.view(x_features.size(0), -1) + return F.normalize(x_out, dim=1) + + +class HardNet8(nn.Module): + r"""Module, which computes HardNet8 descriptors of given grayscale patches of 32x32. + + This is based on the original code from paper "Improving the HardNet Descriptor". + See :cite:`HardNet2020` for more details. + + Args: + pretrained: Download and set pretrained weights to the model. + + Returns: + torch.Tensor: HardNet8 descriptor of the patches. + + Shape: + - Input: :math:`(B, 1, 32, 32)` + - Output: :math:`(B, 128)` + + Examples: + >>> input = torch.rand(16, 1, 32, 32) + >>> hardnet = HardNet8() + >>> descs = hardnet(input) # 16x128 + + """ + + patch_size = 32 + + def __init__(self, pretrained: bool = False) -> None: + super().__init__() + self.features = nn.Sequential( + nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 32, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(128, affine=False), + nn.ReLU(), + nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(128, affine=False), + nn.ReLU(), + nn.Conv2d(128, 256, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(256, affine=False), + nn.ReLU(), + nn.Dropout(0.3), + nn.Conv2d(256, 512, kernel_size=8, bias=False), + nn.BatchNorm2d(512, affine=False), + ) + self.features.apply(self.weights_init) + self.register_buffer("components", torch.ones(512, 128, dtype=torch.float)) + self.register_buffer("mean", torch.zeros(512, dtype=torch.float)) + + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["hardnet8v2"], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict, strict=True) + self.eval() + + @staticmethod + def weights_init(m: object) -> None: + if isinstance(m, nn.Conv2d): + nn.init.orthogonal_(m.weight.data, gain=0.6) + if m.bias is not None: + nn.init.constant_(m.bias.data, 0.01) + + @staticmethod + def _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: + """Normalize the input by batch.""" + if not is_mps_tensor_safe(x): + sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True) + else: + mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True) + sp = torch.std(x, dim=(-3, -2, -1), keepdim=True) + # WARNING: we need to .detach() input, otherwise the gradients produced by + # the patches extractor with F.grid_sample are very noisy, making the detector + # training totally unstable. + return (x - mp.detach()) / (sp.detach() + eps) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"]) + x_norm: torch.Tensor = self._normalize_input(input) + x_features: torch.Tensor = self.features(x_norm) + mean: torch.Tensor = torch.jit.annotate(torch.Tensor, self.mean) + components: torch.Tensor = torch.jit.annotate(torch.Tensor, self.components) + x_prePCA = F.normalize(x_features.view(x_features.size(0), -1)) + pca = torch.mm(x_prePCA - mean, components) + return F.normalize(pca, dim=1) diff --git a/python_embeded/Lib/site-packages/kornia/feature/hynet.py b/python_embeded/Lib/site-packages/kornia/feature/hynet.py new file mode 100644 index 0000000000000000000000000000000000000000..5fda81ca10a9e75129acea7fc580448a99cc65be --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/hynet.py @@ -0,0 +1,245 @@ +# 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. +# + +from typing import Dict + +import torch +from torch import nn + +from kornia.core import Module, Parameter, Tensor, tensor, zeros + +urls: Dict[str, str] = {} +urls["liberty"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth" # pylint: disable +urls["notredame"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth" # pylint: disable +urls["yosemite"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable + + +class FilterResponseNorm2d(Module): + r"""Feature Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence + in the Training of Deep Neural Networks', see :cite:`FRN2019` for more details. + + .. math:: + y = \gamma \times \frac{x}{\sqrt{\mathrm{E}[x^2]} + |\epsilon|} + \beta + + + Args: + num_features: number of channels + eps: normalization constant + is_bias: use bias + is_scale: use scale + drop_rate: dropout rate, + is_eps_leanable: if eps is learnable + + Returns: + torch.Tensor: Normalized features + + Shape: + - Input: :math:`(B, \text{num_features}, H, W)` + - Output: :math:`(B, \text{num_features}, H, W)` + + """ # noqa: D205 + + def __init__( + self, + num_features: int, + eps: float = 1e-6, + is_bias: bool = True, + is_scale: bool = True, + is_eps_leanable: bool = False, + ) -> None: + super().__init__() + + self.num_features = num_features + self.init_eps = eps + self.is_eps_leanable = is_eps_leanable + self.is_bias = is_bias + self.is_scale = is_scale + + self.weight = Parameter(torch.ones(1, num_features, 1, 1), requires_grad=True) + self.bias = Parameter(zeros(1, num_features, 1, 1), requires_grad=True) + if is_eps_leanable: + self.eps = Parameter(tensor(1), requires_grad=True) + else: + self.register_buffer("eps", tensor([eps])) + self.reset_parameters() + + def reset_parameters(self) -> None: + nn.init.ones_(self.weight) + nn.init.zeros_(self.bias) + if self.is_eps_leanable: + nn.init.constant_(self.eps, self.init_eps) + + def extra_repr(self) -> str: + return "num_features={num_features}, eps={init_eps}".format(**self.__dict__) + + def forward(self, x: Tensor) -> Tensor: + # Compute the mean norm of activations per channel. + nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True) + + # Perform FRN. + x = x * torch.rsqrt(nu2 + self.eps.abs()) + + # Scale and Bias + if self.is_scale: + x = self.weight * x + if self.is_bias: + x = x + self.bias + return x + + +class TLU(Module): + r"""TLU layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep + Neural Networks, see :cite:`FRN2019` for more details. :math:`{\tau}` is learnable per channel. + + .. math:: + y = \max(x, {\tau}) + + Args: + num_features: number of channels + + Returns: + torch.Tensor + + Shape: + - Input: :math:`(B, \text{num_features}, H, W)` + - Output: :math:`(B, \text{num_features}, H, W)` + + """ # noqa:D205 + + def __init__(self, num_features: int) -> None: + """max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau.""" + super().__init__() + self.num_features = num_features + self.tau = Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True) + self.reset_parameters() + + def reset_parameters(self) -> None: + # nn.init.zeros_(self.tau) + nn.init.constant_(self.tau, -1) + + def extra_repr(self) -> str: + return "num_features={num_features}".format(**self.__dict__) + + def forward(self, x: Tensor) -> Tensor: + return torch.max(x, self.tau) + + +class HyNet(Module): + r"""Module, which computes HyNet descriptors of given grayscale patches of 32x32. + + This is based on the original code from paper + "HyNet: Learning Local Descriptor with Hybrid Similarity Measure and Triplet Loss". + See :cite:`hynet2020` for more details. + + Args: + pretrained: Download and set pretrained weights to the model. + is_bias: use bias in TLU layers + is_bias_FRN: use bias in FRN layers + dim_desc: descriptor dimensionality, + drop_rate: dropout rate, + eps_l2_norm: to avoid div by zero + + Returns: + HyNet descriptor of the patches. + + Shape: + - Input: :math:`(B, 1, 32, 32)` + - Output: :math:`(B, 128)` + + Examples: + >>> input = torch.rand(16, 1, 32, 32) + >>> hynet = HyNet() + >>> descs = hynet(input) # 16x128 + + """ + + patch_size = 32 + + def __init__( + self, + pretrained: bool = False, + is_bias: bool = True, + is_bias_FRN: bool = True, + dim_desc: int = 128, + drop_rate: float = 0.3, + eps_l2_norm: float = 1e-10, + ) -> None: + super().__init__() + self.eps_l2_norm = eps_l2_norm + self.dim_desc = dim_desc + self.drop_rate = drop_rate + self.layer1 = nn.Sequential( + FilterResponseNorm2d(1, is_bias=is_bias_FRN), + TLU(1), + nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=is_bias), + FilterResponseNorm2d(32, is_bias=is_bias_FRN), + TLU(32), + ) + + self.layer2 = nn.Sequential( + nn.Conv2d(32, 32, kernel_size=3, padding=1, bias=is_bias), + FilterResponseNorm2d(32, is_bias=is_bias_FRN), + TLU(32), + ) + + self.layer3 = nn.Sequential( + nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=is_bias), + FilterResponseNorm2d(64, is_bias=is_bias_FRN), + TLU(64), + ) + + self.layer4 = nn.Sequential( + nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=is_bias), + FilterResponseNorm2d(64, is_bias=is_bias_FRN), + TLU(64), + ) + self.layer5 = nn.Sequential( + nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=is_bias), + FilterResponseNorm2d(128, is_bias=is_bias_FRN), + TLU(128), + ) + + self.layer6 = nn.Sequential( + nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=is_bias), + FilterResponseNorm2d(128, is_bias=is_bias_FRN), + TLU(128), + ) + + self.layer7 = nn.Sequential( + nn.Dropout(self.drop_rate), + nn.Conv2d(128, self.dim_desc, kernel_size=8, bias=False), + nn.BatchNorm2d(self.dim_desc, affine=False), + ) + + self.desc_norm = nn.LocalResponseNorm(2 * self.dim_desc, 2.0 * self.dim_desc, 0.5, 0.0) + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict, strict=True) + self.eval() + + def forward(self, x: Tensor) -> Tensor: + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.layer5(x) + x = self.layer6(x) + x = self.layer7(x) + x = self.desc_norm(x + self.eps_l2_norm) + x = x.view(x.size(0), -1) + return x diff --git a/python_embeded/Lib/site-packages/kornia/feature/integrated.py b/python_embeded/Lib/site-packages/kornia/feature/integrated.py new file mode 100644 index 0000000000000000000000000000000000000000..1c26856adb3afe6b15d170826b782536832d8257 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/integrated.py @@ -0,0 +1,547 @@ +# 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. +# + +import warnings +from typing import ClassVar, Dict, List, Optional, Tuple + +import torch + +from kornia.color import rgb_to_grayscale +from kornia.constants import pi +from kornia.core import Device, Module, Tensor, concatenate, deg2rad +from kornia.core.check import KORNIA_CHECK_LAF +from kornia.geometry.subpix import ConvQuadInterp3d +from kornia.geometry.transform import ScalePyramid + +from .affine_shape import LAFAffNetShapeEstimator +from .hardnet import HardNet +from .keynet import KeyNetDetector +from .laf import extract_patches_from_pyramid, get_laf_center, get_laf_orientation, get_laf_scale, scale_laf +from .lightglue import LightGlue +from .matching import GeometryAwareDescriptorMatcher, _no_match +from .orientation import LAFOrienter, OriNet, PassLAF +from .responses import BlobDoG, BlobDoGSingle, BlobHessian, CornerGFTT +from .scale_space_detector import ( + Detector_config, + MultiResolutionDetector, + ScaleSpaceDetector, + get_default_detector_config, +) +from .siftdesc import SIFTDescriptor + + +def get_laf_descriptors( + img: Tensor, lafs: Tensor, patch_descriptor: Module, patch_size: int = 32, grayscale_descriptor: bool = True +) -> Tensor: + r"""Get local descriptors, corresponding to LAFs (keypoints). + + Args: + img: image features with shape :math:`(B,C,H,W)`. + lafs: local affine frames :math:`(B,N,2,3)`. + patch_descriptor: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor` + or :class:`~kornia.feature.HardNet`. + patch_size: patch size in pixels, which descriptor expects. + grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image. + + Returns: + Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size. + + """ + KORNIA_CHECK_LAF(lafs) + patch_descriptor = patch_descriptor.to(img) + patch_descriptor.eval() + + timg: Tensor = img + if lafs.shape[1] == 0: + warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty tensor", stacklevel=1) + return torch.empty(lafs.shape[0], lafs.shape[1], 128, dtype=lafs.dtype, device=lafs.device) + if grayscale_descriptor and img.size(1) == 3: + timg = rgb_to_grayscale(img) + + patches: Tensor = extract_patches_from_pyramid(timg, lafs, patch_size) + # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape + # So we need to reshape a bit :) + B, N, CH, H, W = patches.size() + return patch_descriptor(patches.view(B * N, CH, H, W)).view(B, N, -1) + + +class LAFDescriptor(Module): + r"""Module to get local descriptors, corresponding to LAFs (keypoints). + + Internally uses :func:`~kornia.feature.get_laf_descriptors`. + + Args: + patch_descriptor_module: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor` + or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet`. + patch_size: patch size in pixels, which descriptor expects. + grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image. + + """ + + def __init__( + self, patch_descriptor_module: Optional[Module] = None, patch_size: int = 32, grayscale_descriptor: bool = True + ) -> None: + super().__init__() + if patch_descriptor_module is None: + patch_descriptor_module = HardNet(True) + self.descriptor = patch_descriptor_module + self.patch_size = patch_size + self.grayscale_descriptor = grayscale_descriptor + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(descriptor={self.descriptor.__repr__()}, " + f"patch_size={self.patch_size}, " + f"grayscale_descriptor='{self.grayscale_descriptor})" + ) + + def forward(self, img: Tensor, lafs: Tensor) -> Tensor: + r"""Three stage local feature detection. + + First the location and scale of interest points are determined by + detect function. Then affine shape and orientation. + + Args: + img: image features with shape :math:`(B,C,H,W)`. + lafs: local affine frames :math:`(B,N,2,3)`. + + Returns: + Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size. + + """ + return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor) + + +class LocalFeature(Module): + """Module, which combines local feature detector and descriptor. + + Args: + detector: the detection module. + descriptor: the descriptor module. + scaling_coef: multiplier for change default detector scale (e.g. it is too small for KeyNet by default) + + """ + + def __init__(self, detector: Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None: + super().__init__() + self.detector = detector + self.descriptor = descriptor + if scaling_coef <= 0: + raise ValueError(f"Scaling coef should be >= 0, got {scaling_coef}") + self.scaling_coef = scaling_coef + + def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]: + """Run forward. + + Args: + img: image to extract features with shape :math:`(B,C,H,W)`. + mask: a mask with weights where to apply the response function. + The shape must be the same as the input image. + + Returns: + - Detected local affine frames with shape :math:`(B,N,2,3)`. + - Response function values for corresponding lafs with shape :math:`(B,N,1)`. + - Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size. + + """ + lafs, responses = self.detector(img, mask) + lafs = scale_laf(lafs, self.scaling_coef) + descs = self.descriptor(img, lafs) + return (lafs, responses, descs) + + +class SIFTFeature(LocalFeature): + """Convenience module, which implements DoG detector + (Root)SIFT descriptor. + + Using `kornia.feature.MultiResolutionDetector` without blur pyramid Still not as good as OpenCV/VLFeat because of + https://github.com/kornia/kornia/pull/884, + but we are working on it + """ + + def __init__( + self, + num_features: int = 8000, + upright: bool = False, + rootsift: bool = True, + device: Optional[Device] = None, + config: Optional[Detector_config] = None, + ) -> None: + patch_size: int = 41 + if device is None: + device = torch.device("cpu") + if config is None: + config = get_default_detector_config() + detector = MultiResolutionDetector( + BlobDoGSingle(1.0, 1.6), + num_features, + config, + ori_module=PassLAF() if upright else LAFOrienter(19), + aff_module=PassLAF(), + ).to(device) + descriptor = LAFDescriptor( + SIFTDescriptor(patch_size=patch_size, rootsift=rootsift), patch_size=patch_size, grayscale_descriptor=True + ).to(device) + super().__init__(detector, descriptor) + + +class SIFTFeatureScaleSpace(LocalFeature): + """Convenience module, which implements DoG detector + (Root)SIFT descriptor. + + Using `kornia.feature.ScaleSpaceDetector` with blur pyramid. + + Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it + """ + + def __init__( + self, + num_features: int = 8000, + upright: bool = False, + rootsift: bool = True, + device: Optional[Device] = None, + ) -> None: + if device is None: + device = torch.device("cpu") + patch_size: int = 41 + detector = ScaleSpaceDetector( + num_features, + resp_module=BlobDoG(), + nms_module=ConvQuadInterp3d(10), + scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True), + ori_module=PassLAF() if upright else LAFOrienter(19), + scale_space_response=True, + minima_are_also_good=True, + mr_size=6.0, + ).to(device) + descriptor = LAFDescriptor( + SIFTDescriptor(patch_size=patch_size, rootsift=rootsift), patch_size=patch_size, grayscale_descriptor=True + ).to(device) + super().__init__(detector, descriptor) + + +class GFTTAffNetHardNet(LocalFeature): + """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor.""" + + def __init__( + self, + num_features: int = 8000, + upright: bool = False, + device: Optional[Device] = None, + config: Optional[Detector_config] = None, + ) -> None: + if device is None: + device = torch.device("cpu") + if config is None: + config = get_default_detector_config() + detector = MultiResolutionDetector( + CornerGFTT(), + num_features, + config, + ori_module=PassLAF() if upright else LAFOrienter(19), + aff_module=LAFAffNetShapeEstimator(True).eval(), + ).to(device) + descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device) + super().__init__(detector, descriptor) + + +class HesAffNetHardNet(LocalFeature): + """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor.""" + + def __init__( + self, + num_features: int = 2048, + upright: bool = False, + device: Optional[Device] = None, + config: Optional[Detector_config] = None, + ) -> None: + if device is None: + device = torch.device("cpu") + if config is None: + config = get_default_detector_config() + detector = MultiResolutionDetector( + BlobHessian(), + num_features, + config, + ori_module=PassLAF() if upright else LAFOrienter(19), + aff_module=LAFAffNetShapeEstimator(True).eval(), + ).to(device) + descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device) + super().__init__(detector, descriptor) + + +class KeyNetHardNet(LocalFeature): + """Convenience module, which implements KeyNet detector + HardNet descriptor.""" + + def __init__( + self, + num_features: int = 8000, + upright: bool = False, + device: Optional[Device] = None, + scale_laf: float = 1.0, + ) -> None: + if device is None: + device = torch.device("cpu") + ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True)) + detector = KeyNetDetector(True, num_features=num_features, ori_module=ori_module).to(device) + descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device) + super().__init__(detector, descriptor, scale_laf) + + +class KeyNetAffNetHardNet(LocalFeature): + """Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor. + + .. image:: _static/img/keynet_affnet.jpg + """ + + def __init__( + self, + num_features: int = 8000, + upright: bool = False, + device: Optional[Device] = None, + scale_laf: float = 1.0, + ) -> None: + if device is None: + device = torch.device("cpu") + ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True)) + detector = KeyNetDetector( + True, num_features=num_features, ori_module=ori_module, aff_module=LAFAffNetShapeEstimator(True).eval() + ).to(device) + descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device) + super().__init__(detector, descriptor, scale_laf) + + +class LocalFeatureMatcher(Module): + r"""Module, which finds correspondences between two images based on local features. + + Args: + local_feature: Local feature detector. See :class:`~kornia.feature.GFTTAffNetHardNet`. + matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`. + + Returns: + Dict[str, Tensor]: Dictionary with image correspondences and confidence scores. + + Example: + >>> img1 = torch.rand(1, 1, 320, 200) + >>> img2 = torch.rand(1, 1, 128, 128) + >>> input = {"image0": img1, "image1": img2} + >>> gftt_hardnet_matcher = LocalFeatureMatcher( + ... GFTTAffNetHardNet(10), kornia.feature.DescriptorMatcher('snn', 0.8) + ... ) + >>> out = gftt_hardnet_matcher(input) + + """ + + def __init__(self, local_feature: Module, matcher: Module) -> None: + super().__init__() + self.local_feature = local_feature + self.matcher = matcher + self.eval() + + def extract_features(self, image: Tensor, mask: Optional[Tensor] = None) -> Dict[str, Tensor]: + """Extract features from simple image.""" + lafs0, resps0, descs0 = self.local_feature(image, mask) + return {"lafs": lafs0, "responses": resps0, "descriptors": descs0} + + def no_match_output(self, device: Device, dtype: torch.dtype) -> Dict[str, Tensor]: + return { + "keypoints0": torch.empty(0, 2, device=device, dtype=dtype), + "keypoints1": torch.empty(0, 2, device=device, dtype=dtype), + "lafs0": torch.empty(0, 0, 2, 3, device=device, dtype=dtype), + "lafs1": torch.empty(0, 0, 2, 3, device=device, dtype=dtype), + "confidence": torch.empty(0, device=device, dtype=dtype), + "batch_indexes": torch.empty(0, device=device, dtype=torch.long), + } + + def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]: + """Run forward. + + Args: + data: dictionary containing the input data in the following format: + + Keyword Args: + image0: left image with shape :math:`(N, 1, H1, W1)`. + image1: right image with shape :math:`(N, 1, H2, W2)`. + mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`. + mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`. + + Returns: + - ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`. + - ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`. + - ``confidence``, confidence score [0, 1] :math:`(NC)`. + - ``lafs0``, matching LAFs from image0 :math:`(1, NC, 2, 3)`. + - ``lafs1``, matching LAFs from image1 :math:`(1, NC, 2, 3)`. + - ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`. + + """ + num_image_pairs: int = data["image0"].shape[0] + + if ("lafs0" not in data.keys()) or ("descriptors0" not in data.keys()): + # One can supply pre-extracted local features + feats_dict0: Dict[str, Tensor] = self.extract_features(data["image0"]) + lafs0, descs0 = feats_dict0["lafs"], feats_dict0["descriptors"] + else: + lafs0, descs0 = data["lafs0"], data["descriptors0"] + + if ("lafs1" not in data.keys()) or ("descriptors1" not in data.keys()): + feats_dict1: Dict[str, Tensor] = self.extract_features(data["image1"]) + lafs1, descs1 = feats_dict1["lafs"], feats_dict1["descriptors"] + else: + lafs1, descs1 = data["lafs1"], data["descriptors1"] + + keypoints0: Tensor = get_laf_center(lafs0) + keypoints1: Tensor = get_laf_center(lafs1) + + out_keypoints0: List[Tensor] = [] + out_keypoints1: List[Tensor] = [] + out_confidence: List[Tensor] = [] + out_batch_indexes: List[Tensor] = [] + out_lafs0: List[Tensor] = [] + out_lafs1: List[Tensor] = [] + + for batch_idx in range(num_image_pairs): + dists, idxs = self.matcher(descs0[batch_idx], descs1[batch_idx]) + if len(idxs) == 0: + continue + + current_keypoints_0 = keypoints0[batch_idx, idxs[:, 0]] + current_keypoints_1 = keypoints1[batch_idx, idxs[:, 1]] + current_lafs_0 = lafs0[batch_idx, idxs[:, 0]] + current_lafs_1 = lafs1[batch_idx, idxs[:, 1]] + + out_confidence.append(1.0 - dists) + batch_idxs = batch_idx * torch.ones(len(dists), device=keypoints0.device, dtype=torch.long) + out_keypoints0.append(current_keypoints_0) + out_keypoints1.append(current_keypoints_1) + out_lafs0.append(current_lafs_0) + out_lafs1.append(current_lafs_1) + out_batch_indexes.append(batch_idxs) + + if len(out_batch_indexes) == 0: + return self.no_match_output(data["image0"].device, data["image0"].dtype) + + return { + "keypoints0": concatenate(out_keypoints0, dim=0).view(-1, 2), + "keypoints1": concatenate(out_keypoints1, dim=0).view(-1, 2), + "lafs0": concatenate(out_lafs0, dim=0).view(1, -1, 2, 3), + "lafs1": concatenate(out_lafs1, dim=0).view(1, -1, 2, 3), + "confidence": concatenate(out_confidence, dim=0).view(-1), + "batch_indexes": concatenate(out_batch_indexes, dim=0).view(-1), + } + + +class LightGlueMatcher(GeometryAwareDescriptorMatcher): + """LightGlue-based matcher in kornia API. + + This is based on the original code from paper "LightGlue: Local Feature Matching at Light Speed". + See :cite:`LightGlue2023` for more details. + + Args: + feature_name: type of feature for matching, can be `disk` or `superpoint`. + params: LightGlue params. + + """ + + known_modes: ClassVar[List[str]] = [ + "aliked", + "dedodeb", + "dedodeg", + "disk", + "dog_affnet_hardnet", + "doghardnet", + "keynet_affnet_hardnet", + "sift", + "superpoint", + ] + + def __init__(self, feature_name: str = "disk", params: Optional[Dict] = None) -> None: # type: ignore + feature_name_: str = feature_name.lower() + super().__init__(feature_name_) + self.feature_name = feature_name_ + if params is None: + params = {} + self.params = params + self.matcher = LightGlue(self.feature_name, **params) + + def forward( + self, + desc1: Tensor, + desc2: Tensor, + lafs1: Tensor, + lafs2: Tensor, + hw1: Optional[Tuple[int, int]] = None, + hw2: Optional[Tuple[int, int]] = None, + ) -> Tuple[Tensor, Tensor]: + """Run forward. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`. + lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`. + hw1: Height/width of image. + hw2: Height/width of image. + + Return: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, + shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`. + + """ + if (desc1.shape[0] < 2) or (desc2.shape[0] < 2): + return _no_match(desc1) + keypoints1 = get_laf_center(lafs1) + keypoints2 = get_laf_center(lafs2) + if len(desc1.shape) == 2: + desc1 = desc1.unsqueeze(0) + if len(desc2.shape) == 2: + desc2 = desc2.unsqueeze(0) + dev = lafs1.device + if hw1 is None: + hw1_ = keypoints1.max(dim=1)[0].squeeze().flip(0) + else: + hw1_ = torch.tensor(hw1, device=dev) + if hw2 is None: + hw2_ = keypoints2.max(dim=1)[0].squeeze().flip(0) + else: + hw2_ = torch.tensor(hw2, device=dev) + ori0 = deg2rad(get_laf_orientation(lafs1).reshape(1, -1)) + ori0[ori0 < 0] += 2.0 * pi + ori1 = deg2rad(get_laf_orientation(lafs2).reshape(1, -1)) + ori1[ori1 < 0] += 2.0 * pi + input_dict = { + "image0": { + "keypoints": keypoints1, + "scales": get_laf_scale(lafs1).reshape(1, -1), + "oris": ori0, + "lafs": lafs1, + "descriptors": desc1, + "image_size": hw1_.flip(0).reshape(-1, 2).to(dev), + }, + "image1": { + "keypoints": keypoints2, + "lafs": lafs2, + "scales": get_laf_scale(lafs2).reshape(1, -1), + "oris": ori1, + "descriptors": desc2, + "image_size": hw2_.flip(0).reshape(-1, 2).to(dev), + }, + } + pred = self.matcher(input_dict) + matches0, mscores0 = pred["matches0"], pred["matching_scores0"] + valid = matches0 > -1 + matches = torch.stack([torch.where(valid)[1], matches0[valid]], -1) + return mscores0[valid].reshape(-1, 1), matches diff --git a/python_embeded/Lib/site-packages/kornia/feature/keynet.py b/python_embeded/Lib/site-packages/kornia/feature/keynet.py new file mode 100644 index 0000000000000000000000000000000000000000..b22a0a29e4be7f1369a9bd08668f2028cd32823c --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/keynet.py @@ -0,0 +1,213 @@ +# 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. +# + +from typing import List, Optional + +import torch +import torch.nn.functional as F +from torch import nn +from typing_extensions import TypedDict + +from kornia.core import Module, Tensor, concatenate +from kornia.filters import SpatialGradient +from kornia.geometry.transform import pyrdown + +from .scale_space_detector import Detector_config, MultiResolutionDetector, get_default_detector_config + + +class KeyNet_conf(TypedDict): + num_filters: int + num_levels: int + kernel_size: int + Detector_conf: Detector_config + + +keynet_default_config: KeyNet_conf = { + # Key.Net Model + "num_filters": 8, + "num_levels": 3, + "kernel_size": 5, + # Extraction Parameters + "Detector_conf": get_default_detector_config(), +} + +KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth" + + +class _FeatureExtractor(Module): + """Helper class for KeyNet. + + It loads both, the handcrafted and learnable blocks + """ + + def __init__(self) -> None: + super().__init__() + + self.hc_block = _HandcraftedBlock() + self.lb_block = _LearnableBlock() + + def forward(self, x: Tensor) -> Tensor: + x_hc = self.hc_block(x) + x_lb = self.lb_block(x_hc) + return x_lb + + +class _HandcraftedBlock(Module): + """Helper class for KeyNet, it defines the handcrafted filters within the Key.Net handcrafted block.""" + + def __init__(self) -> None: + super().__init__() + self.spatial_gradient = SpatialGradient("sobel", 1) + + def forward(self, x: Tensor) -> Tensor: + sobel = self.spatial_gradient(x) + dx, dy = sobel[:, :, 0, :, :], sobel[:, :, 1, :, :] + + sobel_dx = self.spatial_gradient(dx) + dxx, dxy = sobel_dx[:, :, 0, :, :], sobel_dx[:, :, 1, :, :] + + sobel_dy = self.spatial_gradient(dy) + dyy = sobel_dy[:, :, 1, :, :] + + hc_feats = concatenate([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], 1) + + return hc_feats + + +class _LearnableBlock(nn.Sequential): + """Helper class for KeyNet. + + It defines the learnable blocks within the Key.Net + """ + + def __init__(self, in_channels: int = 10) -> None: + super().__init__() + + self.conv0 = _KeyNetConvBlock(in_channels) + self.conv1 = _KeyNetConvBlock() + self.conv2 = _KeyNetConvBlock() + + def forward(self, x: Tensor) -> Tensor: + x = self.conv2(self.conv1(self.conv0(x))) + return x + + +def _KeyNetConvBlock( + in_channels: int = 8, + out_channels: int = 8, + kernel_size: int = 5, + stride: int = 1, + padding: int = 2, + dilation: int = 1, +) -> nn.Sequential: + """Create KeyNet Conv Block. + + Default learnable convolutional block for KeyNet. + """ + return nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation), + nn.BatchNorm2d(out_channels), + nn.ReLU(inplace=True), + ) + + +class KeyNet(Module): + """Key.Net model definition -- local feature detector (response function). + + This is based on the original code + from paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters". See :cite:`KeyNet2019` for + more details. + + .. image:: _static/img/KeyNet.png + + Args: + pretrained: Download and set pretrained weights to the model. + keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`. + + Returns: + KeyNet response score. + + Shape: + - Input: :math:`(B, 1, H, W)` + - Output: :math:`(B, 1, H, W)` + + """ + + def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config) -> None: + super().__init__() + + num_filters = keynet_conf["num_filters"] + self.num_levels = keynet_conf["num_levels"] + kernel_size = keynet_conf["kernel_size"] + padding = kernel_size // 2 + + self.feature_extractor = _FeatureExtractor() + self.last_conv = nn.Sequential( + nn.Conv2d( + in_channels=num_filters * self.num_levels, out_channels=1, kernel_size=kernel_size, padding=padding + ), + nn.ReLU(inplace=True), + ) + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(KeyNet_URL, map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict["state_dict"], strict=True) + self.eval() + + def forward(self, x: Tensor) -> Tensor: + """X - input image.""" + shape_im = x.shape + feats: List[Tensor] = [self.feature_extractor(x)] + for _ in range(1, self.num_levels): + x = pyrdown(x, factor=1.2) + feats_i = self.feature_extractor(x) + feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode="bilinear") + feats.append(feats_i) + scores = self.last_conv(concatenate(feats, 1)) + return scores + + +class KeyNetDetector(MultiResolutionDetector): + """Multi-scale feature detector based on KeyNet. + + This is based on the original code from paper + "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters". + See :cite:`KeyNet2019` for more details. + + .. image:: _static/img/keynet.jpg + + Args: + pretrained: Download and set pretrained weights to the model. + num_features: Number of features to detect. + keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`. + ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`, + which does nothing. See :class:`~kornia.feature.LAFOrienter` for details. + aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`, + which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details. + + """ + + def __init__( + self, + pretrained: bool = False, + num_features: int = 2048, + keynet_conf: KeyNet_conf = keynet_default_config, + ori_module: Optional[Module] = None, + aff_module: Optional[Module] = None, + ) -> None: + model = KeyNet(pretrained, keynet_conf) + super().__init__(model, num_features, keynet_conf["Detector_conf"], ori_module, aff_module) diff --git a/python_embeded/Lib/site-packages/kornia/feature/laf.py b/python_embeded/Lib/site-packages/kornia/feature/laf.py new file mode 100644 index 0000000000000000000000000000000000000000..7fed16e1200381ec3c0debcf531baa04ed2cb672 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/laf.py @@ -0,0 +1,615 @@ +# 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. +# + +import math +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F + +from kornia.core import Tensor, concatenate, cos, sin, stack, tensor, zeros +from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE +from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg +from kornia.geometry.linalg import transform_points +from kornia.geometry.transform import pyrdown + + +def get_laf_scale(LAF: Tensor) -> Tensor: + """Return a scale of the LAFs. + + Args: + LAF: :math:`(B, N, 2, 3)` + + Returns: + scale :math:`(B, N, 1, 1)` + + Example: + >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3 + >>> output = get_laf_scale(input) # BxNx1x1 + + """ + KORNIA_CHECK_LAF(LAF) + eps = 1e-10 + out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] - LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + eps + return out.abs().sqrt() + + +def get_laf_center(LAF: Tensor) -> Tensor: + """Return a center (keypoint) of the LAFs. + + The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5. + + Args: + LAF: :math:`(B, N, 2, 3)` + + Returns: + xy :math:`(B, N, 2)` + + Example: + >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3 + >>> output = get_laf_center(input) # BxNx2 + + """ + KORNIA_CHECK_LAF(LAF) + out = LAF[..., 2] + return out + + +def get_laf_orientation(LAF: Tensor) -> Tensor: + """Return orientation of the LAFs, in degrees. + + Args: + LAF: :math:`(B, N, 2, 3)` + + Returns: + angle in degrees :math:`(B, N, 1)` + + Example: + >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3 + >>> output = get_laf_orientation(input) # BxNx1 + + """ + KORNIA_CHECK_LAF(LAF) + angle_rad = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0]) + return rad2deg(angle_rad).unsqueeze(-1) + + +def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor: + """Apply additional rotation to the LAFs. + + Compared to `set_laf_orientation`, the resulting rotation is original LAF orientation plus angles_degrees. + + Args: + LAF: :math:`(B, N, 2, 3)` + angles_degrees: :math:`(B, N, 1)` in degrees. + + Returns: + LAF oriented with angles :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_LAF(LAF) + B, N = LAF.shape[:2] + rotmat = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2) + out_laf = LAF.clone() + out_laf[:, :, :2, :2] = torch.bmm(LAF[:, :, :2, :2].reshape(B * N, 2, 2), rotmat).reshape(B, N, 2, 2) + return out_laf + + +def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor: + """Change the orientation of the LAFs. + + Args: + LAF: :math:`(B, N, 2, 3)` + angles_degrees: :math:`(B, N, 1)` in degrees. + + Returns: + LAF oriented with angles :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_LAF(LAF) + B, N = LAF.shape[:2] + ori = get_laf_orientation(LAF).reshape_as(angles_degrees) + return rotate_laf(LAF, angles_degrees - ori) + + +def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: Optional[Tensor] = None) -> Tensor: + """Create a LAF from keypoint center, scale and orientation. + + Useful to create kornia LAFs from OpenCV keypoints. + + Args: + xy: :math:`(B, N, 2)`. + scale: :math:`(B, N, 1, 1)`. If not provided, scale = 1.0 is assumed + ori: angle in degrees :math:`(B, N, 1)`. If not provided orientation = 0 is assumed + + Returns: + LAF :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_SHAPE(xy, ["B", "N", "2"]) + device = xy.device + dtype = xy.dtype + B, N = xy.shape[:2] + if scale is None: + scale = torch.ones(B, N, 1, 1, device=device, dtype=dtype) + if ori is None: + ori = zeros(B, N, 1, device=device, dtype=dtype) + KORNIA_CHECK_SHAPE(scale, ["B", "N", "1", "1"]) + KORNIA_CHECK_SHAPE(ori, ["B", "N", "1"]) + unscaled_laf = concatenate([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1) + laf = scale_laf(unscaled_laf, scale) + return laf + + +def scale_laf(laf: Tensor, scale_coef: Union[float, Tensor]) -> Tensor: + """Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient. + + So the center, shape and orientation of the local feature stays the same, but the region area changes. + + Args: + laf: :math:`(B, N, 2, 3)` + scale_coef: broadcastable tensor or float. + + Returns: + LAF :math:`(B, N, 2, 3)` + + Example: + >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3 + >>> scale = 0.5 + >>> output = scale_laf(input, scale) # BxNx2x3 + + """ + if not isinstance(scale_coef, (float, Tensor)): + raise TypeError(f"scale_coef should be float or Tensor. Got {type(scale_coef)}") + KORNIA_CHECK_LAF(laf) + centerless_laf = laf[:, :, :2, :2] + return concatenate([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3) + + +def make_upright(laf: Tensor, eps: float = 1e-9) -> Tensor: + """Rectify the affine matrix, so that it becomes upright. + + Args: + laf: :math:`(B, N, 2, 3)` + eps: for safe division. + + Returns: + laf: :math:`(B, N, 2, 3)` + + Example: + >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3 + >>> output = make_upright(input) # BxNx2x3 + + """ + KORNIA_CHECK_LAF(laf) + det = get_laf_scale(laf) + scale = det + # The function is equivalent to doing 2x2 SVD and resetting rotation + # matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S. + b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + eps + laf1_ell = concatenate([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3) + laf2_ell = concatenate( + [ + ((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] + laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)), + (det / b2a2).contiguous(), + ], + dim=3, + ) + laf_unit_scale = concatenate([concatenate([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3) + return scale_laf(laf_unit_scale, scale) + + +def ellipse_to_laf(ells: Tensor) -> Tensor: + """Convert ellipse regions to LAF format. + + Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected + by inverse matrix square root: A = invsqrt([a b; b c]). + + See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m + + Args: + ells: tensor :math:`(B, N, 5)` of ellipses in Oxford format [x y a b c]. + + Returns: + LAF :math:`(B, N, 2, 3)` + + Example: + >>> input = torch.ones(1, 10, 5) # BxNx5 + >>> output = ellipse_to_laf(input) # BxNx2x3 + + """ + KORNIA_CHECK_SHAPE(ells, ["B", "N", "5"]) + B, N, _ = ells.shape + # Previous implementation was incorrectly using Cholesky decomp as matrix sqrt + # ell_shape = concatenate([concatenate([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2), + # concatenate([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2) + # out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2) + + # We will calculate 2x2 matrix square root via special case formula + # https://en.wikipedia.org/wiki/Square_root_of_a_matrix + # "The Cholesky factorization provides another particular example of square root + # which should not be confused with the unique non-negative square root." + # https://en.wikipedia.org/wiki/Square_root_of_a_2_by_2_matrix + # M = (A 0; C D) + # R = (sqrt(A) 0; C / (sqrt(A)+sqrt(D)) sqrt(D)) + a11 = ells[..., 2:3].abs().sqrt() + a12 = torch.zeros_like(a11) + a22 = ells[..., 4:5].abs().sqrt() + a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9) + A = stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse() + out = concatenate([A, ells[..., :2].view(B, N, 2, 1)], dim=3) + return out + + +def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor: + """Convert LAFs to boundary points of the regions + center. + + Used for local features visualization, see visualize_laf function. + + Args: + LAF: :math:`(B, N, 2, 3)` + n_pts: number of points to output. + + Returns: + tensor of boundary points LAF: :math:`(B, N, n_pts, 2)` + + """ + KORNIA_CHECK_LAF(LAF) + B, N, _, _ = LAF.size() + pts = concatenate( + [ + sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1), + cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1), + torch.ones(n_pts - 1, 1), + ], + dim=1, + ) + # Add origin to draw also the orientation + pts = concatenate([tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3) + pts = pts.to(LAF.device).to(LAF.dtype) + aux = tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3) + HLAF = concatenate([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1) + pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1) + return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3)) + + +def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]: + """Return list for drawing LAFs (local features). + + Args: + LAF: :math:`(B, N, 2, 3)` + img_idx: which points to output. + + Returns: + List of boundary points x, y` + + Examples: + x, y = get_laf_pts_to_draw(LAF, img_idx) + plt.figure() + plt.imshow(kornia.utils.tensor_to_image(img[img_idx])) + plt.plot(x, y, 'r') + plt.show() + + """ + # TODO: Refactor doctest + KORNIA_CHECK_LAF(LAF) + pts = laf_to_boundary_points(LAF[img_idx : img_idx + 1])[0] + pts_np = pts.detach().permute(1, 0, 2).cpu() + return (pts_np[..., 0].tolist(), pts_np[..., 1].tolist()) + + +def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor: + """De-normalize LAFs from scale to image scale. + + The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5. + + B,N,H,W = images.size() + MIN_SIZE = min(H - 1, W -1) + [a11 a21 x] + [a21 a22 y] + becomes + [a11*MIN_SIZE a21*MIN_SIZE x*(W-1)] + [a21*MIN_SIZE a22*MIN_SIZE y*(W-1)] + + Args: + LAF: :math:`(B, N, 2, 3)` + images: :math:`(B, CH, H, W)` + + Returns: + the denormalized LAF: :math:`(B, N, 2, 3)`, scale in pixels + + """ + KORNIA_CHECK_LAF(LAF) + _, _, h, w = images.size() + wf = float(w - 1) + hf = float(h - 1) + min_size = min(hf, wf) + coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) * min_size + coef[0, 0, 0, 2] = wf + coef[0, 0, 1, 2] = hf + return coef.expand_as(LAF) * LAF + + +def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor: + """Normalize LAFs to [0,1] scale from pixel scale. + + See below: + B,N,H,W = images.size() + MIN_SIZE = min(H - 1, W -1) + [a11 a21 x] + [a21 a22 y] + becomes: + [a11/MIN_SIZE a21/MIN_SIZE x/(W-1)] + [a21/MIN_SIZE a22/MIN_SIZE y/(H-1)] + + Args: + LAF: :math:`(B, N, 2, 3)` + images: :math:`(B, CH, H, W)` + + Returns: + the denormalized LAF: :math:`(B, N, 2, 3)`, scale in image percentage (0, 1) + + """ + KORNIA_CHECK_LAF(LAF) + _, _, h, w = images.size() + wf = float(w - 1) + hf = float(h - 1) + min_size = min(hf, wf) + coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) / min_size + coef[0, 0, 0, 2] = 1.0 / wf + coef[0, 0, 1, 2] = 1.0 / hf + return coef.expand_as(LAF) * LAF + + +def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int = 32) -> Tensor: + """Generate affine grid. + + Args: + img: image tensor of shape :math:`(B, CH, H, W)`. + LAF: laf with shape :math:`(B, N, 2, 3)`. + PS: patch size to be extracted. + + Returns: + grid :math:`(B*N, PS, PS, 2)` + + """ + KORNIA_CHECK_LAF(LAF) + B, N, _, _ = LAF.size() + _, ch, h, w = img.size() + + # norm, then renorm is needed for allowing detection on one resolution + # and extraction at arbitrary other + LAF_renorm = denormalize_laf(LAF, img) + + grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False) + grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w - 1) - 1.0 + grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h - 1) - 1.0 + return grid + + +def extract_patches_simple( + img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True +) -> Tensor: + """Extract patches defined by LAFs from image tensor. + + No smoothing applied, huge aliasing (better use extract_patches_from_pyramid). + + Args: + img: images, LAFs are detected in :math:`(B, CH, H, W)`. + laf: :math:`(B, N, 2, 3)`. + PS: patch size. + normalize_lafs_before_extraction: if True, lafs are normalized to image size. + + Returns: + patches with shape :math:`(B, N, CH, PS,PS)`. + + """ + KORNIA_CHECK_LAF(laf) + if normalize_lafs_before_extraction: + nlaf = normalize_laf(laf, img) + else: + nlaf = laf + _, ch, h, w = img.size() + B, N, _, _ = laf.size() + out = [] + # for loop temporarily, to be refactored + for i in range(B): + grid = generate_patch_grid_from_normalized_LAF(img[i : i + 1], nlaf[i : i + 1], PS).to(img.device) + out.append( + F.grid_sample( + img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False + ) + ) + return concatenate(out, dim=0).view(B, N, ch, PS, PS) + + +def extract_patches_from_pyramid( + img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True +) -> Tensor: + """Extract patches defined by LAFs from image tensor. + + Patches are extracted from appropriate pyramid level. + + Args: + img: images, LAFs are detected in :math:`(B, CH, H, W)`. + laf: :math:`(B, N, 2, 3)`. + PS: patch size. + normalize_lafs_before_extraction: if True, lafs are normalized to image size. + + Returns: + patches with shape :math:`(B, N, CH, PS,PS)`. + + """ + KORNIA_CHECK_LAF(laf) + if normalize_lafs_before_extraction: + nlaf = normalize_laf(laf, img) + else: + nlaf = laf + B, N, _, _ = laf.size() + _, ch, h, w = img.size() + scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS) + max_level = min(img.size(2), img.size(3)) // PS + pyr_idx = scale.log2().clamp(min=0.0, max=max(0, max_level - 1)).long() + cur_img = img + cur_pyr_level = 0 + out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device) + we_are_in_business = True + while we_are_in_business: + _, ch, h, w = cur_img.size() + # for loop temporarily, to be refactored + for i in range(B): + scale_mask = (pyr_idx[i] == cur_pyr_level).squeeze() + if (scale_mask.float().sum().item()) == 0: + continue + scale_mask = (scale_mask > 0).view(-1) + grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1, scale_mask, :, :], PS) + patches = F.grid_sample( + cur_img[i : i + 1].expand(grid.shape[0], ch, h, w), grid, padding_mode="border", align_corners=False + ) + out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches.to(nlaf.dtype)) + we_are_in_business = min(cur_img.size(2), cur_img.size(3)) >= PS + if not we_are_in_business: + break + cur_img = pyrdown(cur_img) + cur_pyr_level += 1 + return out + + +def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor: + """Check if the LAF is touching or partly outside the image boundary. + + Returns the mask of LAFs, which are fully inside the image, i.e. valid. + + Args: + laf: :math:`(B, N, 2, 3)`. + images: images, lafs are detected in :math:`(B, CH, H, W)`. + border: additional border. + + Returns: + mask with shape :math:`(B, N)`. + + """ + KORNIA_CHECK_LAF(laf) + _, _, h, w = images.size() + pts = laf_to_boundary_points(laf, 12) + good_lafs_mask = ( + (pts[..., 0] >= border) * (pts[..., 0] <= w - border) * (pts[..., 1] >= border) * (pts[..., 1] <= h - border) + ) + good_lafs_mask = good_lafs_mask.min(dim=2)[0] + return good_lafs_mask + + +def laf_to_three_points(laf: Tensor) -> Tensor: + """Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector, + LAF-y unit vector. + + Args: + laf: :math:`(B, N, 2, 3)`. + + Returns: + threepts :math:`(B, N, 2, 3)`. + + """ # noqa:D205 + KORNIA_CHECK_LAF(laf) + three_pts = stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1) + return three_pts + + +def laf_from_three_points(threepts: Tensor) -> Tensor: + """Convert three points to local affine frame. + + Order is (0,0), (0, 1), (1, 0). + + Args: + threepts: :math:`(B, N, 2, 3)`. + + Returns: + laf :math:`(B, N, 2, 3)`. + + """ + laf = stack([threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1) + return laf + + +def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor: + r"""Apply perspective transformations to a set of local affine frames (LAFs). + + Args: + trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`. + lafs_1: tensor of lafs of shape :math:`(B, N, 2, 3)`. + + Returns: + tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`. + + Examples: + >>> rng = torch.manual_seed(0) + >>> lafs_1 = torch.rand(2, 4, 2, 3) # BxNx2x3 + >>> lafs_1 + tensor([[[[0.4963, 0.7682, 0.0885], + [0.1320, 0.3074, 0.6341]], + + [[0.4901, 0.8964, 0.4556], + [0.6323, 0.3489, 0.4017]], + + [[0.0223, 0.1689, 0.2939], + [0.5185, 0.6977, 0.8000]], + + [[0.1610, 0.2823, 0.6816], + [0.9152, 0.3971, 0.8742]]], + + + [[[0.4194, 0.5529, 0.9527], + [0.0362, 0.1852, 0.3734]], + + [[0.3051, 0.9320, 0.1759], + [0.2698, 0.1507, 0.0317]], + + [[0.2081, 0.9298, 0.7231], + [0.7423, 0.5263, 0.2437]], + + [[0.5846, 0.0332, 0.1387], + [0.2422, 0.8155, 0.7932]]]]) + >>> trans_01 = torch.eye(3).repeat(2, 1, 1) # Bx3x3 + >>> trans_01.shape + torch.Size([2, 3, 3]) + >>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3 + + """ + KORNIA_CHECK_LAF(lafs_1) + if not torch.is_tensor(trans_01): + raise TypeError("Input type is not a Tensor") + + if not trans_01.device == lafs_1.device: + raise TypeError("Tensor must be in the same device") + + if not trans_01.shape[0] == lafs_1.shape[0]: + raise ValueError("Input batch size must be the same for both tensors") + + if (not (trans_01.shape[-1] == 3)) or (not (trans_01.shape[-2] == 3)): + raise ValueError("Transformation should be homography") + + bs, n, _, _ = lafs_1.size() + # First, we convert LAF to points + threepts_1 = laf_to_three_points(lafs_1) + points_1 = threepts_1.permute(0, 1, 3, 2).reshape(bs, n * 3, 2) + + # First, transform the points + points_0 = transform_points(trans_01, points_1) + + # Back to LAF format + threepts_0 = points_0.view(bs, n, 3, 2).permute(0, 1, 3, 2) + return laf_from_three_points(threepts_0) diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdacc1cc62bdff632f3fbb6d9b9f8514c597fc1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue.py @@ -0,0 +1,701 @@ +# 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. +# + +import math +import warnings +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Callable, ClassVar, Dict, List, Optional, Sequence, Tuple + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core import ( + Module, + ModuleList, + Tensor, + arange, + concatenate, + cos, + einsum, + ones, + ones_like, + sin, + stack, + where, + zeros, +) +from kornia.core.check import KORNIA_CHECK +from kornia.feature.laf import laf_to_three_points, scale_laf +from kornia.utils._compat import custom_fwd + +try: + from flash_attn.modules.mha import FlashCrossAttention +except ModuleNotFoundError: + FlashCrossAttention = None + +if FlashCrossAttention or hasattr(F, "scaled_dot_product_attention"): + FLASH_AVAILABLE = True +else: + FLASH_AVAILABLE = False + + +def math_clamp(x, min_, max_): # type: ignore + """Clamp a value to lie within [min, max].""" + return min(max(x, min_), max_) + + +@custom_fwd(cast_inputs=torch.float32) +def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor: + """Normalize tensor of keypoints.""" + if isinstance(size, torch.Size): + size = torch.tensor(size)[None] + shift = size.float().to(kpts) / 2 + scale = size.max(1).values.float().to(kpts) / 2 + kpts = (kpts - shift[:, None]) / scale[:, None, None] + return kpts + + +def pad_to_length(x: Tensor, length: int) -> Tuple[Tensor, Tensor]: + """Pad tensor to desired length.""" + if length <= x.shape[-2]: + return x, ones_like(x[..., :1], dtype=torch.bool) + pad = ones(*x.shape[:-2], length - x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype) + y = concatenate([x, pad], dim=-2) + mask = zeros(*y.shape[:-1], 1, dtype=torch.bool, device=x.device) + mask[..., : x.shape[-2], :] = True + return y, mask + + +def rotate_half(x: Tensor) -> Tensor: + """Apply half rotation.""" + x = x.unflatten(-1, (-1, 2)) + x1, x2 = x.unbind(dim=-1) + return stack((-x2, x1), dim=-1).flatten(start_dim=-2) + + +def apply_cached_rotary_emb(freqs: Tensor, t: Tensor) -> Tensor: + """Apply rotary embedding.""" + return (t * freqs[0]) + (rotate_half(t) * freqs[1]) + + +class LearnableFourierPositionalEncoding(Module): + def __init__(self, M: int, dim: int, F_dim: Optional[int] = None, gamma: float = 1.0) -> None: + super().__init__() + F_dim = F_dim if F_dim is not None else dim + self.gamma = gamma + self.Wr = nn.Linear(M, F_dim // 2, bias=False) + nn.init.normal_(self.Wr.weight.data, mean=0, std=self.gamma**-2) + + def forward(self, x: Tensor) -> Tensor: + """Encode position vector.""" + projected = self.Wr(x) + cosines, sines = cos(projected), sin(projected) + emb = stack([cosines, sines], 0).unsqueeze(-3) + return emb.repeat_interleave(2, dim=-1) + + +class TokenConfidence(Module): + def __init__(self, dim: int) -> None: + super().__init__() + self.token = nn.Sequential(nn.Linear(dim, 1), nn.Sigmoid()) + + def forward(self, desc0: Tensor, desc1: Tensor) -> Tuple[Tensor, Tensor]: + """Get confidence tokens.""" + dtype = self.token[0].weight.dtype + orig_dtype = desc0.dtype + return ( + self.token(desc0.detach().to(dtype)).squeeze(-1).to(orig_dtype), + self.token(desc1.detach().to(dtype)).squeeze(-1).to(orig_dtype), + ) + + +class Attention(Module): + def __init__(self, allow_flash: bool) -> None: + super().__init__() + if allow_flash and not FLASH_AVAILABLE: + warnings.warn( + "FlashAttention is not available. For optimal speed, consider installing torch >= 2.0 or flash-attn.", + stacklevel=2, + ) + self.enable_flash = allow_flash and FLASH_AVAILABLE + self.has_sdp = hasattr(F, "scaled_dot_product_attention") + if allow_flash and FlashCrossAttention: + self.flash_ = FlashCrossAttention() + if self.has_sdp: + torch.backends.cuda.enable_flash_sdp(allow_flash) + + def forward(self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None) -> Tensor: + if self.enable_flash and q.device.type == "cuda": + # use torch 2.0 scaled_dot_product_attention with flash + if self.has_sdp: + args = [x.half().contiguous() for x in [q, k, v]] + v = F.scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignore + return v if mask is None else v.nan_to_num() + else: + KORNIA_CHECK(mask is None) + q, k, v = (x.transpose(-2, -3).contiguous() for x in [q, k, v]) + m = self.flash_(q.half(), stack([k, v], 2).half()) + return m.transpose(-2, -3).to(q.dtype).clone() + elif self.has_sdp: + args = [x.contiguous() for x in [q, k, v]] + v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignore + return v if mask is None else v.nan_to_num() + else: + s = q.shape[-1] ** -0.5 + sim = einsum("...id,...jd->...ij", q, k) * s + if mask is not None: + sim.masked_fill(~mask, -float("inf")) + attn = F.softmax(sim, -1) + return einsum("...ij,...jd->...id", attn, v) + + +class SelfBlock(Module): + def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None: + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + KORNIA_CHECK(self.embed_dim % num_heads == 0, "Embed dimension should be dividable by num_heads") + self.head_dim = self.embed_dim // num_heads + self.Wqkv = nn.Linear(embed_dim, 3 * embed_dim, bias=bias) + self.inner_attn = Attention(flash) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.ffn = nn.Sequential( + nn.Linear(2 * embed_dim, 2 * embed_dim), + nn.LayerNorm(2 * embed_dim, elementwise_affine=True), + nn.GELU(), + nn.Linear(2 * embed_dim, embed_dim), + ) + + def forward( + self, + x: Tensor, + encoding: Tensor, + mask: Optional[Tensor] = None, + ) -> Tensor: + qkv = self.Wqkv(x) + qkv = qkv.unflatten(-1, (self.num_heads, -1, 3)).transpose(1, 2) + q, k, v = qkv[..., 0], qkv[..., 1], qkv[..., 2] + q = apply_cached_rotary_emb(encoding, q) + k = apply_cached_rotary_emb(encoding, k) + context = self.inner_attn(q, k, v, mask=mask) + message = self.out_proj(context.transpose(1, 2).flatten(start_dim=-2)) + return x + self.ffn(concatenate([x, message], -1)) + + +class CrossBlock(Module): + def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None: + super().__init__() + self.heads = num_heads + dim_head = embed_dim // num_heads + self.scale = dim_head**-0.5 + inner_dim = dim_head * num_heads + self.to_qk = nn.Linear(embed_dim, inner_dim, bias=bias) + self.to_v = nn.Linear(embed_dim, inner_dim, bias=bias) + self.to_out = nn.Linear(inner_dim, embed_dim, bias=bias) + self.ffn = nn.Sequential( + nn.Linear(2 * embed_dim, 2 * embed_dim), + nn.LayerNorm(2 * embed_dim, elementwise_affine=True), + nn.GELU(), + nn.Linear(2 * embed_dim, embed_dim), + ) + if flash and FLASH_AVAILABLE: + self.flash = Attention(True) + else: + self.flash = None # type: ignore + + def map_(self, func: Callable, x0: Tensor, x1: Tensor) -> Tuple[Tensor, Tensor]: # type: ignore + return func(x0), func(x1) + + def forward(self, x0: Tensor, x1: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + qk0, qk1 = self.map_(self.to_qk, x0, x1) + v0, v1 = self.map_(self.to_v, x0, x1) + qk0, qk1, v0, v1 = (t.unflatten(-1, (self.heads, -1)).transpose(1, 2) for t in (qk0, qk1, v0, v1)) + if self.flash is not None and qk0.device.type == "cuda": + m0 = self.flash(qk0, qk1, v1, mask) + m1 = self.flash(qk1, qk0, v0, mask.transpose(-1, -2) if mask is not None else None) + else: + qk0, qk1 = qk0 * self.scale**0.5, qk1 * self.scale**0.5 + sim = einsum("bhid, bhjd -> bhij", qk0, qk1) + if mask is not None: + sim = sim.masked_fill(~mask, -float("inf")) + attn01 = F.softmax(sim, dim=-1) + attn10 = F.softmax(sim.transpose(-2, -1).contiguous(), dim=-1) + m0 = einsum("bhij, bhjd -> bhid", attn01, v1) + m1 = einsum("bhji, bhjd -> bhid", attn10.transpose(-2, -1), v0) + if mask is not None: + m0, m1 = m0.nan_to_num(), m1.nan_to_num() + m0, m1 = self.map_(lambda t: t.transpose(1, 2).flatten(start_dim=-2), m0, m1) + m0, m1 = self.map_(self.to_out, m0, m1) + x0 = x0 + self.ffn(concatenate([x0, m0], -1)) + x1 = x1 + self.ffn(concatenate([x1, m1], -1)) + return x0, x1 + + +class TransformerLayer(Module): + def __init__(self, *args, **kwargs): # type: ignore + super().__init__() + self.self_attn = SelfBlock(*args, **kwargs) + self.cross_attn = CrossBlock(*args, **kwargs) + + def forward( + self, + desc0: Tensor, + desc1: Tensor, + encoding0: Tensor, + encoding1: Tensor, + mask0: Optional[Tensor] = None, + mask1: Optional[Tensor] = None, + ) -> Tensor: + if mask0 is not None and mask1 is not None: + return self.masked_forward(desc0, desc1, encoding0, encoding1, mask0, mask1) + else: + desc0 = self.self_attn(desc0, encoding0) + desc1 = self.self_attn(desc1, encoding1) + return self.cross_attn(desc0, desc1) + + # This part is compiled and allows padding inputs + def masked_forward( + self, desc0: Tensor, desc1: Tensor, encoding0: Tensor, encoding1: Tensor, mask0: Tensor, mask1: Tensor + ) -> Tensor: + mask = mask0 & mask1.transpose(-1, -2) + mask0 = mask0 & mask0.transpose(-1, -2) + mask1 = mask1 & mask1.transpose(-1, -2) + desc0 = self.self_attn(desc0, encoding0, mask0) + desc1 = self.self_attn(desc1, encoding1, mask1) + return self.cross_attn(desc0, desc1, mask) + + +def sigmoid_log_double_softmax(sim: Tensor, z0: Tensor, z1: Tensor) -> Tensor: + """Create the log assignment matrix from logits and similarity.""" + b, m, n = sim.shape + certainties = F.logsigmoid(z0) + F.logsigmoid(z1).transpose(1, 2) + scores0 = F.log_softmax(sim, 2) + scores1 = F.log_softmax(sim.transpose(-1, -2).contiguous(), 2).transpose(-1, -2) + scores = sim.new_full((b, m + 1, n + 1), 0) + scores[:, :m, :n] = scores0 + scores1 + certainties + scores[:, :-1, -1] = F.logsigmoid(-z0.squeeze(-1)) + scores[:, -1, :-1] = F.logsigmoid(-z1.squeeze(-1)) + return scores + + +class MatchAssignment(Module): + def __init__(self, dim: int) -> None: + super().__init__() + self.dim = dim + self.matchability = nn.Linear(dim, 1, bias=True) + self.final_proj = nn.Linear(dim, dim, bias=True) + + def forward(self, desc0: Tensor, desc1: Tensor) -> Tuple[Tensor, Tensor]: + """Build assignment matrix from descriptors.""" + mdesc0, mdesc1 = self.final_proj(desc0), self.final_proj(desc1) + _, _, d = mdesc0.shape + mdesc0, mdesc1 = mdesc0 / d**0.25, mdesc1 / d**0.25 + sim = einsum("bmd,bnd->bmn", mdesc0, mdesc1) + z0 = self.matchability(desc0) + z1 = self.matchability(desc1) + scores = sigmoid_log_double_softmax(sim, z0, z1) + return scores, sim + + def get_matchability(self, desc: Tensor) -> Tensor: + return torch.sigmoid(self.matchability(desc)).squeeze(-1) + + +def filter_matches(scores: Tensor, th: float) -> Tuple[Tensor, Tensor, Tensor, Tensor]: + """Obtain matches from a log assignment matrix [Bx M+1 x N+1].""" + max0, max1 = scores[:, :-1, :-1].max(2), scores[:, :-1, :-1].max(1) + m0, m1 = max0.indices, max1.indices + indices0 = arange(m0.shape[1], device=m0.device)[None] + indices1 = arange(m1.shape[1], device=m1.device)[None] + mutual0 = indices0 == m1.gather(1, m0) + mutual1 = indices1 == m0.gather(1, m1) + max0_exp = max0.values.exp() + zero = max0_exp.new_tensor(0) + mscores0 = where(mutual0, max0_exp, zero) + mscores1 = where(mutual1, mscores0.gather(1, m1), zero) + valid0 = mutual0 & (mscores0 > th) + valid1 = mutual1 & valid0.gather(1, m1) + m0 = where(valid0, m0, -1) + m1 = where(valid1, m1, -1) + return m0, m1, mscores0, mscores1 + + +class LightGlue(Module): + default_conf: ClassVar[Dict[str, Any]] = { + "name": "lightglue", # just for interfacing + "input_dim": 256, # input descriptor dimension (autoselected from weights) + "descriptor_dim": 256, + "add_scale_ori": False, + "add_laf": False, # for KeyNetAffNetHardNet + "scale_coef": 1.0, # to compensate for the SIFT scale bigger than KeyNet + "n_layers": 9, + "num_heads": 4, + "flash": True, # enable FlashAttention if available. + "mp": False, # enable mixed precision + "depth_confidence": 0.95, # early stopping, disable with -1 + "width_confidence": 0.99, # point pruning, disable with -1 + "filter_threshold": 0.1, # match threshold + "weights": None, + } + + # Point pruning involves an overhead (gather). + # Therefore, we only activate it if there are enough keypoints. + pruning_keypoint_thresholds: ClassVar[Dict[str, Any]] = { + "cpu": -1, + "mps": -1, + "cuda": 1024, + "flash": 1536, + } + required_data_keys: ClassVar[List[str]] = ["image0", "image1"] + + version: ClassVar[str] = "v0.1_arxiv" + url: ClassVar[str] = "https://github.com/cvg/LightGlue/releases/download/{}/{}_lightglue.pth" + + features: ClassVar[Dict[str, Any]] = { + "superpoint": { + "weights": "superpoint_lightglue", + "input_dim": 256, + }, + "dedodeb": { + "weights": "dedodeb_lightglue", + "input_dim": 256, + }, + "dedodeg": { + "weights": "dedodeg_lightglue", + "input_dim": 256, + }, + "disk": { + "weights": "disk_lightglue", + "input_dim": 128, + }, + "aliked": { + "weights": "aliked_lightglue", + "input_dim": 128, + }, + "sift": { + "weights": "sift_lightglue", + "input_dim": 128, + "add_scale_ori": True, + }, + "dog_affnet_hardnet": { + "weights": "doghardnet", + "input_dim": 128, + "width_confidence": -1, + "depth_confidence": -1, + "add_scale_ori": True, + "scale_coef": 1.0 / 6.0, + }, + "doghardnet": { + "weights": "doghardnet", + "input_dim": 128, + "width_confidence": -1, + "depth_confidence": -1, + "add_scale_ori": True, + "scale_coef": 1.0 / 6.0, + }, + "keynet_affnet_hardnet": { + "weights": "keynet_affnet_hardnet_lightglue", + "input_dim": 128, + "width_confidence": -1, + "depth_confidence": -1, + "add_laf": True, + }, + } + + def __init__(self, features: str = "superpoint", **conf_) -> None: # type: ignore + super().__init__() + self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf_}) + if features is not None: + KORNIA_CHECK(features in list(self.features.keys()), "Features keys are wrong") + for k, v in self.features[features].items(): + setattr(conf, k, v) + KORNIA_CHECK(not (self.conf.add_scale_ori and self.conf.add_laf)) # we use either scale ori, or LAF + + if conf.input_dim != conf.descriptor_dim: + self.input_proj = nn.Linear(conf.input_dim, conf.descriptor_dim, bias=True) + else: + self.input_proj = nn.Identity() # type: ignore + + head_dim = conf.descriptor_dim // conf.num_heads + self.posenc = LearnableFourierPositionalEncoding( + 2 + 2 * conf.add_scale_ori + 4 * conf.add_laf, + head_dim, + head_dim, + ) + + h, n, d = conf.num_heads, conf.n_layers, conf.descriptor_dim + self.transformers = ModuleList([TransformerLayer(d, h, conf.flash) for _ in range(n)]) + self.log_assignment = ModuleList([MatchAssignment(d) for _ in range(n)]) + self.token_confidence = ModuleList([TokenConfidence(d) for _ in range(n - 1)]) + self.register_buffer( + "confidence_thresholds", + Tensor([self.confidence_threshold(i) for i in range(self.conf.n_layers)]), + ) + state_dict = None + if features is not None: + fname = f"{conf.weights}_{self.version}.pth".replace(".", "-") + if features == "dog_affnet_hardnet": + features = "doghardnet" # new dog model is better for affnet as well + if features in ["keynet_affnet_hardnet"]: + fname = "keynet_affnet_hardnet_lightlue.pth" + url = "http://cmp.felk.cvut.cz/~mishkdmy/models/keynet_affnet_hardnet_lightlue.pth" + elif features in ["dedodeb"]: + fname = "dedodeb_lightglue.pth" + url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth" + elif features in ["dedodeg"]: + fname = "dedodeg_lightglue.pth" + url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth" + else: + url = self.url.format(self.version, features) + state_dict = torch.hub.load_state_dict_from_url(url, file_name=fname) + elif conf.weights is not None: + path = Path(__file__).parent + path = path / f"weights/{self.conf.weights}.pth" + state_dict = torch.load(str(path), map_location="cpu") + if state_dict: + # rename old state dict entries + for i in range(self.conf.n_layers): + pattern = f"self_attn.{i}", f"transformers.{i}.self_attn" + state_dict = {k.replace(*pattern): v for k, v in state_dict.items()} + pattern = f"cross_attn.{i}", f"transformers.{i}.cross_attn" + state_dict = {k.replace(*pattern): v for k, v in state_dict.items()} + self.load_state_dict(state_dict, strict=False) + print("Loaded LightGlue model") + # static lengths LightGlue is compiled for (only used with torch.compile) + self.static_lengths = None + + def compile( + self, mode: str = "reduce-overhead", static_lengths: Sequence[int] = (256, 512, 768, 1024, 1280, 1536) + ) -> None: + if self.conf.width_confidence != -1: + warnings.warn( + "Point pruning is partially disabled for compiled forward.", + stacklevel=2, + ) + + for i in range(self.conf.n_layers): + self.transformers[i].masked_forward = torch.compile( # type: ignore[assignment] + self.transformers[i].masked_forward, mode=mode, fullgraph=True + ) + + self.static_lengths = static_lengths # type: ignore + + def forward(self, data: dict) -> dict: # type: ignore + """Match keypoints and descriptors between two images. + + Input (dict): + image0: dict + keypoints: [B x M x 2] + descriptors: [B x M x D] + image: [B x C x H x W] or image_size: [B x 2] + image1: dict + keypoints: [B x N x 2] + descriptors: [B x N x D] + image: [B x C x H x W] or image_size: [B x 2] + Output (dict): + log_assignment: [B x M+1 x N+1] + matches0: [B x M] + matching_scores0: [B x M] + matches1: [B x N] + matching_scores1: [B x N] + matches: List[[Si x 2]], scores: List[[Si]] + """ + with torch.autocast(enabled=self.conf.mp, device_type="cuda"): + return self._forward(data) + + def _forward(self, data: dict) -> dict: # type: ignore + for key in self.required_data_keys: + KORNIA_CHECK(key in data, f"Missing key {key} in data") + data0, data1 = data["image0"], data["image1"] + kpts0, kpts1 = data0["keypoints"], data1["keypoints"] + b, m, _ = kpts0.shape + b, n, _ = kpts1.shape + device = kpts0.device + size0, size1 = data0.get("image_size"), data1.get("image_size") + size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] + size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] + + kpts0 = normalize_keypoints(kpts0, size0).clone() + kpts1 = normalize_keypoints(kpts1, size1).clone() + KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore + KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore + if self.conf.add_scale_ori: + kpts0 = concatenate([kpts0] + [data0[k].unsqueeze(-1) for k in ("scales", "oris")], -1) + if self.conf.scale_coef != 1.0: + kpts0[..., -2] = kpts0[..., -2] * self.conf.scale_coef + kpts1 = concatenate([kpts1] + [data1[k].unsqueeze(-1) for k in ("scales", "oris")], -1) + if self.conf.scale_coef != 1.0: + kpts1[..., -2] = kpts1[..., -2] * self.conf.scale_coef + elif self.conf.add_laf: + laf0 = scale_laf(data0["lafs"], self.conf.scale_coef) + laf1 = scale_laf(data1["lafs"], self.conf.scale_coef) + laf0 = laf_to_three_points(laf0) + laf1 = laf_to_three_points(laf1) + kpts0 = concatenate( + [ + kpts0, + normalize_keypoints(laf0[..., 0], size0).clone().to(kpts0.dtype), + normalize_keypoints(laf0[..., 1], size0).clone().to(kpts0.dtype), + ], + -1, + ) + kpts1 = concatenate( + [ + kpts1, + normalize_keypoints(laf1[..., 0], size1).clone().to(kpts1.dtype), + normalize_keypoints(laf1[..., 1], size1).clone().to(kpts1.dtype), + ], + -1, + ) + + desc0 = data0["descriptors"].detach().contiguous() + desc1 = data1["descriptors"].detach().contiguous() + + KORNIA_CHECK(desc0.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config") + KORNIA_CHECK(desc1.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config") + + if torch.is_autocast_enabled(): + desc0 = desc0.half() + desc1 = desc1.half() + + mask0, mask1 = None, None + c = max(m, n) + do_compile = self.static_lengths and c <= max(self.static_lengths) + if do_compile: + kn = min([k for k in self.static_lengths if k >= c]) + desc0, mask0 = pad_to_length(desc0, kn) + desc1, mask1 = pad_to_length(desc1, kn) + kpts0, _ = pad_to_length(kpts0, kn) + kpts1, _ = pad_to_length(kpts1, kn) + desc0 = self.input_proj(desc0) + desc1 = self.input_proj(desc1) + # cache positional embeddings + encoding0 = self.posenc(kpts0) + encoding1 = self.posenc(kpts1) + + # GNN + final_proj + assignment + do_early_stop = self.conf.depth_confidence > 0 + do_point_pruning = self.conf.width_confidence > 0 and not do_compile + pruning_th = self.pruning_min_kpts(device) + if do_point_pruning: + ind0 = arange(0, m, device=device)[None] + ind1 = arange(0, n, device=device)[None] + # We store the index of the layer at which pruning is detected. + prune0 = ones_like(ind0) + prune1 = ones_like(ind1) + token0, token1 = None, None + for i in range(self.conf.n_layers): + desc0, desc1 = self.transformers[i](desc0, desc1, encoding0, encoding1, mask0=mask0, mask1=mask1) + if i == self.conf.n_layers - 1: + continue # no early stopping or adaptive width at last layer + + if do_early_stop: + token0, token1 = self.token_confidence[i](desc0, desc1) + if self.check_if_stop(token0[..., :m, :], token1[..., :n, :], i, m + n): + break + if do_point_pruning and desc0.shape[-2] > pruning_th: + scores0 = self.log_assignment[i].get_matchability(desc0) + prunemask0 = self.get_pruning_mask(token0, scores0, i) # type: ignore + keep0 = where(prunemask0)[1] + ind0 = ind0.index_select(1, keep0) + desc0 = desc0.index_select(1, keep0) + encoding0 = encoding0.index_select(-2, keep0) + prune0[:, ind0] += 1 + if do_point_pruning and desc1.shape[-2] > pruning_th: + scores1 = self.log_assignment[i].get_matchability(desc1) + prunemask1 = self.get_pruning_mask(token1, scores1, i) # type: ignore + keep1 = where(prunemask1)[1] + ind1 = ind1.index_select(1, keep1) + desc1 = desc1.index_select(1, keep1) + encoding1 = encoding1.index_select(-2, keep1) + prune1[:, ind1] += 1 + + desc0, desc1 = desc0[..., :m, :], desc1[..., :n, :] + scores, _ = self.log_assignment[i](desc0, desc1) + m0, m1, mscores0, mscores1 = filter_matches(scores, self.conf.filter_threshold) + matches, mscores = [], [] + for k in range(b): + valid = m0[k] > -1 + m_indices_0 = where(valid)[0] + m_indices_1 = m0[k][valid] + if do_point_pruning: + m_indices_0 = ind0[k, m_indices_0] + m_indices_1 = ind1[k, m_indices_1] + matches.append(stack([m_indices_0, m_indices_1], -1)) + mscores.append(mscores0[k][valid]) + + # TODO: Remove when hloc switches to the compact format. + if do_point_pruning: + m0_ = torch.full((b, m), -1, device=m0.device, dtype=m0.dtype) + m1_ = torch.full((b, n), -1, device=m1.device, dtype=m1.dtype) + m0_[:, ind0] = where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0))) + m1_[:, ind1] = where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0))) + mscores0_ = zeros((b, m), device=mscores0.device) + mscores1_ = zeros((b, n), device=mscores1.device) + mscores0_[:, ind0] = mscores0 + mscores1_[:, ind1] = mscores1 + m0, m1, mscores0, mscores1 = m0_, m1_, mscores0_, mscores1_ + else: + prune0 = ones_like(mscores0) * self.conf.n_layers + prune1 = ones_like(mscores1) * self.conf.n_layers + + pred = { + "log_assignment": scores, + "matches0": m0, + "matches1": m1, + "matching_scores0": mscores0, + "matching_scores1": mscores1, + "stop": i + 1, + "matches": matches, + "scores": mscores, + "prune0": prune0, + "prune1": prune1, + } + + return pred + + def confidence_threshold(self, layer_index: int) -> float: + """Scaled confidence threshold.""" + threshold = 0.8 + 0.1 * math.exp(-4.0 * layer_index / self.conf.n_layers) + return min(max(threshold, 0), 1) + + def get_pruning_mask(self, confidences: Tensor, scores: Tensor, layer_index: int) -> Tensor: + """Mask points which should be removed.""" + keep = scores > (1 - self.conf.width_confidence) + if confidences is not None: # Low-confidence points are never pruned. + keep |= confidences <= self.confidence_thresholds[layer_index] + return keep + + def check_if_stop( + self, + confidences0: Tensor, + confidences1: Tensor, + layer_index: int, + num_points: int, + ) -> Tensor: + """Evaluate stopping condition.""" + confidences = concatenate([confidences0, confidences1], -1) + threshold = self.confidence_thresholds[layer_index] + ratio_confident = 1.0 - (confidences < threshold).float().sum() / num_points + return ratio_confident > self.conf.depth_confidence + + def pruning_min_kpts(self, device: torch.device) -> int: + if self.conf.flash and FLASH_AVAILABLE and device.type == "cuda": + return self.pruning_keypoint_thresholds["flash"] + else: + return self.pruning_keypoint_thresholds[device.type] diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25117e801ffe260c87196c4db3cb0b96bea38f1e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/__init__.py @@ -0,0 +1,18 @@ +# 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. +# + +from .lightglue import OnnxLightGlue diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/lightglue.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/lightglue.py new file mode 100644 index 0000000000000000000000000000000000000000..9df1a76021238ae3c69a63f5fc991ed2b50e440f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/lightglue.py @@ -0,0 +1,188 @@ +# 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. +# + +from __future__ import annotations + +from typing import ClassVar + +import torch + +from kornia.core import Device, Tensor +from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE + +from .utils import download_onnx_from_url, normalize_keypoints + +try: + import numpy as np + import onnxruntime as ort +except ImportError: + np = None # type: ignore + ort = None + +__all__ = ["OnnxLightGlue"] + + +class OnnxLightGlue: + r"""Wrapper for loading LightGlue-ONNX models and running inference via ONNXRuntime. + + LightGlue :cite:`LightGlue2023` performs fast descriptor-based deep keypoint matching. + This module requires `onnxruntime` to be installed. + + If you have trained your own LightGlue model, see https://github.com/fabio-sim/LightGlue-ONNX + for how to export the model to ONNX and optimize it. + + Args: + weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weights + are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``. `Note that FP16 requires CUDA.` + Defaults to ``'disk_fp16'`` if ``device`` is CUDA, and ``'disk'`` if CPU. + device: Device to run inference on. + + """ + + MODEL_URLS: ClassVar[dict[str, str]] = { + "disk": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused.onnx", + "superpoint": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/superpoint_lightglue_fused.onnx", + "disk_fp16": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx", + "superpoint_fp16": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/superpoint_lightglue_fused_fp16.onnx", + } + + required_data_keys: ClassVar[list[str]] = ["image0", "image1"] + + def __init__(self, weights: str | None = None, device: Device = "cpu") -> None: + KORNIA_CHECK(ort is not None, "onnxruntime is not installed.") + KORNIA_CHECK(np is not None, "numpy is not installed.") + + device = torch.device(device) # type: ignore + self.device = device + + if device.type == "cpu": + providers = ["CPUExecutionProvider"] + elif device.type == "cuda": + providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] + else: + raise ValueError(f"Unsupported device {device}") + + if weights is None: + weights = "disk_fp16" if device.type == "cuda" else "disk" + + if weights in self.MODEL_URLS: + if "fp16" in weights: + KORNIA_CHECK(device.type == "cuda", "FP16 requires CUDA.") + + url = self.MODEL_URLS[weights] + if device.type == "cpu": + url = url.replace(".onnx", "_cpu.onnx") + + weights = download_onnx_from_url(url) + + self.session = ort.InferenceSession(weights, providers=providers) + + def __call__(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]: + return self.forward(data) + + def forward(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]: + r"""Match keypoints and descriptors between two images. + + The output contains the matches (the indices of the matching keypoint pairs between the first and second image) + and the corresponding confidence scores. + Only a batch size of 1 is supported. + + Args: + data: Dictionary containing both images and the keypoints and descriptors thereof. + + Returns: + Dictionary containing the matches and scores. + + ``data`` (``dict``): + ``image0`` (``dict``): + ``keypoints`` (`float32`): :math:`(1, M, 2)` + + ``descriptors`` (`float32`): :math:`(1, M, D)` + + ``image``: :math:`(1, C, H, W)` or ``image_size``: :math:`(1, 2)` + + ``image1`` (``dict``): + ``keypoints`` (`float32`): :math:`(1, N, 2)` + + ``descriptors`` (`float32`): :math:`(1, N, D)` + + ``image``: :math:`(1, C, H, W)` or ``image_size``: :math:`(1, 2)` + + ``output`` (``dict``): + ``matches`` (`int64`): :math:`(S, 2)` + + ``scores`` (`float32`): :math:`(S)` + + """ + # Input validation. + for key in self.required_data_keys: + KORNIA_CHECK(key in data, f"Missing key {key} in data") + data0, data1 = data["image0"], data["image1"] + kpts0_, kpts1_ = data0["keypoints"].contiguous(), data1["keypoints"].contiguous() + desc0, desc1 = data0["descriptors"].contiguous(), data1["descriptors"].contiguous() + KORNIA_CHECK_SAME_DEVICES([kpts0_, desc0, kpts1_, desc1], "Wrong device") + KORNIA_CHECK(kpts0_.device.type == self.device.type, "Wrong device") + KORNIA_CHECK(torch.float32 == kpts0_.dtype == kpts1_.dtype == desc0.dtype == desc1.dtype, "Wrong dtype") + KORNIA_CHECK_SHAPE(kpts0_, ["1", "M", "2"]) + KORNIA_CHECK_SHAPE(kpts1_, ["1", "N", "2"]) + KORNIA_CHECK_SHAPE(desc0, ["1", "M", "D"]) + KORNIA_CHECK_SHAPE(desc1, ["1", "N", "D"]) + KORNIA_CHECK(kpts0_.shape[1] == desc0.shape[1], "Number of keypoints does not match number of descriptors") + KORNIA_CHECK(kpts1_.shape[1] == desc1.shape[1], "Number of keypoints does not match number of descriptors") + KORNIA_CHECK(desc0.shape[2] == desc1.shape[2], "Descriptors' dimensions do not match") + + # Normalize keypoints. + size0, size1 = data0.get("image_size"), data1.get("image_size") + size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] # type: ignore + size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] # type: ignore + + kpts0 = normalize_keypoints(kpts0_, size=size0) # type: ignore + kpts1 = normalize_keypoints(kpts1_, size=size1) # type: ignore + + KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore + KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore + + # Inference. + lightglue_inputs = {"kpts0": kpts0, "kpts1": kpts1, "desc0": desc0, "desc1": desc1} + lightglue_outputs = ["matches0", "mscores0"] + binding = self.session.io_binding() + + for name, tensor in lightglue_inputs.items(): + binding.bind_input( + name, + device_type=self.device.type, + device_id=0, + element_type=np.float32, + shape=tuple(tensor.shape), + buffer_ptr=tensor.data_ptr(), + ) + + for name in lightglue_outputs: + binding.bind_output(name, device_type=self.device.type, device_id=0) + + self.session.run_with_iobinding(binding) + + matches, mscores = binding.get_outputs() + + # TODO: The following is an unnecessary copy. Replace with a better solution when torch supports + # constructing a tensor from a data pointer, or when ORT supports converting to torch tensor. + # https://github.com/microsoft/onnxruntime/issues/15963 + outputs = { + "matches": torch.from_dlpack(matches.numpy()).to(self.device), + "scores": torch.from_dlpack(mscores.numpy()).to(self.device), + } + return outputs diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73dddfd8d27d5915719705b5735391ade26b1e38 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from .download import download_onnx_from_url +from .keypoints import normalize_keypoints diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/download.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/download.py new file mode 100644 index 0000000000000000000000000000000000000000..6ccb79f98936500ef8eb6fa30024810d06a8eb9f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/download.py @@ -0,0 +1,80 @@ +# 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. +# + +from __future__ import annotations + +import os +import sys +from typing import Optional +from urllib.parse import urlparse + +from torch.hub import HASH_REGEX, download_url_to_file, get_dir + + +def download_onnx_from_url( + url: str, + model_dir: Optional[str] = None, + progress: bool = True, + check_hash: bool = False, + file_name: Optional[str] = None, +) -> str: + r"""Load the ONNX model at the given URL. + + If downloaded file is a zip file, it will be automatically + decompressed. + + If the object is already present in `model_dir`, it's deserialized and + returned. + The default value of ``model_dir`` is ``/checkpoints`` where + ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`. + + Args: + url (str): URL of the object to download + model_dir (str, optional): directory in which to save the object + progress (bool, optional): whether or not to display a progress bar to stderr. + Default: True + check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention + ``filename-.ext`` where ```` is the first eight or more + digits of the SHA256 hash of the contents of the file. The hash is used to + ensure unique names and to verify the contents of the file. + Default: False + file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set. + + Example: + >>> model = download_onnx_from_url('https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx') + + """ + if model_dir is None: + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + + os.makedirs(model_dir, exist_ok=True) + + parts = urlparse(url) + filename = os.path.basename(parts.path) + if file_name is not None: + filename = file_name + cached_file = os.path.join(model_dir, filename) + if not os.path.exists(cached_file): + sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n') + hash_prefix = None + if check_hash: + r = HASH_REGEX.search(filename) # r is Optional[Match[str]] + hash_prefix = r.group(1) if r else None + download_url_to_file(url, cached_file, hash_prefix, progress=progress) + + return cached_file diff --git a/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/keypoints.py b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/keypoints.py new file mode 100644 index 0000000000000000000000000000000000000000..504b8d8cca74767187e7cbcd27a600be24ead818 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/lightglue_onnx/utils/keypoints.py @@ -0,0 +1,32 @@ +# 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. +# + +from __future__ import annotations + +import torch + +from kornia.core import Tensor, tensor + + +def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor: + """Normalize tensor of keypoints.""" + if isinstance(size, torch.Size): + size = tensor(size)[None] + shift = size.float().to(kpts) / 2 + scale = size.max(1).values.float().to(kpts) / 2 + kpts = (kpts - shift[:, None]) / scale[:, None, None] + return kpts diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3bb160faf22b244fe5cdfdfbe0769359f4e64cf --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/__init__.py @@ -0,0 +1,20 @@ +# 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. +# + +from __future__ import annotations + +from .loftr import LoFTR diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec76097444decedcc1f98ef97c968f25b93c7e49 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/__init__.py @@ -0,0 +1,33 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any + +from .resnet_fpn import ResNetFPN_8_2, ResNetFPN_16_4 + + +def build_backbone(config: dict[str, Any]) -> ResNetFPN_8_2 | ResNetFPN_16_4: + """Build model backbone.""" + if config["backbone_type"] == "ResNetFPN": + if config["resolution"] == (8, 2): + return ResNetFPN_8_2(config["resnetfpn"]) + elif config["resolution"] == (16, 4): + return ResNetFPN_16_4(config["resnetfpn"]) + + raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_type']} with res {config['resolution']} not supported.") diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/resnet_fpn.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/resnet_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..166e25589c8fa79e20fc438cc11acc408d1ac3cf --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/backbone/resnet_fpn.py @@ -0,0 +1,217 @@ +# 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. +# + +from typing import Any, Dict, List, Type, Union + +import torch.nn.functional as F +from torch import nn + +from kornia.core import Module, Tensor + + +def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: + """1x1 convolution without padding.""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False) + + +def conv3x3(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: + """3x3 convolution with padding.""" + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) + + +class BasicBlock(Module): + def __init__(self, in_planes: int, planes: int, stride: int = 1) -> None: + super().__init__() + self.conv1 = conv3x3(in_planes, planes, stride) + self.conv2 = conv3x3(planes, planes) + self.bn1 = nn.BatchNorm2d(planes) + self.bn2 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + + if stride == 1: + self.downsample = None + else: + self.downsample = nn.Sequential(conv1x1(in_planes, planes, stride=stride), nn.BatchNorm2d(planes)) + + def forward(self, x: Tensor) -> Tensor: + y = x + y = self.relu(self.bn1(self.conv1(y))) + y = self.bn2(self.conv2(y)) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class ResNetFPN_8_2(nn.Module): + """ResNet+FPN, output resolution are 1/8 and 1/2. + + Each block has 2 layers. + """ + + def __init__(self, config: Dict[str, Any]) -> None: + super().__init__() + # Config + block = BasicBlock + initial_dim = config["initial_dim"] + block_dims = config["block_dims"] + + # Class Variable + self.in_planes = initial_dim + + # Networks + self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = nn.BatchNorm2d(initial_dim) + self.relu = nn.ReLU(inplace=True) + + self.layer1 = self._make_layer(block, block_dims[0], stride=1) # 1/2 + self.layer2 = self._make_layer(block, block_dims[1], stride=2) # 1/4 + self.layer3 = self._make_layer(block, block_dims[2], stride=2) # 1/8 + + # 3. FPN upsample + self.layer3_outconv = conv1x1(block_dims[2], block_dims[2]) + self.layer2_outconv = conv1x1(block_dims[1], block_dims[2]) + self.layer2_outconv2 = nn.Sequential( + conv3x3(block_dims[2], block_dims[2]), + nn.BatchNorm2d(block_dims[2]), + nn.LeakyReLU(), + conv3x3(block_dims[2], block_dims[1]), + ) + self.layer1_outconv = conv1x1(block_dims[0], block_dims[1]) + self.layer1_outconv2 = nn.Sequential( + conv3x3(block_dims[1], block_dims[1]), + nn.BatchNorm2d(block_dims[1]), + nn.LeakyReLU(), + conv3x3(block_dims[1], block_dims[0]), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential: + layer1 = block(self.in_planes, dim, stride=stride) + layer2 = block(dim, dim, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x: Tensor) -> List[Tensor]: + # ResNet Backbone + x0 = self.relu(self.bn1(self.conv1(x))) + x1 = self.layer1(x0) # 1/2 + x2 = self.layer2(x1) # 1/4 + x3 = self.layer3(x2) # 1/8 + + # FPN + x3_out = self.layer3_outconv(x3) + + x2_out = self.layer2_outconv(x2) + x3_out_2x = F.interpolate(x3_out, size=(x2_out.shape[2:]), mode="bilinear", align_corners=True) + x2_out = self.layer2_outconv2(x2_out + x3_out_2x) + + x1_out = self.layer1_outconv(x1) + x2_out_2x = F.interpolate(x2_out, size=(x1_out.shape[2:]), mode="bilinear", align_corners=True) + x1_out = self.layer1_outconv2(x1_out + x2_out_2x) + + return [x3_out, x1_out] + + +class ResNetFPN_16_4(nn.Module): + """ResNet+FPN, output resolution are 1/16 and 1/4. + + Each block has 2 layers. + """ + + def __init__(self, config: Dict[str, Any]) -> None: + super().__init__() + # Config + block = BasicBlock + initial_dim = config["initial_dim"] + block_dims = config["block_dims"] + + # Class Variable + self.in_planes = initial_dim + + # Networks + self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = nn.BatchNorm2d(initial_dim) + self.relu = nn.ReLU(inplace=True) + + self.layer1 = self._make_layer(block, block_dims[0], stride=1) # 1/2 + self.layer2 = self._make_layer(block, block_dims[1], stride=2) # 1/4 + self.layer3 = self._make_layer(block, block_dims[2], stride=2) # 1/8 + self.layer4 = self._make_layer(block, block_dims[3], stride=2) # 1/16 + + # 3. FPN upsample + self.layer4_outconv = conv1x1(block_dims[3], block_dims[3]) + self.layer3_outconv = conv1x1(block_dims[2], block_dims[3]) + self.layer3_outconv2 = nn.Sequential( + conv3x3(block_dims[3], block_dims[3]), + nn.BatchNorm2d(block_dims[3]), + nn.LeakyReLU(), + conv3x3(block_dims[3], block_dims[2]), + ) + + self.layer2_outconv = conv1x1(block_dims[1], block_dims[2]) + self.layer2_outconv2 = nn.Sequential( + conv3x3(block_dims[2], block_dims[2]), + nn.BatchNorm2d(block_dims[2]), + nn.LeakyReLU(), + conv3x3(block_dims[2], block_dims[1]), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential: + layer1 = block(self.in_planes, dim, stride=stride) + layer2 = block(dim, dim, stride=1) + layers = (layer1, layer2) + + self.in_planes = dim + return nn.Sequential(*layers) + + def forward(self, x: Tensor) -> List[Tensor]: + # ResNet Backbone + x0 = self.relu(self.bn1(self.conv1(x))) + x1 = self.layer1(x0) # 1/2 + x2 = self.layer2(x1) # 1/4 + x3 = self.layer3(x2) # 1/8 + x4 = self.layer4(x3) # 1/16 + + # FPN + x4_out = self.layer4_outconv(x4) + + x4_out_2x = F.interpolate(x4_out, scale_factor=2.0, mode="bilinear", align_corners=True) + x3_out = self.layer3_outconv(x3) + x3_out = self.layer3_outconv2(x3_out + x4_out_2x) + + x3_out_2x = F.interpolate(x3_out, scale_factor=2.0, mode="bilinear", align_corners=True) + x2_out = self.layer2_outconv(x2) + x2_out = self.layer2_outconv2(x2_out + x3_out_2x) + + return [x4_out, x2_out] diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr.py new file mode 100644 index 0000000000000000000000000000000000000000..0841c2f00baf3802d678d5f10a8215039fb9400f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr.py @@ -0,0 +1,212 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any, Optional + +import torch + +from kornia.core import Module, Tensor +from kornia.geometry import resize + +from .backbone import build_backbone +from .loftr_module import FinePreprocess, LocalFeatureTransformer +from .utils.coarse_matching import CoarseMatching +from .utils.fine_matching import FineMatching +from .utils.position_encoding import PositionEncodingSine + +urls: dict[str, str] = {} +urls["outdoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt" +urls["indoor_new"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor_ds_new.ckpt" +urls["indoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt" + +# Comments: the config below is the one corresponding to the pretrained models +# Some do not change there anything, unless you want to retrain it. + +default_cfg = { + "backbone_type": "ResNetFPN", + "resolution": (8, 2), + "fine_window_size": 5, + "fine_concat_coarse_feat": True, + "resnetfpn": {"initial_dim": 128, "block_dims": [128, 196, 256]}, + "coarse": { + "d_model": 256, + "d_ffn": 256, + "nhead": 8, + "layer_names": ["self", "cross", "self", "cross", "self", "cross", "self", "cross"], + "attention": "linear", + "temp_bug_fix": False, + }, + "match_coarse": { + "thr": 0.2, + "border_rm": 2, + "match_type": "dual_softmax", + "dsmax_temperature": 0.1, + "skh_iters": 3, + "skh_init_bin_score": 1.0, + "skh_prefilter": True, + "train_coarse_percent": 0.4, + "train_pad_num_gt_min": 200, + }, + "fine": {"d_model": 128, "d_ffn": 128, "nhead": 8, "layer_names": ["self", "cross"], "attention": "linear"}, +} + + +class LoFTR(Module): + r"""Module, which finds correspondences between two images. + + This is based on the original code from paper "LoFTR: Detector-Free Local + Feature Matching with Transformers". See :cite:`LoFTR2021` for more details. + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + config: Dict with initialization parameters. Do not pass it, unless you know what you are doing`. + pretrained: Download and set pretrained weights to the model. Options: 'outdoor', 'indoor'. + 'outdoor' is trained on the MegaDepth dataset and 'indoor' + on the ScanNet. + + Returns: + Dictionary with image correspondences and confidence scores. + + Example: + >>> img1 = torch.rand(1, 1, 320, 200) + >>> img2 = torch.rand(1, 1, 128, 128) + >>> input = {"image0": img1, "image1": img2} + >>> loftr = LoFTR('outdoor') + >>> out = loftr(input) + + """ + + def __init__(self, pretrained: Optional[str] = "outdoor", config: dict[str, Any] = default_cfg) -> None: + super().__init__() + # Misc + self.config = config + if pretrained == "indoor_new": + self.config["coarse"]["temp_bug_fix"] = True + # Modules + self.backbone = build_backbone(config) + self.pos_encoding = PositionEncodingSine( + config["coarse"]["d_model"], temp_bug_fix=config["coarse"]["temp_bug_fix"] + ) + self.loftr_coarse = LocalFeatureTransformer(config["coarse"]) + self.coarse_matching = CoarseMatching(config["match_coarse"]) + self.fine_preprocess = FinePreprocess(config) + self.loftr_fine = LocalFeatureTransformer(config["fine"]) + self.fine_matching = FineMatching() + self.pretrained = pretrained + if pretrained is not None: + if pretrained not in urls.keys(): + raise ValueError(f"pretrained should be None or one of {urls.keys()}") + + pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict["state_dict"]) + self.eval() + + def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]: + """Run forward. + + Args: + data: dictionary containing the input data in the following format: + + Keyword Args: + image0: left image with shape :math:`(N, 1, H1, W1)`. + image1: right image with shape :math:`(N, 1, H2, W2)`. + mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`. + mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`. + + Returns: + - ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`. + - ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`. + - ``confidence``, confidence score [0, 1] :math:`(NC)`. + - ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`. + + """ + # 1. Local Feature CNN + _data: dict[str, Tensor | int | torch.Size] = { + "bs": data["image0"].size(0), + "hw0_i": data["image0"].shape[2:], + "hw1_i": data["image1"].shape[2:], + } + + if _data["hw0_i"] == _data["hw1_i"]: # faster & better BN convergence + feats_c, feats_f = self.backbone(torch.cat([data["image0"], data["image1"]], dim=0)) + (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(_data["bs"]), feats_f.split(_data["bs"]) + else: # handle different input shapes + (feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data["image0"]), self.backbone(data["image1"]) + + _data.update( + { + "hw0_c": feat_c0.shape[2:], + "hw1_c": feat_c1.shape[2:], + "hw0_f": feat_f0.shape[2:], + "hw1_f": feat_f1.shape[2:], + } + ) + + # 2. coarse-level loftr module + # add featmap with positional encoding, then flatten it to sequence [N, HW, C] + + # feat_c0 = rearrange(self.pos_encoding(feat_c0), 'n c h w -> n (h w) c') + # feat_c1 = rearrange(self.pos_encoding(feat_c1), 'n c h w -> n (h w) c') + feat_c0 = self.pos_encoding(feat_c0).permute(0, 2, 3, 1) + n, h, w, c = feat_c0.shape + feat_c0 = feat_c0.reshape(n, -1, c) + + feat_c1 = self.pos_encoding(feat_c1).permute(0, 2, 3, 1) + n1, h1, w1, c1 = feat_c1.shape + feat_c1 = feat_c1.reshape(n1, -1, c1) + + mask_c0 = mask_c1 = None # mask is useful in training + if "mask0" in data: + mask_c0 = resize(data["mask0"], _data["hw0_c"], interpolation="nearest").flatten(-2) + if "mask1" in data: + mask_c1 = resize(data["mask1"], _data["hw1_c"], interpolation="nearest").flatten(-2) + feat_c0, feat_c1 = self.loftr_coarse(feat_c0, feat_c1, mask_c0, mask_c1) + + # 3. match coarse-level + self.coarse_matching(feat_c0, feat_c1, _data, mask_c0=mask_c0, mask_c1=mask_c1) + + # 4. fine-level refinement + feat_f0_unfold, feat_f1_unfold = self.fine_preprocess(feat_f0, feat_f1, feat_c0, feat_c1, _data) + if feat_f0_unfold.size(0) != 0: # at least one coarse level predicted + feat_f0_unfold, feat_f1_unfold = self.loftr_fine(feat_f0_unfold, feat_f1_unfold) + + # 5. match fine-level + self.fine_matching(feat_f0_unfold, feat_f1_unfold, _data) + + rename_keys: dict[str, str] = { + "mkpts0_f": "keypoints0", + "mkpts1_f": "keypoints1", + "mconf": "confidence", + "b_ids": "batch_indexes", + } + out: dict[str, Tensor] = {} + for k, v in rename_keys.items(): + _d = _data[k] + if isinstance(_d, Tensor): + out[v] = _d + else: + raise TypeError(f"Expected Tensor for item `{k}`. Gotcha {type(_d)}") + return out + + def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override] + for k in list(state_dict.keys()): + if k.startswith("matcher."): + state_dict[k.replace("matcher.", "", 1)] = state_dict.pop(k) + return super().load_state_dict(state_dict, *args, **kwargs) diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ddbb95bb2030463984a44c6bf2c9c28caf0faf9 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from .fine_preprocess import FinePreprocess +from .transformer import LocalFeatureTransformer diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/fine_preprocess.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/fine_preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..06ce46b11070359b229496288e8bc146eeda6a20 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/fine_preprocess.py @@ -0,0 +1,95 @@ +# 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. +# + +from typing import Any, Dict, Tuple + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core import Module, Tensor + + +class FinePreprocess(Module): + def __init__(self, config: Dict[str, Any]) -> None: + super().__init__() + + self.config = config + self.cat_c_feat = config["fine_concat_coarse_feat"] + self.W = self.config["fine_window_size"] + + d_model_c = self.config["coarse"]["d_model"] + d_model_f = self.config["fine"]["d_model"] + self.d_model_f = d_model_f + if self.cat_c_feat: + self.down_proj = nn.Linear(d_model_c, d_model_f, bias=True) + self.merge_feat = nn.Linear(2 * d_model_f, d_model_f, bias=True) + + self._reset_parameters() + + def _reset_parameters(self) -> None: + for p in self.parameters(): + if p.dim() > 1: + nn.init.kaiming_normal_(p, mode="fan_out", nonlinearity="relu") + + def forward( + self, feat_f0: Tensor, feat_f1: Tensor, feat_c0: Tensor, feat_c1: Tensor, data: Dict[str, Any] + ) -> Tuple[Tensor, Tensor]: + W = self.W + stride = data["hw0_f"][0] // data["hw0_c"][0] + + data.update({"W": W}) + if data["b_ids"].shape[0] == 0: + feat0 = torch.empty(0, self.W**2, self.d_model_f, device=feat_f0.device) + feat1 = torch.empty(0, self.W**2, self.d_model_f, device=feat_f0.device) + return feat0, feat1 + + # 1. unfold(crop) all local windows + feat_f0_unfold = F.unfold(feat_f0, kernel_size=(W, W), stride=stride, padding=W // 2) + + # feat_f0_unfold = rearrange(feat_f0_unfold, 'n (c ww) l -> n l ww c', ww=W**2) + n0, cww0, l0 = feat_f0_unfold.shape + c0 = cww0 // (W * W) + feat_f0_unfold = feat_f0_unfold.reshape(n0, c0, -1, l0).permute(0, 3, 2, 1) + + feat_f1_unfold = F.unfold(feat_f1, kernel_size=(W, W), stride=stride, padding=W // 2) + # feat_f1_unfold = rearrange(feat_f1_unfold, 'n (c ww) l -> n l ww c', ww=W**2) + n1, cww1, l1 = feat_f1_unfold.shape + c1 = cww1 // (W * W) + feat_f1_unfold = feat_f1_unfold.reshape(n1, c1, -1, l1).permute(0, 3, 2, 1) + + # 2. select only the predicted matches + feat_f0_unfold = feat_f0_unfold[data["b_ids"], data["i_ids"]] # [n, ww, cf] + feat_f1_unfold = feat_f1_unfold[data["b_ids"], data["j_ids"]] + + # option: use coarse-level loftr feature as context: concat and linear + if self.cat_c_feat: + feat_c_win = self.down_proj( + torch.cat([feat_c0[data["b_ids"], data["i_ids"]], feat_c1[data["b_ids"], data["j_ids"]]], 0) + ) # [2n, c] + feat_cf_win = self.merge_feat( + torch.cat( + [ + torch.cat([feat_f0_unfold, feat_f1_unfold], 0), # [2n, ww, cf] + feat_c_win.unsqueeze(1).repeat(1, W**2, 1), # [2n, ww, cf] + ], + -1, + ) + ) + feat_f0_unfold, feat_f1_unfold = torch.chunk(feat_cf_win, 2, dim=0) + + return feat_f0_unfold, feat_f1_unfold diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/linear_attention.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/linear_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..a4eafe4def0db136d599a6c3dc7b68f8ffb30dc2 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/linear_attention.py @@ -0,0 +1,123 @@ +# 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. +# + +"""Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention". + +Modified from: https://github.com/idiap/fast- +transformers/blob/master/fast_transformers/attention/linear_attention.py. +""" + +from typing import Optional + +import torch +from torch.nn import Dropout + +from kornia.core import Module, Tensor + + +def elu_feature_map(x: Tensor) -> Tensor: + """Apply elu activation.""" + return torch.nn.functional.elu(x) + 1 + + +class LinearAttention(Module): + def __init__(self, eps: float = 1e-6) -> None: + super().__init__() + self.feature_map = elu_feature_map + self.eps = eps + + def forward( + self, + queries: Tensor, + keys: Tensor, + values: Tensor, + q_mask: Optional[Tensor] = None, + kv_mask: Optional[Tensor] = None, + ) -> Tensor: + """Multi-Head linear attention proposed in "Transformers are RNNs". + + Args: + queries: [N, L, H, D] + keys: [N, S, H, D] + values: [N, S, H, D] + q_mask: [N, L] + kv_mask: [N, S] + + Returns: + queried_values: (N, L, H, D) + + """ + Q = self.feature_map(queries) + K = self.feature_map(keys) + + # set padded position to zero + if q_mask is not None: + Q = Q * q_mask[:, :, None, None] + if kv_mask is not None: + K = K * kv_mask[:, :, None, None] + values = values * kv_mask[:, :, None, None] + + v_length = values.size(1) + values = values / v_length # prevent fp16 overflow + KV = torch.einsum("nshd,nshv->nhdv", K, values) # (S,D)' @ S,V + Z = 1 / (torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps) + queried_values = torch.einsum("nlhd,nhdv,nlh->nlhv", Q, KV, Z) * v_length + + return queried_values.contiguous() + + +class FullAttention(Module): + def __init__(self, use_dropout: bool = False, attention_dropout: float = 0.1) -> None: + super().__init__() + self.use_dropout = use_dropout + self.dropout = Dropout(attention_dropout) + + def forward( + self, + queries: Tensor, + keys: Tensor, + values: Tensor, + q_mask: Optional[Tensor] = None, + kv_mask: Optional[Tensor] = None, + ) -> Tensor: + """Multi-head scaled dot-product attention, a.k.a full attention. + + Args: + queries: [N, L, H, D] + keys: [N, S, H, D] + values: [N, S, H, D] + q_mask: [N, L] + kv_mask: [N, S] + + Returns: + queried_values: (N, L, H, D) + + """ + # Compute the unnormalized attention and apply the masks + QK = torch.einsum("nlhd,nshd->nlsh", queries, keys) + if kv_mask is not None and q_mask is not None: + QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float("-inf")) + + # Compute the attention and the weighted average + softmax_temp = 1.0 / queries.size(3) ** 0.5 # sqrt(D) + A = torch.softmax(softmax_temp * QK, dim=2) + if self.use_dropout: + A = self.dropout(A) + + queried_values = torch.einsum("nlsh,nshd->nlhd", A, values) + + return queried_values.contiguous() diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/transformer.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..bea9e97bb3ad804c9d941b9204c0a2c6b564369b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/loftr_module/transformer.py @@ -0,0 +1,129 @@ +# 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. +# + +from __future__ import annotations + +import copy +from typing import Any, Literal, Optional + +import torch +from torch import nn + +from kornia.core import Module, Tensor + +from .linear_attention import FullAttention, LinearAttention + + +class LoFTREncoderLayer(Module): + def __init__(self, d_model: int, nhead: int, attention: Optional[Literal["linear"]] = "linear") -> None: + super().__init__() + + self.dim = d_model // nhead + self.nhead = nhead + + # multi-head attention + self.q_proj = nn.Linear(d_model, d_model, bias=False) + self.k_proj = nn.Linear(d_model, d_model, bias=False) + self.v_proj = nn.Linear(d_model, d_model, bias=False) + self.attention = LinearAttention() if attention == "linear" else FullAttention() + self.merge = nn.Linear(d_model, d_model, bias=False) + + # feed-forward network + self.mlp = nn.Sequential( + nn.Linear(d_model * 2, d_model * 2, bias=False), nn.ReLU(True), nn.Linear(d_model * 2, d_model, bias=False) + ) + + # norm and dropout + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + + def forward( + self, x: Tensor, source: Tensor, x_mask: Optional[Tensor] = None, source_mask: Optional[Tensor] = None + ) -> Tensor: + """Run forward. + + Args: + x: [N, L, C] + source: [N, S, C] + x_mask: [N, L] (optional) + source_mask: [N, S] (optional) + + """ + bs = x.size(0) + query, key, value = x, source, source + + # multi-head attention + query = self.q_proj(query).view(bs, -1, self.nhead, self.dim) # [N, L, (H, D)] + key = self.k_proj(key).view(bs, -1, self.nhead, self.dim) # [N, S, (H, D)] + value = self.v_proj(value).view(bs, -1, self.nhead, self.dim) + message = self.attention(query, key, value, q_mask=x_mask, kv_mask=source_mask) # [N, L, (H, D)] + message = self.merge(message.view(bs, -1, self.nhead * self.dim)) # [N, L, C] + message = self.norm1(message) + + # feed-forward network + message = self.mlp(torch.cat([x, message], dim=2)) + message = self.norm2(message) + + return x + message + + +class LocalFeatureTransformer(Module): + """A Local Feature Transformer (LoFTR) module.""" + + def __init__(self, config: dict[str, Any]) -> None: + super().__init__() + + self.config = config + self.d_model = config["d_model"] + self.nhead = config["nhead"] + self.layer_names = config["layer_names"] + encoder_layer = LoFTREncoderLayer(config["d_model"], config["nhead"], config["attention"]) + self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(len(self.layer_names))]) + self._reset_parameters() + + def _reset_parameters(self) -> None: + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def forward( + self, feat0: Tensor, feat1: Tensor, mask0: None | Tensor = None, mask1: None | Tensor = None + ) -> tuple[Tensor, Tensor]: + """Run forward. + + Args: + feat0: [N, L, C] + feat1: [N, S, C] + mask0: [N, L] (optional) + mask1: [N, S] (optional) + + """ + if self.d_model != feat0.size(2): + msg = "the feature number of src and transformer must be equal" + raise ValueError(msg) + + for layer, name in zip(self.layers, self.layer_names): + if name == "self": + feat0 = layer(feat0, feat0, mask0, mask0) + feat1 = layer(feat1, feat1, mask1, mask1) + elif name == "cross": + feat0 = layer(feat0, feat1, mask0, mask1) + feat1 = layer(feat1, feat0, mask1, mask0) + else: + raise KeyError + + return feat0, feat1 diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d273d5cba09827eabbe13c7f953f35f94a5f9ea --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/__init__.py @@ -0,0 +1,16 @@ +# 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. +# diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/coarse_matching.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/coarse_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..66c862e61e73888b22271b692095df3f7364c4b4 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/coarse_matching.py @@ -0,0 +1,294 @@ +# 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. +# + +from typing import Any, Dict, Optional, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.core import Module, Tensor + +INF = 1e9 + + +def mask_border(m: Tensor, b: int, v: Union[Tensor, float, bool]) -> None: + """Mask borders with value. + + Args: + m (torch.Tensor): [N, H0, W0, H1, W1] + b (int): border size. + v (m.dtype): border value. + """ + if b <= 0: + return + + m[:, :b] = v + m[:, :, :b] = v + m[:, :, :, :b] = v + m[:, :, :, :, :b] = v + m[:, -b:] = v + m[:, :, -b:] = v + m[:, :, :, -b:] = v + m[:, :, :, :, -b:] = v + + +def mask_border_with_padding(m: Tensor, bd: int, v: Union[Tensor, float, bool], p_m0: Tensor, p_m1: Tensor) -> None: + """Apply masking to a padded boarder.""" + if bd <= 0: + return + + m[:, :bd] = v + m[:, :, :bd] = v + m[:, :, :, :bd] = v + m[:, :, :, :, :bd] = v + + h0s, w0s = p_m0.sum(1).max(-1)[0].int(), p_m0.sum(-1).max(-1)[0].int() + h1s, w1s = p_m1.sum(1).max(-1)[0].int(), p_m1.sum(-1).max(-1)[0].int() + for b_idx, (h0, w0, h1, w1) in enumerate(zip(h0s, w0s, h1s, w1s)): + m[b_idx, h0 - bd :] = v + m[b_idx, :, w0 - bd :] = v + m[b_idx, :, :, h1 - bd :] = v + m[b_idx, :, :, :, w1 - bd :] = v + + +def compute_max_candidates(p_m0: Tensor, p_m1: Tensor) -> Tensor: + """Compute the max candidates of all pairs within a batch. + + Args: + p_m0: padded mask 0 + p_m1: padded mask 1 + + """ + h0s, w0s = p_m0.sum(1).max(-1)[0], p_m0.sum(-1).max(-1)[0] + h1s, w1s = p_m1.sum(1).max(-1)[0], p_m1.sum(-1).max(-1)[0] + max_cand = torch.sum(torch.min(torch.stack([h0s * w0s, h1s * w1s], -1), -1)[0]) + return max_cand + + +class CoarseMatching(Module): + def __init__(self, config: Dict[str, Any]) -> None: + super().__init__() + self.config = config + # general config + self.thr = config["thr"] + self.border_rm = config["border_rm"] + # -- # for training fine-level LoFTR + self.train_coarse_percent = config["train_coarse_percent"] + self.train_pad_num_gt_min = config["train_pad_num_gt_min"] + + # we provide 2 options for differentiable matching + self.match_type = config["match_type"] + if self.match_type == "dual_softmax": + self.temperature = config["dsmax_temperature"] + elif self.match_type == "sinkhorn": + try: + from .superglue import log_optimal_transport + except ImportError: + raise ImportError("download superglue.py first!") from None + self.log_optimal_transport = log_optimal_transport + self.bin_score = nn.Parameter(torch.tensor(config["skh_init_bin_score"], requires_grad=True)) + self.skh_iters = config["skh_iters"] + self.skh_prefilter = config["skh_prefilter"] + else: + raise NotImplementedError + + def forward( + self, + feat_c0: Tensor, + feat_c1: Tensor, + data: Dict[str, Tensor], + mask_c0: Optional[Tensor] = None, + mask_c1: Optional[Tensor] = None, + ) -> None: + """Run forward. + + Args: + feat_c0 (torch.Tensor): [N, L, C] + feat_c1 (torch.Tensor): [N, S, C] + data (dict) + mask_c0 (torch.Tensor): [N, L] (optional) + mask_c1 (torch.Tensor): [N, S] (optional) + Update: + data (dict): { + 'b_ids' (torch.Tensor): [M'], + 'i_ids' (torch.Tensor): [M'], + 'j_ids' (torch.Tensor): [M'], + 'gt_mask' (torch.Tensor): [M'], + 'mkpts0_c' (torch.Tensor): [M, 2], + 'mkpts1_c' (torch.Tensor): [M, 2], + 'mconf' (torch.Tensor): [M]} + NOTE: M' != M during training. + + """ + _, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2) + + # normalize + feat_c0, feat_c1 = (feat / feat.shape[-1] ** 0.5 for feat in [feat_c0, feat_c1]) + + if self.match_type == "dual_softmax": + sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature + if mask_c0 is not None and mask_c1 is not None: + sim_matrix.masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF) + conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2) + + elif self.match_type == "sinkhorn": + # sinkhorn, dustbin included + sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) + if mask_c0 is not None and mask_c1 is not None: + sim_matrix[:, :L, :S].masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF) + + # build uniform prior & use sinkhorn + log_assign_matrix = self.log_optimal_transport(sim_matrix, self.bin_score, self.skh_iters) + assign_matrix = log_assign_matrix.exp() + conf_matrix = assign_matrix[:, :-1, :-1] + + # filter prediction with dustbin score (only in evaluation mode) + if not self.training and self.skh_prefilter: + filter0 = (assign_matrix.max(dim=2)[1] == S)[:, :-1] # [N, L] + filter1 = (assign_matrix.max(dim=1)[1] == L)[:, :-1] # [N, S] + conf_matrix[filter0[..., None].repeat(1, 1, S)] = 0 + conf_matrix[filter1[:, None].repeat(1, L, 1)] = 0 + + if self.config["sparse_spvs"]: + data.update({"conf_matrix_with_bin": assign_matrix.clone()}) + + data.update({"conf_matrix": conf_matrix}) + + # predict coarse matches from conf_matrix + data.update(**self.get_coarse_match(conf_matrix, data)) + + @torch.no_grad() + def get_coarse_match(self, conf_matrix: Tensor, data: Dict[str, Tensor]) -> Dict[str, Tensor]: + """Get corase matching. + + Args: + conf_matrix (torch.Tensor): [N, L, S] + data (dict): with keys ['hw0_i', 'hw1_i', 'hw0_c', 'hw1_c'] + + Returns: + coarse_matches (dict): { + 'b_ids' (torch.Tensor): [M'], + 'i_ids' (torch.Tensor): [M'], + 'j_ids' (torch.Tensor): [M'], + 'gt_mask' (torch.Tensor): [M'], + 'm_bids' (torch.Tensor): [M], + 'mkpts0_c' (torch.Tensor): [M, 2], + 'mkpts1_c' (torch.Tensor): [M, 2], + 'mconf' (torch.Tensor): [M]} + + """ + axes_lengths = { + "h0c": data["hw0_c"][0], + "w0c": data["hw0_c"][1], + "h1c": data["hw1_c"][0], + "w1c": data["hw1_c"][1], + } + _device = conf_matrix.device + # 1. confidence thresholding + mask = conf_matrix > self.thr + N = conf_matrix.shape[0] + mask = mask.reshape(N, axes_lengths["h0c"], axes_lengths["w0c"], axes_lengths["h1c"], axes_lengths["w1c"]) + # mask = rearrange(mask, 'b (h0c w0c) (h1c w1c) -> b h0c w0c h1c w1c', + # **axes_lengths) + if "mask0" not in data: + mask_border(mask, self.border_rm, False) + else: + mask_border_with_padding(mask, self.border_rm, False, data["mask0"], data["mask1"]) + mask = mask.reshape(N, axes_lengths["h0c"] * axes_lengths["w0c"], axes_lengths["h1c"] * axes_lengths["w1c"]) + # rearrange(mask, 'b h0c w0c h1c w1c -> b (h0c w0c) (h1c w1c)', + # **axes_lengths) + + # 2. mutual nearest + mask = ( + mask + * (conf_matrix == conf_matrix.max(dim=2, keepdim=True)[0]) + * (conf_matrix == conf_matrix.max(dim=1, keepdim=True)[0]) + ) + + # 3. find all valid coarse matches + # this only works when at most one `True` in each row + mask_v, all_j_ids = mask.max(dim=2) + b_ids, i_ids = torch.where(mask_v) + j_ids = all_j_ids[b_ids, i_ids] + mconf = conf_matrix[b_ids, i_ids, j_ids] + + # 4. Random sampling of training samples for fine-level LoFTR + # (optional) pad samples with gt coarse-level matches + if self.training: + # NOTE: + # The sampling is performed across all pairs in a batch without manually balancing + # #samples for fine-level increases w.r.t. batch_size + if "mask0" not in data: + num_candidates_max = mask.size(0) * max(mask.size(1), mask.size(2)) + else: + num_candidates_max = compute_max_candidates(data["mask0"], data["mask1"]) + num_matches_train = num_candidates_max * self.train_coarse_percent + num_matches_train = int(num_matches_train) + num_matches_pred = len(b_ids) + if self.train_pad_num_gt_min >= num_matches_train: + msg = "min-num-gt-pad should be less than num-train-matches" + raise ValueError(msg) + + # pred_indices is to select from prediction + if num_matches_pred <= num_matches_train - self.train_pad_num_gt_min: + pred_indices = torch.arange(num_matches_pred, device=_device) + else: + pred_indices = torch.randint( + num_matches_pred, (num_matches_train - self.train_pad_num_gt_min,), device=_device + ) + + # gt_pad_indices is to select from gt padding. e.g. max(3787-4800, 200) + gt_pad_indices = torch.randint( + len(data["spv_b_ids"]), + (max(num_matches_train - num_matches_pred, self.train_pad_num_gt_min),), + device=_device, + ) + mconf_gt = torch.zeros(len(data["spv_b_ids"]), device=_device) # set conf of gt paddings to all zero + + b_ids, i_ids, j_ids, mconf = ( # type: ignore + torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0) + for x, y in zip( + [b_ids, data["spv_b_ids"]], + [i_ids, data["spv_i_ids"]], + [j_ids, data["spv_j_ids"]], + [mconf, mconf_gt], + ) + ) + + # These matches select patches that feed into fine-level network + coarse_matches = {"b_ids": b_ids, "i_ids": i_ids, "j_ids": j_ids} + + # 4. Update with matches in original image resolution + scale = data["hw0_i"][0] / data["hw0_c"][0] + scale0 = scale * data["scale0"][b_ids] if "scale0" in data else scale + scale1 = scale * data["scale1"][b_ids] if "scale1" in data else scale + mkpts0_c = torch.stack([i_ids % data["hw0_c"][1], i_ids // data["hw0_c"][1]], dim=1) * scale0 + mkpts1_c = torch.stack([j_ids % data["hw1_c"][1], j_ids // data["hw1_c"][1]], dim=1) * scale1 + + # These matches is the current prediction (for visualization) + coarse_matches.update( + { + "gt_mask": mconf == 0, + "m_bids": b_ids[mconf != 0], # mconf == 0 => gt matches + "mkpts0_c": mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype), + "mkpts1_c": mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype), + "mconf": mconf[mconf != 0], + } + ) + + return coarse_matches diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/fine_matching.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/fine_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..23ffbc1c031363b6e01a8baced23295aeeaed7c1 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/fine_matching.py @@ -0,0 +1,99 @@ +# 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. +# + +from __future__ import annotations + +import math +from typing import Any + +import torch + +from kornia.core import Module, Tensor +from kornia.geometry.subpix import dsnt +from kornia.utils.grid import create_meshgrid + + +class FineMatching(Module): + """FineMatching with s2d paradigm.""" + + def __init__(self) -> None: + super().__init__() + + def forward(self, feat_f0: Tensor, feat_f1: Tensor, data: dict[str, Any]) -> None: + """Run forward. + + Args: + feat_f0 (torch.Tensor): [M, WW, C] + feat_f1 (torch.Tensor): [M, WW, C] + data (dict) + Update: + data (dict):{ + 'expec_f' (torch.Tensor): [M, 3], + 'mkpts0_f' (torch.Tensor): [M, 2], + 'mkpts1_f' (torch.Tensor): [M, 2]} + + """ + M, WW, C = feat_f0.shape + W = int(math.sqrt(WW)) + scale = data["hw0_i"][0] / data["hw0_f"][0] + self.M, self.W, self.WW, self.C, self.scale = M, W, WW, C, scale + + # corner case: if no coarse matches found + if M == 0: + if self.training: + raise ValueError("M >0, when training, see coarse_matching.py") + # logger.warning('No matches found in coarse-level.') + data.update( + { + "expec_f": torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype), + "mkpts0_f": data["mkpts0_c"], + "mkpts1_f": data["mkpts1_c"], + } + ) + return + + feat_f0_picked = feat_f0[:, WW // 2, :] + sim_matrix = torch.einsum("mc,mrc->mr", feat_f0_picked, feat_f1) + softmax_temp = 1.0 / C**0.5 + heatmap = torch.softmax(softmax_temp * sim_matrix, dim=1).view(-1, W, W) + + # compute coordinates from heatmap + coords_normalized = dsnt.spatial_expectation2d(heatmap[None], True)[0] # [M, 2] + grid_normalized = create_meshgrid( + W, W, normalized_coordinates=True, device=heatmap.device, dtype=heatmap.dtype + ).reshape(1, -1, 2) # [1, WW, 2] + + # compute std over + var = torch.sum(grid_normalized**2 * heatmap.view(-1, WW, 1), dim=1) - coords_normalized**2 # [M, 2] + std = torch.sum(torch.sqrt(torch.clamp(var, min=1e-10)), -1) # [M] clamp needed for numerical stability + + # for fine-level supervision + data.update({"expec_f": torch.cat([coords_normalized, std.unsqueeze(1)], -1)}) + + # compute absolute kpt coords + self.get_fine_match(coords_normalized, data) + + @torch.no_grad() + def get_fine_match(self, coords_normed: Tensor, data: dict[str, Any]) -> None: + W, _, _, scale = self.W, self.WW, self.C, self.scale + + # mkpts0_f and mkpts1_f + mkpts0_f = data["mkpts0_c"] + scale1 = scale * data["scale1"][data["b_ids"]] if "scale0" in data else scale + mkpts1_f = data["mkpts1_c"] + (coords_normed * (W // 2) * scale1)[: len(data["mconf"])] + + data.update({"mkpts0_f": mkpts0_f, "mkpts1_f": mkpts1_f}) diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/geometry.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..2676d72064ecb8c5e5328ee1ac37e29a0dca3589 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/geometry.py @@ -0,0 +1,80 @@ +# 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. +# + +from typing import Tuple + +import torch + +from kornia.core import Tensor + + +@torch.no_grad() +def warp_kpts( + kpts0: Tensor, depth0: Tensor, depth1: Tensor, T_0to1: Tensor, K0: Tensor, K1: Tensor +) -> Tuple[Tensor, Tensor]: + """Warp kpts0 from I0 to I1 with depth, K and Rt Also check covisibility and depth consistency. + + Depth is consistent if relative error < 0.2 (hard-coded). + + Args: + kpts0: [N, L, 2] - , + depth0: [N, H, W], + depth1: [N, H, W], + T_0to1: [N, 3, 4], + K0: [N, 3, 3], + K1: [N, 3, 3], + + Returns: + calculable_mask: [N, L] + warped_keypoints0: [N, L, 2] + + """ + kpts0_long = kpts0.round().long() + + # Sample depth, get calculable_mask on depth != 0 + kpts0_depth = torch.stack( + [depth0[i, kpts0_long[i, :, 1], kpts0_long[i, :, 0]] for i in range(kpts0.shape[0])], dim=0 + ) # (N, L) + nonzero_mask = kpts0_depth != 0 + + # Unproject + kpts0_h = torch.cat([kpts0, torch.ones_like(kpts0[:, :, [0]])], dim=-1) * kpts0_depth[..., None] # (N, L, 3) + kpts0_cam = K0.inverse() @ kpts0_h.transpose(2, 1) # (N, 3, L) + + # Rigid Transform + w_kpts0_cam = T_0to1[:, :3, :3] @ kpts0_cam + T_0to1[:, :3, [3]] # (N, 3, L) + w_kpts0_depth_computed = w_kpts0_cam[:, 2, :] + + # Project + w_kpts0_h = (K1 @ w_kpts0_cam).transpose(2, 1) # (N, L, 3) + w_kpts0 = w_kpts0_h[:, :, :2] / (w_kpts0_h[:, :, [2]] + 1e-4) # (N, L, 2), +1e-4 to avoid zero depth + + # Covisible Check + h, w = depth1.shape[1:3] + covisible_mask = ( + (w_kpts0[:, :, 0] > 0) * (w_kpts0[:, :, 0] < w - 1) * (w_kpts0[:, :, 1] > 0) * (w_kpts0[:, :, 1] < h - 1) + ) + w_kpts0_long = w_kpts0.long() + w_kpts0_long[~covisible_mask, :] = 0 + + w_kpts0_depth = torch.stack( + [depth1[i, w_kpts0_long[i, :, 1], w_kpts0_long[i, :, 0]] for i in range(w_kpts0_long.shape[0])], dim=0 + ) # (N, L) + consistent_mask = ((w_kpts0_depth - w_kpts0_depth_computed) / w_kpts0_depth).abs() < 0.2 + valid_mask = nonzero_mask * covisible_mask * consistent_mask + + return valid_mask, w_kpts0 diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/position_encoding.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..727d70870089c319fccbb0f041ac3703ea8c251e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/position_encoding.py @@ -0,0 +1,93 @@ +# 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. +# + +import math +from typing import Tuple + +import torch + +from kornia.core import Module, Tensor, cos, sin, zeros + + +class PositionEncodingSine(Module): + """A sinusoidal position encoding that generalized to 2-dimensional images.""" + + pe: Tensor + + def __init__(self, d_model: int, max_shape: Tuple[int, int] = (256, 256), temp_bug_fix: bool = True) -> None: + """Construct sinusoidal positional encoding. + + Args: + d_model: Dimensions of model input. + max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels + temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41), + the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact + on the final performance. For now, we keep both impls for backward compatibility. + We will remove the buggy impl after re-training all variants of our released models. + + """ + super().__init__() + self.d_model = d_model + self.temp_bug_fix = temp_bug_fix + + pe = self._create_position_encoding(max_shape) + self.register_buffer("pe", pe, persistent=False) # [1, C, H, W] + + def _create_position_encoding(self, max_shape: Tuple[int, int]) -> Tensor: + """Create a position encoding from scratch. + + For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape + should be (H//8, W//8). + """ + pe = zeros((self.d_model, *max_shape)) + y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0) + x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0) + if self.temp_bug_fix: + div_term = torch.exp( + torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / (self.d_model // 2)) + ) + else: # a buggy implementation (for backward compatibility only) + div_term = torch.exp( + torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / self.d_model // 2) + ) + div_term = div_term[:, None, None] # [C//4, 1, 1] + pe[0::4, :, :] = sin(x_position * div_term) + pe[1::4, :, :] = cos(x_position * div_term) + pe[2::4, :, :] = sin(y_position * div_term) + pe[3::4, :, :] = cos(y_position * div_term) + return pe.unsqueeze(0) + + def update_position_encoding_size(self, max_shape: Tuple[int, int]) -> None: + """Update position encoding to new max_shape. + + For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape + should be (H//8, W//8). + """ + self.pe = self._create_position_encoding(max_shape).to(self.pe.device) + + def forward(self, x: Tensor) -> Tensor: + """Run forward. + + Args: + x: [N, C, H, W] + + """ + if x.size(2) > self.pe.size(2) or x.size(3) > self.pe.size(3): + max_shape = (max(x.size(2), self.pe.size(2)), max(x.size(3), self.pe.size(3))) + self.update_position_encoding_size(max_shape) + + return x + self.pe[:, :, : x.size(2), : x.size(3)] diff --git a/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/supervision.py b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..b06a1903c89b5f3cfdcce52abdd7cff8ad7b7994 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/loftr/utils/supervision.py @@ -0,0 +1,170 @@ +# 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. +# + +from __future__ import annotations + +from typing import Any + +import torch + +from kornia.core import Tensor +from kornia.utils import create_meshgrid + +from .geometry import warp_kpts + + +# Coarse-Level supervision +@torch.no_grad() +def mask_pts_at_padded_regions(grid_pt: Tensor, mask: Tensor) -> Tensor: + """For megadepth dataset, zero-padding exists in images.""" + n, h, w = mask.shape + mask = mask.reshape(n, h * w).unsqueeze(-1).repeat(1, 1, 2) + # from einops import repeat + # mask = repeat(mask, 'n h w -> n (h w) c', c=2) + grid_pt[~mask.bool()] = 0 + return grid_pt + + +@torch.no_grad() +def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None: + """Perform coarse supervision. + + Update: + data (dict): { + "conf_matrix_gt": [N, hw0, hw1], + 'spv_b_ids': [M] + 'spv_i_ids': [M] + 'spv_j_ids': [M] + 'spv_w_pt0_i': [N, hw0, 2], in original image resolution + 'spv_pt1_i': [N, hw1, 2], in original image resolution + } + + Note: + - for scannet dataset, there're 3 kinds of resolution {i, c, f} + - for megadepth dataset, there're 4 kinds of resolution {i, i_resize, c, f} + + """ + # 1. misc + device = data["image0"].device + N, _, H0, W0 = data["image0"].shape + _, _, H1, W1 = data["image1"].shape + scale = config["LOFTR"]["RESOLUTION"][0] + scale0 = scale * data["scale0"][:, None] if "scale0" in data else scale + scale1 = scale * data["scale1"][:, None] if "scale0" in data else scale + h0, w0, h1, w1 = (x // scale for x in [H0, W0, H1, W1]) + + # 2. warp grids + # create kpts in meshgrid and resize them to image resolution + grid_pt0_c = create_meshgrid(h0, w0, False, device).reshape(1, h0 * w0, 2).expand(N, h0 * w0, 2) # [N, hw, 2] + grid_pt0_i = scale0 * grid_pt0_c + grid_pt1_c = create_meshgrid(h1, w1, False, device).reshape(1, h1 * w1, 2).expand(N, h1 * w1, 2) + grid_pt1_i = scale1 * grid_pt1_c + + # mask padded region to (0, 0), so no need to manually mask conf_matrix_gt + if "mask0" in data: + grid_pt0_i = mask_pts_at_padded_regions(grid_pt0_i, data["mask0"]) + grid_pt1_i = mask_pts_at_padded_regions(grid_pt1_i, data["mask1"]) + + # warp kpts bi-directionally and resize them to coarse-level resolution + # (no depth consistency check, since it leads to worse results experimentally) + # (unhandled edge case: points with 0-depth will be warped to the left-up corner) + _, w_pt0_i = warp_kpts(grid_pt0_i, data["depth0"], data["depth1"], data["T_0to1"], data["K0"], data["K1"]) + _, w_pt1_i = warp_kpts(grid_pt1_i, data["depth1"], data["depth0"], data["T_1to0"], data["K1"], data["K0"]) + w_pt0_c = w_pt0_i / scale1 + w_pt1_c = w_pt1_i / scale0 + + # 3. check if mutual nearest neighbor + w_pt0_c_round = w_pt0_c[:, :, :].round().long() + nearest_index1 = w_pt0_c_round[..., 0] + w_pt0_c_round[..., 1] * w1 + w_pt1_c_round = w_pt1_c[:, :, :].round().long() + nearest_index0 = w_pt1_c_round[..., 0] + w_pt1_c_round[..., 1] * w0 + + # corner case: out of boundary + def out_bound_mask(pt: Tensor, w: Tensor, h: Tensor) -> Tensor: + return (pt[..., 0] < 0) + (pt[..., 0] >= w) + (pt[..., 1] < 0) + (pt[..., 1] >= h) + + nearest_index1[out_bound_mask(w_pt0_c_round, w1, h1)] = 0 + nearest_index0[out_bound_mask(w_pt1_c_round, w0, h0)] = 0 + + loop_back = torch.stack([nearest_index0[_b][_i] for _b, _i in enumerate(nearest_index1)], dim=0) + correct_0to1 = loop_back == torch.arange(h0 * w0, device=device)[None].repeat(N, 1) + correct_0to1[:, 0] = False # ignore the top-left corner + + # 4. construct a gt conf_matrix + conf_matrix_gt = torch.zeros(N, h0 * w0, h1 * w1, device=device) + b_ids, i_ids = torch.where(correct_0to1 != 0) + j_ids = nearest_index1[b_ids, i_ids] + + conf_matrix_gt[b_ids, i_ids, j_ids] = 1 + data.update({"conf_matrix_gt": conf_matrix_gt}) + + # 5. save coarse matches(gt) for training fine level + if len(b_ids) == 0: + # this won't affect fine-level loss calculation + b_ids = torch.tensor([0], device=device) + i_ids = torch.tensor([0], device=device) + j_ids = torch.tensor([0], device=device) + + data.update({"spv_b_ids": b_ids, "spv_i_ids": i_ids, "spv_j_ids": j_ids}) + + # 6. save intermediate results (for fast fine-level computation) + data.update({"spv_w_pt0_i": w_pt0_i, "spv_pt1_i": grid_pt1_i}) + + +def compute_supervision_coarse(data: dict[str, Any], config: dict[str, Any]) -> None: + """Compute coarse supervision.""" + if len(set(data["dataset_name"])) != 1: + raise ValueError("Do not support mixed datasets training!") + data_source = data["dataset_name"][0] + if data_source.lower() in ["scannet", "megadepth"]: + spvs_coarse(data, config) + else: + raise ValueError(f"Unknown data source: {data_source}") + + +# Fine-Level supervision +@torch.no_grad() +def spvs_fine(data: dict[str, Any], config: dict[str, Any]) -> None: + """Perform fine supervision. + + Update: + data (dict):{ + "expec_f_gt": [M, 2]} + """ + # 1. misc + # w_pt0_i, pt1_i = data.pop('spv_w_pt0_i'), data.pop('spv_pt1_i') + w_pt0_i, pt1_i = data["spv_w_pt0_i"], data["spv_pt1_i"] + scale = config["LOFTR"]["RESOLUTION"][1] + radius = config["LOFTR"]["FINE_WINDOW_SIZE"] // 2 + + # 2. get coarse prediction + b_ids, i_ids, j_ids = data["b_ids"], data["i_ids"], data["j_ids"] + + # 3. compute gt + scale = scale * data["scale1"][b_ids] if "scale0" in data else scale + # `expec_f_gt` might exceed the window, i.e. abs(*) > 1, which would be filtered later + expec_f_gt = (w_pt0_i[b_ids, i_ids] - pt1_i[b_ids, j_ids]) / scale / radius # [M, 2] + data.update({"expec_f_gt": expec_f_gt}) + + +def compute_supervision_fine(data: dict[str, Any], config: dict[str, Any]) -> None: + """Compute fine supervision.""" + data_source = data["dataset_name"][0] + if data_source.lower() in ["scannet", "megadepth"]: + spvs_fine(data, config) + else: + raise NotImplementedError diff --git a/python_embeded/Lib/site-packages/kornia/feature/matching.py b/python_embeded/Lib/site-packages/kornia/feature/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..7083388afde0f1a2d8f505e8cd2e7d8b28e12d4e --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/matching.py @@ -0,0 +1,553 @@ +# 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. +# + +from typing import Any, ClassVar, Dict, List, Optional, Tuple + +import torch + +from kornia.core import Module, Tensor, concatenate +from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE +from kornia.feature.laf import get_laf_center +from kornia.feature.steerers import DiscreteSteerer +from kornia.utils.helpers import is_mps_tensor_safe + +from .adalam import get_adalam_default_config, match_adalam + + +def _cdist(d1: Tensor, d2: Tensor) -> Tensor: + r"""Manual `torch.cdist` for M1.""" + if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)): + return torch.cdist(d1, d2) + d1_sq = (d1**2).sum(dim=1, keepdim=True) + d2_sq = (d2**2).sum(dim=1, keepdim=True) + dm = d1_sq.repeat(1, d2.size(0)) + d2_sq.repeat(1, d1.size(0)).t() - 2.0 * d1 @ d2.t() + dm = dm.clamp(min=0.0).sqrt() + return dm + + +def _get_default_fginn_params() -> Dict[str, Any]: + config = {"th": 0.85, "mutual": False, "spatial_th": 10.0} + return config + + +def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None) -> Tensor: + """Check validity of provided distance matrix, or calculates L2-distance matrix if dm is not provided. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + dm_: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + """ + if dm_ is None: + dm = _cdist(desc1, desc2) + else: + KORNIA_CHECK_DM_DESC(desc1, desc2, dm_) + dm = dm_ + return dm + + +def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]: + """Output empty tensors. + + Returns: + - Descriptor distance of matching descriptors, shape of :math:`(0, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`. + + """ + dists = torch.empty(0, 1, device=dm.device, dtype=dm.dtype) + idxs = torch.empty(0, 2, device=dm.device, dtype=torch.long) + return dists, idxs + + +def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + r"""Find nearest neighbors in desc2 for each vector in desc1. + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + dm: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + Returns: + - Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`. + + """ + KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"]) + if (len(desc1) == 0) or (len(desc2) == 0): + return _no_match(desc1) + distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm) + match_dists, idxs_in_2 = torch.min(distance_matrix, dim=1) + idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device) + matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1) + return match_dists.view(-1, 1), matches_idxs.view(-1, 2) + + +def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + """Find mutual nearest neighbors in desc2 for each vector in desc1. + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + dm: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + Return: + - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`, + where 0 <= B3 <= min(B1, B2) + + """ + KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"]) + if (len(desc1) == 0) or (len(desc2) == 0): + return _no_match(desc1) + distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm) + ms = min(distance_matrix.size(0), distance_matrix.size(1)) + match_dists, idxs_in_2 = torch.min(distance_matrix, dim=1) + match_dists2, idxs_in_1 = torch.min(distance_matrix, dim=0) + minsize_idxs = torch.arange(ms, device=distance_matrix.device) + + if distance_matrix.size(0) <= distance_matrix.size(1): + mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms] + matches_idxs = concatenate([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], 1)[mutual_nns] + match_dists = match_dists[mutual_nns] + else: + mutual_nns = minsize_idxs == idxs_in_2[idxs_in_1][:ms] + matches_idxs = concatenate([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], 1)[mutual_nns] + match_dists = match_dists2[mutual_nns] + return match_dists.view(-1, 1), matches_idxs.view(-1, 2) + + +def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + """Find nearest neighbors in desc2 for each vector in desc1. + + The method satisfies first to second nearest neighbor distance <= th. + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + th: distance ratio threshold. + dm: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + Return: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`, + where 0 <= B3 <= B1. + + """ + KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"]) + + if desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches + return _no_match(desc1) + distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm) + vals, idxs_in_2 = torch.topk(distance_matrix, 2, dim=1, largest=False) + ratio = vals[:, 0] / vals[:, 1] + mask = ratio <= th + match_dists = ratio[mask] + if len(match_dists) == 0: + return _no_match(distance_matrix) + idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask] + idxs_in_2 = idxs_in_2[:, 0][mask] + matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1) + return match_dists.view(-1, 1), matches_idxs.view(-1, 2) + + +def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + """Find mutual nearest neighbors in desc2 for each vector in desc1. + + the method satisfies first to second nearest neighbor distance <= th. + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + th: distance ratio threshold. + dm: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + Return: + - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, + shape of :math:`(B3, 2)` where 0 <= B3 <= B1. + + """ + KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"]) + + if (desc1.shape[0] < 2) or (desc2.shape[0] < 2): + return _no_match(desc1) + distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm) + + dists1, idx1 = match_snn(desc1, desc2, th, distance_matrix) + dists2, idx2 = match_snn(desc2, desc1, th, distance_matrix.t()) + + if len(dists2) > 0 and len(dists1) > 0: + idx2 = idx2.flip(1) + if not is_mps_tensor_safe(idx1): + idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1.0) + else: + idxs1_rep = idx1.to(desc1).repeat_interleave(idx2.size(0), dim=0) + idxs_dm = (idx2.to(desc2).repeat(idx1.size(0), 1) - idxs1_rep).abs().sum(dim=1) + idxs_dm = idxs_dm.reshape(idx1.size(0), idx2.size(0)) + mutual_idxs1 = idxs_dm.min(dim=1)[0] < 1e-8 + mutual_idxs2 = idxs_dm.min(dim=0)[0] < 1e-8 + good_idxs1 = idx1[mutual_idxs1.view(-1)] + good_idxs2 = idx2[mutual_idxs2.view(-1)] + dists1_good = dists1[mutual_idxs1.view(-1)] + dists2_good = dists2[mutual_idxs2.view(-1)] + _, idx_upl1 = torch.sort(good_idxs1[:, 0]) + _, idx_upl2 = torch.sort(good_idxs2[:, 0]) + good_idxs1 = good_idxs1[idx_upl1] + match_dists = torch.max(dists1_good[idx_upl1], dists2_good[idx_upl2]) + matches_idxs = good_idxs1 + match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2) + else: + match_dists, matches_idxs = _no_match(distance_matrix) + return match_dists, matches_idxs + + +def match_fginn( + desc1: Tensor, + desc2: Tensor, + lafs1: Tensor, + lafs2: Tensor, + th: float = 0.8, + spatial_th: float = 10.0, + mutual: bool = False, + dm: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Find nearest neighbors in desc2 for each vector in desc1. + + The method satisfies first to second nearest neighbor distance <= th, + and assures 2nd nearest neighbor is geometrically inconsistent with the 1st one + (see :cite:`MODS2015` for more details) + + If the distance matrix dm is not provided, :py:func:`torch.cdist` is used. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`. + lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`. + + th: distance ratio threshold. + spatial_th: minimal distance in pixels to 2nd nearest neighbor. + mutual: also perform mutual nearest neighbor check + dm: Tensor containing the distances from each descriptor in desc1 + to each descriptor in desc2, shape of :math:`(B1, B2)`. + + Return: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`, + where 0 <= B3 <= B1. + + """ + KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"]) + BIG_NUMBER = 1000000.0 + + distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm) + dtype = distance_matrix.dtype + + if desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches + return _no_match(distance_matrix) + + num_candidates = max(2, min(10, desc2.shape[0])) + vals_cand, idxs_in_2 = torch.topk(distance_matrix, num_candidates, dim=1, largest=False) + vals = vals_cand[:, 0] + xy2 = get_laf_center(lafs2).view(-1, 2) + candidates_xy = xy2[idxs_in_2] + kdist = torch.norm(candidates_xy - candidates_xy[0:1], p=2, dim=2) + fginn_vals = vals_cand[:, 1:] + (kdist[:, 1:] < spatial_th).to(dtype) * BIG_NUMBER + fginn_vals_best, fginn_idxs_best = fginn_vals.min(dim=1) + + # orig_idxs = idxs_in_2.gather(1, fginn_idxs_best.unsqueeze(1))[0] + # if you need to know fginn indexes - uncomment + + vals_2nd = fginn_vals_best + idxs_in_2 = idxs_in_2[:, 0] + + ratio = vals / vals_2nd + mask = ratio <= th + match_dists = ratio[mask] + if len(match_dists) == 0: + return _no_match(distance_matrix) + idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask] + idxs_in_2 = idxs_in_2[mask] + matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1) + match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2) + + if not mutual: # returning 1-way matches + return match_dists, matches_idxs + _, idxs_in_1_mut = torch.min(distance_matrix, dim=0) + good_mask = matches_idxs[:, 0] == idxs_in_1_mut[matches_idxs[:, 1]] + return match_dists[good_mask], matches_idxs[good_mask] + + +class DescriptorMatcher(Module): + """Module version of matching functions. + + See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`, + :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details. + + Args: + match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`. + th: threshold on distance ratio, or other quality measure. + + """ + + def __init__(self, match_mode: str = "snn", th: float = 0.8) -> None: + super().__init__() + _match_mode: str = match_mode.lower() + self.known_modes = ["nn", "mnn", "snn", "smnn"] + if _match_mode not in self.known_modes: + raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}") + self.match_mode = _match_mode + self.th = th + + def forward(self, desc1: Tensor, desc2: Tensor) -> Tuple[Tensor, Tensor]: + """Run forward. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + + Returns: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, + shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`. + + """ + if self.match_mode == "nn": + out = match_nn(desc1, desc2) + elif self.match_mode == "mnn": + out = match_mnn(desc1, desc2) + elif self.match_mode == "snn": + out = match_snn(desc1, desc2, self.th) + elif self.match_mode == "smnn": + out = match_smnn(desc1, desc2, self.th) + else: + raise NotImplementedError + return out + + +class DescriptorMatcherWithSteerer(Module): + """Matching that is invariant under rotations, using Steerers. + + Args: + steerer: An instance of :func:`kornia.feature.steerers.DiscreteSteerer`. + steerer_order: order of discretisation of rotation angles, e.g. 4 leads to quarter rotations. + steer_mode: can be `global`, `local`. + `global` means that the we output matches from the global rotation with most matches. + `local` means that we output matches from a distance matrix + where the distance between each descriptor pair is the minimal over rotations. + match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`. + WARNING: using steer_mode `global` with match_mode `nn` will lead to bad results + since `nn` doesn't generate different amount of matches depending on goodness of fit. + th: threshold on distance ratio, or other quality measure. + + Example: + >>> import kornia as K + >>> import kornia.feature as KF + >>> device = K.utils.get_cuda_or_mps_device_if_available() + >>> img1 = torch.randn([1, 3, 768, 768], device=device) + >>> img2 = torch.randn([1, 3, 768, 768], device=device) + >>> dedode = KF.DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-SO2").to(device) + >>> steerer_order = 8 # discretisation order of rotation angles + >>> steerer = KF.steerers.DiscreteSteerer.create_dedode_default( + ... generator_type="SO2", steerer_order=steerer_order + ... ) + >>> steerer = steerer.to(device) + >>> matcher = KF.matching.DescriptorMatcherWithSteerer( + ... steerer=steerer, steerer_order=steerer_order, steer_mode="global", match_mode="smnn", th=0.98 + ... ) + >>> with torch.inference_mode(): + ... kps1, scores1, descs1 = dedode(img1, n=20_000) + ... kps2, scores2, descs2 = dedode(img2, n=20_000) + ... kps1, kps2, descs1, descs2 = kps1[0], kps2[0], descs1[0], descs2[0] + ... dists, idxs, num_rot = matcher( + ... descs1, descs2, normalize=True, subset_size=1000, + ... ) + >>> # print(f"{idxs.shape[0]} tentative matches with steered DeDoDe") + >>> # print(f"at rotation of {num_rot * 360 / steerer_order} degrees") + + """ + + def __init__( + self, + steerer: DiscreteSteerer, + steerer_order: int, + steer_mode: str = "global", + match_mode: str = "snn", + th: float = 0.8, + ) -> None: + super().__init__() + self.steerer = steerer + self.steerer_order = steerer_order + + _steer_mode: str = steer_mode.lower() + self.known_steer_modes = ["global", "local"] + if _steer_mode not in self.known_steer_modes: + raise NotImplementedError(f"{steer_mode} is not supported. Try one of {self.known_steer_modes}") + self.steer_mode = _steer_mode + _match_mode: str = match_mode.lower() + self.known_modes = ["nn", "mnn", "snn", "smnn"] + if _match_mode not in self.known_modes: + raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}") + self.match_mode = _match_mode + self.th = th + + def matching_function(self, d1: Tensor, d2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + if self.match_mode == "nn": + return match_nn(d1, d2, dm=dm) + elif self.match_mode == "mnn": + return match_mnn(d1, d2, dm=dm) + elif self.match_mode == "snn": + return match_snn(d1, d2, self.th, dm=dm) + elif self.match_mode == "smnn": + return match_smnn(d1, d2, self.th, dm=dm) + else: + raise NotImplementedError + + def forward( + self, + desc1: Tensor, + desc2: Tensor, + normalize: bool = False, + subset_size: Optional[int] = None, + ) -> Tuple[Tensor, Tensor, Optional[int]]: + """Run forward. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + normalize: bool to decide whether to normalize descriptors to unit norm. + subset_size: If set, the subset size to use for determining optimal + number of rotations. Smaller subset size leads to faster but less + accurate matching. Only used when `self.steer_mode` is `"global"`. + + Returns: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, + shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`. + - Number of global rotations from desc1 to desc2, in terms of `self.steerer_order` + (will be `None` if `self.steer_mode` is `local`). + + """ + rot1to2 = None + + if normalize: + desc1 = torch.nn.functional.normalize(desc1, dim=-1) + desc2 = torch.nn.functional.normalize(desc2, dim=-1) + + if self.steer_mode == "global": + if subset_size is not None: + subsample1 = torch.randperm(desc1.shape[0])[:subset_size] + subsample2 = torch.randperm(desc2.shape[0])[:subset_size] + _, _, rot1to2 = self( + desc1[subsample1], + desc2[subsample2], + normalize=normalize, + ) + desc1 = self.steerer.steer_descriptions( + desc1, + steerer_power=rot1to2, + normalize=normalize, + ) + dist, idx = self.matching_function(desc1, desc2, None) + return dist, idx, rot1to2 + dist, idx = self.matching_function(desc1, desc2, None) + rot1to2 = 0 + for r in range(1, self.steerer_order): + desc1 = self.steerer.steer_descriptions(desc1, normalize=normalize) + dist_new, idx_new = self.matching_function(desc1, desc2, None) + if idx_new.shape[0] > idx.shape[0]: + dist, idx, rot1to2 = dist_new, idx_new, r + elif self.steer_mode == "local": + dm = _cdist(desc1, desc2) + for _ in range(1, self.steerer_order): + desc1 = self.steerer.steer_descriptions(desc1, normalize=normalize) + dm_new = _cdist(desc1, desc2) + dm = torch.minimum(dm, dm_new) + dist, idx = self.matching_function(desc1, desc2, dm) + else: + raise NotImplementedError + + return dist, idx, rot1to2 + + +class GeometryAwareDescriptorMatcher(Module): + """Module version of matching functions. + + See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`, + :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details. + + Args: + match_mode: type of matching, can be `fginn`. + th: threshold on distance ratio, or other quality measure. + + """ + + known_modes: ClassVar[List[str]] = ["fginn", "adalam"] + + def __init__(self, match_mode: str = "fginn", params: Optional[Dict[str, Tensor]] = None) -> None: + super().__init__() + _match_mode: str = match_mode.lower() + if _match_mode not in self.known_modes: + raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}") + self.match_mode = _match_mode + self.params = params or {} + + def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]: + """Run forward. + + Args: + desc1: Batch of descriptors of a shape :math:`(B1, D)`. + desc2: Batch of descriptors of a shape :math:`(B2, D)`. + lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`. + lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`. + + Returns: + - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`. + - Long tensor indexes of matching descriptors in desc1 and desc2, + shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`. + + """ + if self.match_mode == "fginn": + params = _get_default_fginn_params() + params.update(self.params) + out = match_fginn(desc1, desc2, lafs1, lafs2, params["th"], params["spatial_th"], params["mutual"]) + elif self.match_mode == "adalam": + _params = get_adalam_default_config() + _params.update(self.params) # type: ignore[typeddict-item] + out = match_adalam(desc1, desc2, lafs1, lafs2, config=_params) + else: + raise NotImplementedError + return out diff --git a/python_embeded/Lib/site-packages/kornia/feature/mkd.py b/python_embeded/Lib/site-packages/kornia/feature/mkd.py new file mode 100644 index 0000000000000000000000000000000000000000..0945da3cce5efadc354bd64efa10c92f1f5b178a --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/mkd.py @@ -0,0 +1,641 @@ +# 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. +# + +from typing import Any, Dict, List, Tuple, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.constants import pi +from kornia.core import Tensor, cos, sin, tensor, zeros +from kornia.filters import GaussianBlur2d, SpatialGradient +from kornia.geometry.conversions import cart2pol +from kornia.utils import create_meshgrid + +# Precomputed coefficients for Von Mises kernel, given N and K(appa). +sqrt2: float = 1.4142135623730951 +COEFFS_N1_K1: List[float] = [0.38214156, 0.48090413] +COEFFS_N2_K8: List[float] = [0.14343168, 0.268285, 0.21979234] +COEFFS_N3_K8: List[float] = [0.14343168, 0.268285, 0.21979234, 0.15838885] +COEFFS: Dict[str, List[float]] = {"xy": COEFFS_N1_K1, "rhophi": COEFFS_N2_K8, "theta": COEFFS_N3_K8} + +urls: Dict[str, str] = { + k: f"https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth" + for k in ["cart", "polar", "concat"] +} + + +def get_grid_dict(patch_size: int = 32) -> Dict[str, Tensor]: + r"""Get cartesian and polar parametrizations of grid.""" + kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True) + x = kgrid[0, :, :, 0] + y = kgrid[0, :, :, 1] + rho, phi = cart2pol(x, y) + grid_dict = {"x": x, "y": y, "rho": rho, "phi": phi} + return grid_dict + + +def get_kron_order(d1: int, d2: int) -> Tensor: + r"""Get order for doing kronecker product.""" + kron_order = zeros([d1 * d2, 2], dtype=torch.int64) + for i in range(d1): + for j in range(d2): + kron_order[i * d2 + j, 0] = i + kron_order[i * d2 + j, 1] = j + return kron_order + + +class MKDGradients(nn.Module): + r"""Module, which computes gradients of given patches, stacked as [magnitudes, orientations]. + + Given gradients $g_x$, $g_y$ with respect to $x$, $y$ respectively, + - $\mathbox{mags} = $\sqrt{g_x^2 + g_y^2 + eps}$ + - $\mathbox{oris} = $\mbox{tan}^{-1}(\nicefrac{g_y}{g_x})$. + + Args: + patch_size: Input patch size in pixels. + + Returns: + gradients of given patches. + + Shape: + - Input: (B, 1, patch_size, patch_size) + - Output: (B, 2, patch_size, patch_size) + + Example: + >>> patches = torch.rand(23, 1, 32, 32) + >>> gradient = MKDGradients() + >>> g = gradient(patches) # 23x2x32x32 + + """ + + def __init__(self) -> None: + super().__init__() + self.eps = 1e-8 + + self.grad = SpatialGradient(mode="diff", order=1, normalized=False) + + def forward(self, x: Tensor) -> Tensor: + if not isinstance(x, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(x)}") + if not len(x.shape) == 4: + raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}") + # Modify 'diff' gradient. Before we had lambda function, but it is not jittable + grads_xy = -self.grad(x) + gx = grads_xy[:, :, 0, :, :] + gy = grads_xy[:, :, 1, :, :] + y = torch.cat(cart2pol(gx, gy, self.eps), dim=1) + return y + + def __repr__(self) -> str: + return self.__class__.__name__ + + +class VonMisesKernel(nn.Module): + r"""Module, which computes parameters of Von Mises kernel given coefficients, and embeds given patches. + + Args: + patch_size: Input patch size in pixels. + coeffs: List of coefficients. Some examples are hardcoded in COEFFS, + + Returns: + Von Mises embedding of given parametrization. + + Shape: + - Input: (B, 1, patch_size, patch_size) + - Output: (B, d, patch_size, patch_size) + + Examples: + >>> oris = torch.rand(23, 1, 32, 32) + >>> vm = VonMisesKernel(patch_size=32, + ... coeffs=[0.14343168, + ... 0.268285, + ... 0.21979234]) + >>> emb = vm(oris) # 23x7x32x32 + + """ + + def __init__(self, patch_size: int, coeffs: Union[List[Union[float, int]], Tuple[Union[float, int], ...]]) -> None: + super().__init__() + + self.patch_size = patch_size + b_coeffs = tensor(coeffs) + self.register_buffer("coeffs", b_coeffs) + + # Compute parameters. + n = len(coeffs) - 1 + self.n = n + self.d = 2 * n + 1 + + # Precompute helper variables. + emb0 = torch.ones([1, 1, patch_size, patch_size]) + frange = torch.arange(n) + 1 + frange = frange.reshape(-1, 1, 1) + weights = zeros([2 * n + 1]) + weights[: n + 1] = torch.sqrt(b_coeffs) + weights[n + 1 :] = torch.sqrt(b_coeffs[1:]) + weights = weights.reshape(-1, 1, 1) + self.register_buffer("emb0", emb0) + self.register_buffer("frange", frange) + self.register_buffer("weights", weights) + + def forward(self, x: Tensor) -> Tensor: + if not isinstance(x, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(x)}") + + if not len(x.shape) == 4 or x.shape[1] != 1: + raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}") + + if not isinstance(self.emb0, Tensor): + raise TypeError(f"Emb0 type is not a Tensor. Got {type(x)}") + + emb0 = self.emb0.to(x).repeat(x.size(0), 1, 1, 1) + frange = self.frange.to(x) * x + emb1 = cos(frange) + emb2 = sin(frange) + embedding = torch.cat([emb0, emb1, emb2], dim=1) + embedding = self.weights * embedding + return embedding + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(patch_size={self.patch_size}, n={self.n}, d={self.d}, coeffs={self.coeffs})" + + +class EmbedGradients(nn.Module): + r"""Module that computes gradient embedding, weighted by sqrt of magnitudes of given patches. + + Args: + patch_size: Input patch size in pixels. + relative: absolute or relative gradients. + + Returns: + Gradient embedding. + + Shape: + - Input: (B, 2, patch_size, patch_size) + - Output: (B, 7, patch_size, patch_size) + + Examples: + >>> grads = torch.rand(23, 2, 32, 32) + >>> emb_grads = EmbedGradients(patch_size=32, + ... relative=False) + >>> emb = emb_grads(grads) # 23x7x32x32 + + """ + + def __init__(self, patch_size: int = 32, relative: bool = False) -> None: + super().__init__() + self.patch_size = patch_size + self.relative = relative + self.eps = 1e-8 + + # Theta kernel for gradients. + self.kernel = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS["theta"]) + + # Relative gradients. + kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True) + _, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1]) + self.register_buffer("phi", phi) + + def emb_mags(self, mags: Tensor) -> Tensor: + """Embed square roots of magnitudes with eps for numerical reasons.""" + mags = torch.sqrt(mags + self.eps) + return mags + + def forward(self, grads: Tensor) -> Tensor: + if not isinstance(grads, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(grads)}") + if not len(grads.shape) == 4: + raise ValueError(f"Invalid input shape, we expect Bx2xHxW. Got: {grads.shape}") + mags = grads[:, :1, :, :] + oris = grads[:, 1:, :, :] + if self.relative: + oris = oris - self.phi.to(oris) + y = self.kernel(oris) * self.emb_mags(mags) + return y + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(patch_size={self.patch_size}, relative={self.relative})" + + +def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, Tensor]) -> Tensor: + r"""Compute embeddings for cartesian and polar parametrizations.""" + factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2} + if kernel_type == "cart": + coeffs_ = "xy" + params_ = ["x", "y"] + elif kernel_type == "polar": + coeffs_ = "rhophi" + params_ = ["phi", "rho"] + + # Infer patch_size. + keys = list(grids.keys()) + patch_size = grids[keys[0]].shape[-1] + + # Scale appropriately. + grids_normed = {k: v * factors[k] for k, v in grids.items()} + grids_normed = {k: v.unsqueeze(0).unsqueeze(0).float() for k, v in grids_normed.items()} + + # x,y/rho,phi kernels. + vm_a = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS[coeffs_]) + vm_b = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS[coeffs_]) + + emb_a = vm_a(grids_normed[params_[0]]).squeeze() + emb_b = vm_b(grids_normed[params_[1]]).squeeze() + + # Final precomputed position embedding. + kron_order = get_kron_order(vm_a.d, vm_b.d) + spatial_kernel = emb_a.index_select(0, kron_order[:, 0]) * emb_b.index_select(0, kron_order[:, 1]) + return spatial_kernel + + +class ExplicitSpacialEncoding(nn.Module): + r"""Module that computes explicit cartesian or polar embedding. + + Args: + kernel_type: Parametrization of kernel ``'polar'`` or ``'cart'``. + fmap_size: Input feature map size in pixels. + in_dims: Dimensionality of input feature map. + do_gmask: Apply gaussian mask. + do_l2: Apply l2-normalization. + + Returns: + Explicit cartesian or polar embedding. + + Shape: + - Input: (B, in_dims, fmap_size, fmap_size) + - Output: (B, out_dims, fmap_size, fmap_size) + + Example: + >>> emb_ori = torch.rand(23, 7, 32, 32) + >>> ese = ExplicitSpacialEncoding(kernel_type='polar', + ... fmap_size=32, + ... in_dims=7, + ... do_gmask=True, + ... do_l2=True) + >>> desc = ese(emb_ori) # 23x175x32x32 + + """ + + def __init__( + self, + kernel_type: str = "polar", + fmap_size: int = 32, + in_dims: int = 7, + do_gmask: bool = True, + do_l2: bool = True, + ) -> None: + super().__init__() + + if kernel_type not in ["polar", "cart"]: + raise NotImplementedError(f"{kernel_type} is not valid, use polar or cart).") + + self.kernel_type = kernel_type + self.fmap_size = fmap_size + self.in_dims = in_dims + self.do_gmask = do_gmask + self.do_l2 = do_l2 + self.grid = get_grid_dict(fmap_size) + self.gmask = None + + # Precompute embedding. + emb = spatial_kernel_embedding(self.kernel_type, self.grid) + + # Gaussian mask. + if self.do_gmask: + self.gmask = self.get_gmask(sigma=1.0) + emb = emb * self.gmask + + # Store precomputed embedding. + self.register_buffer("emb", emb.unsqueeze(0)) + self.d_emb: int = emb.shape[0] + self.out_dims: int = self.in_dims * self.d_emb + self.odims: int = self.out_dims + + # Store kronecker form. + emb2, idx1 = self.init_kron() + self.register_buffer("emb2", emb2) + self.register_buffer("idx1", idx1) + + def get_gmask(self, sigma: float) -> Tensor: + """Compute Gaussian mask.""" + norm_rho = self.grid["rho"] / self.grid["rho"].max() + gmask = torch.exp(-1 * norm_rho**2 / sigma**2) + return gmask + + def init_kron(self) -> Tuple[Tensor, Tensor]: + """Initialize helper variables to calculate kronecker.""" + kron = get_kron_order(self.in_dims, self.d_emb) + _emb = torch.jit.annotate(Tensor, self.emb) + emb2 = torch.index_select(_emb, 1, kron[:, 1]) + return emb2, kron[:, 0] + + def forward(self, x: Tensor) -> Tensor: + if not isinstance(x, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(x)}") + if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)): + raise ValueError(f"Invalid input shape, we expect Bx{self.in_dims}xHxW. Got: {x.shape}") + idx1 = torch.jit.annotate(Tensor, self.idx1) + emb1 = torch.index_select(x, 1, idx1) + output = emb1 * self.emb2 + output = output.sum(dim=(2, 3)) + if self.do_l2: + output = F.normalize(output, dim=1) + return output + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"kernel_type={self.kernel_type}, " + f"fmap_size={self.fmap_size}, " + f"in_dims={self.in_dims}, " + f"out_dims={self.out_dims}, " + f"do_gmask={self.do_gmask}, " + f"do_l2={self.do_l2})" + ) + + +class Whitening(nn.Module): + r"""Module, performs supervised or unsupervised whitening. + + This is based on the paper "Understanding and Improving Kernel Local Descriptors". + See :cite:`mukundan2019understanding` for more details. + + Args: + xform: Variant of whitening to use. None, 'lw', 'pca', 'pcaws', 'pcawt'. + whitening_model: Dictionary with keys 'mean', 'eigvecs', 'eigvals' holding Tensors. + in_dims: Dimensionality of input descriptors. + output_dims: (int) Dimensionality reduction. + keval: Shrinkage parameter. + t: Attenuation parameter. + + Returns: + l2-normalized, whitened descriptors. + + Shape: + - Input: (B, in_dims, fmap_size, fmap_size) + - Output: (B, out_dims, fmap_size, fmap_size) + + Examples: + >>> descs = torch.rand(23, 238) + >>> whitening_model = {'pca': {'mean': torch.zeros(238), + ... 'eigvecs': torch.eye(238), + ... 'eigvals': torch.ones(238)}} + >>> whitening = Whitening(xform='pcawt', + ... whitening_model=whitening_model, + ... in_dims=238, + ... output_dims=128, + ... keval=40, + ... t=0.7) + >>> wdescs = whitening(descs) # 23x128 + + """ + + def __init__( + self, + xform: str, + whitening_model: Union[Dict[str, Dict[str, Tensor]], None], + in_dims: int, + output_dims: int = 128, + keval: int = 40, + t: float = 0.7, + ) -> None: + super().__init__() + + self.xform = xform + self.in_dims = in_dims + self.keval = keval + self.t = t + self.pval = 1.0 + + # Compute true output_dims. + output_dims = min(output_dims, in_dims) + self.output_dims = output_dims + + # Initialize identity transform. + self.mean = nn.Parameter(zeros(in_dims), requires_grad=True) + self.evecs = nn.Parameter(torch.eye(in_dims)[:, :output_dims], requires_grad=True) + self.evals = nn.Parameter(torch.ones(in_dims)[:output_dims], requires_grad=True) + + if whitening_model is not None: + self.load_whitening_parameters(whitening_model) + + def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, Tensor]]) -> None: + algo = "lw" if self.xform == "lw" else "pca" + wh_model = whitening_model[algo] + self.mean.data = wh_model["mean"] + self.evecs.data = wh_model["eigvecs"][:, : self.output_dims] + self.evals.data = wh_model["eigvals"][: self.output_dims] + + modifications = { + "pca": self._modify_pca, + "lw": self._modify_lw, + "pcaws": self._modify_pcaws, + "pcawt": self._modify_pcawt, + } + + # Call modification. + modifications[self.xform]() + + def _modify_pca(self) -> None: + """Modify powerlaw parameter.""" + self.pval = 0.5 + + def _modify_lw(self) -> None: + """No modification required.""" + + def _modify_pcaws(self) -> None: + """Shrinkage for eigenvalues.""" + alpha = self.evals[self.keval] + evals = ((1 - alpha) * self.evals) + alpha + self.evecs.data = self.evecs @ torch.diag(torch.pow(evals, -0.5)) + + def _modify_pcawt(self) -> None: + """Attenuation for eigenvalues.""" + m = -0.5 * self.t + self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m)) + + def forward(self, x: Tensor) -> Tensor: + if not isinstance(x, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(x)}") + if not len(x.shape) == 2: + raise ValueError(f"Invalid input shape, we expect NxD. Got: {x.shape}") + x = x - self.mean # Center the data. + x = x @ self.evecs # Apply rotation and/or scaling. + x = torch.sign(x) * torch.pow(torch.abs(x), self.pval) # Powerlaw. + return F.normalize(x, dim=1) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(xform={self.xform}, in_dims={self.in_dims}, output_dims={self.output_dims})" + + +class MKDDescriptor(nn.Module): + r"""Module that computes Multiple Kernel local descriptors. + + This is based on the paper "Understanding and Improving Kernel Local Descriptors". + See :cite:`mukundan2019understanding` for more details. + + Args: + patch_size: Input patch size in pixels. + kernel_type: Parametrization of kernel ``'concat'``, ``'cart'``, ``'polar'``. + whitening: Whitening transform to apply ``None``, ``'lw'``, ``'pca'``, ``'pcawt'``, ``'pcaws'``. + training_set: Set that model was trained on ``'liberty'``, ``'notredame'``, ``'yosemite'``. + output_dims: Dimensionality reduction. + + Returns: + Explicit cartesian or polar embedding. + + Shape: + - Input: :math:`(B, in_{dims}, fmap_{size}, fmap_{size})`. + - Output: :math:`(B, out_{dims}, fmap_{size}, fmap_{size})`, + + Examples: + >>> patches = torch.rand(23, 1, 32, 32) + >>> mkd = MKDDescriptor(patch_size=32, + ... kernel_type='concat', + ... whitening='pcawt', + ... training_set='liberty', + ... output_dims=128) + >>> desc = mkd(patches) # 23x128 + + """ + + def __init__( + self, + patch_size: int = 32, + kernel_type: str = "concat", + whitening: str = "pcawt", + training_set: str = "liberty", + output_dims: int = 128, + ) -> None: + super().__init__() + + self.patch_size: int = patch_size + self.kernel_type: str = kernel_type + self.whitening: str = whitening + self.training_set: str = training_set + + self.sigma = 1.4 * (patch_size / 64) + self.smoothing = GaussianBlur2d((5, 5), (self.sigma, self.sigma), "replicate") + self.gradients = MKDGradients() + # This stupid thing needed for jitting... + polar_s: str = "polar" + cart_s: str = "cart" + self.parametrizations = [polar_s, cart_s] if self.kernel_type == "concat" else [self.kernel_type] + + # Initialize cartesian/polar embedding with absolute/relative gradients. + self.odims: int = 0 + relative_orientations = {polar_s: True, cart_s: False} + self.feats = {} + for parametrization in self.parametrizations: + gradient_embedding = EmbedGradients(patch_size=patch_size, relative=relative_orientations[parametrization]) + spatial_encoding = ExplicitSpacialEncoding( + kernel_type=parametrization, fmap_size=patch_size, in_dims=gradient_embedding.kernel.d + ) + + self.feats[parametrization] = nn.Sequential(gradient_embedding, spatial_encoding) + self.odims += spatial_encoding.odims + # Compute true output_dims. + self.output_dims: int = min(output_dims, self.odims) + + # Load supervised(lw)/unsupervised(pca) model trained on training_set. + if self.whitening is not None: + whitening_models = torch.hub.load_state_dict_from_url( + urls[self.kernel_type], map_location=torch.device("cpu") + ) + whitening_model = whitening_models[training_set] + self.whitening_layer = Whitening( + whitening, whitening_model, in_dims=self.odims, output_dims=self.output_dims + ) + self.odims = self.output_dims + self.eval() + + def forward(self, patches: Tensor) -> Tensor: + if not isinstance(patches, Tensor): + raise TypeError(f"Input type is not a Tensor. Got {type(patches)}") + if not len(patches.shape) == 4: + raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {patches.shape}") + # Extract gradients. + g = self.smoothing(patches) + g = self.gradients(g) + + # Extract polar/cart features. + features = [] + for parametrization in self.parametrizations: + self.feats[parametrization].to(g.device) + features.append(self.feats[parametrization](g)) + + # Concatenate. + y = torch.cat(features, dim=1) + + # l2-normalize. + y = F.normalize(y, dim=1) + + # Whiten descriptors. + if self.whitening is not None: + y = self.whitening_layer(y) + + return y + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"patch_size={self.patch_size}, " + f"kernel_type={self.kernel_type}, " + f"whitening={self.whitening}, " + f"training_set={self.training_set}, " + f"output_dims={self.output_dims})" + ) + + +def load_whitening_model(kernel_type: str, training_set: str) -> Dict[str, Any]: + """Load whitening model.""" + whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=torch.device("cpu")) + whitening_model = whitening_models[training_set] + return whitening_model + + +class SimpleKD(nn.Module): + """Example to write custom Kernel Descriptors.""" + + def __init__( + self, + patch_size: int = 32, + kernel_type: str = "polar", # 'cart' 'polar' + whitening: str = "pcawt", # 'lw', 'pca', 'pcaws', 'pcawt + training_set: str = "liberty", # 'liberty', 'notredame', 'yosemite' + output_dims: int = 128, + ) -> None: + super().__init__() + + relative: bool = kernel_type == "polar" + sigma: float = 1.4 * (patch_size / 64) + self.patch_size = patch_size + # Sequence of modules. + smoothing = GaussianBlur2d((5, 5), (sigma, sigma), "replicate") + gradients = MKDGradients() + ori = EmbedGradients(patch_size=patch_size, relative=relative) + ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=patch_size, in_dims=ori.kernel.d) + wh = Whitening( + whitening, load_whitening_model(kernel_type, training_set), in_dims=ese.odims, output_dims=output_dims + ) + + self.features = nn.Sequential(smoothing, gradients, ori, ese, wh) + + def forward(self, x: Tensor) -> Tensor: + return self.features(x) diff --git a/python_embeded/Lib/site-packages/kornia/feature/orientation.py b/python_embeded/Lib/site-packages/kornia/feature/orientation.py new file mode 100644 index 0000000000000000000000000000000000000000..06c5c06acaad155846015870bd1e5c0676b8072b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/orientation.py @@ -0,0 +1,266 @@ +# 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. +# + +from typing import Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from kornia.constants import pi +from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE +from kornia.filters import SpatialGradient, get_gaussian_discrete_kernel1d, get_gaussian_kernel2d +from kornia.geometry import rad2deg + +from .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientation + +urls: Dict[str, str] = {} +urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth" + + +class PassLAF(nn.Module): + """Dummy module to use instead of local feature orientation or affine shape estimator.""" + + def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + laf: :math:`(B, N, 2, 3)` + img: :math:`(B, 1, H, W)` + + Returns: + LAF, unchanged :math:`(B, N, 2, 3)` + + """ + return laf + + +class PatchDominantGradientOrientation(nn.Module): + """Module, which estimates the dominant gradient orientation of the given patches, in radians. + + Zero angle points towards right. + + Args: + patch_size: size of the (square) input patch. + num_angular_bins: number of histogram bins. + eps: for safe division, and arctan. + + """ + + def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8) -> None: + super().__init__() + self.patch_size = patch_size + self.num_ang_bins = num_angular_bins + self.gradient = SpatialGradient("sobel", 1) + self.eps = eps + self.angular_smooth = nn.Conv1d(1, 1, kernel_size=5, padding=2, bias=False, padding_mode="circular") + with torch.no_grad(): + self.angular_smooth.weight[:] = get_gaussian_discrete_kernel1d(5, 1.6) + sigma: float = float(self.patch_size) / 6.0 + self.weighting = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(patch_size={self.patch_size}, num_ang_bins={self.num_ang_bins}, eps={self.eps})" + ) + + def forward(self, patch: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + patch: :math:`(B, 1, H, W)` + + Returns: + angle in radians: :math:`(B)` + + """ + KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"]) + _, CH, W, H = patch.size() + if (W != self.patch_size) or (H != self.patch_size) or (CH != 1): + raise TypeError( + f"input shape should be must be [Bx1x{self.patch_size}x{self.patch_size}]. Got {patch.size()}" + ) + self.weighting = self.weighting.to(patch.dtype).to(patch.device) + self.angular_smooth = self.angular_smooth.to(patch.dtype).to(patch.device) + grads: torch.Tensor = self.gradient(patch) + # unpack the edges + gx: torch.Tensor = grads[:, :, 0] + gy: torch.Tensor = grads[:, :, 1] + + mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps) * self.weighting + ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi + + o_big = float(self.num_ang_bins) * (ori + 1.0 * pi) / (2.0 * pi) + bo0_big = torch.floor(o_big) + wo1_big = o_big - bo0_big + bo0_big = bo0_big % self.num_ang_bins + bo1_big = (bo0_big + 1) % self.num_ang_bins + wo0_big = (1.0 - wo1_big) * mag + wo1_big = wo1_big * mag + ang_bins_list = [] + for i in range(0, self.num_ang_bins): + ang_bins_i = F.adaptive_avg_pool2d( + (bo0_big == i).to(patch.dtype) * wo0_big + (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1) + ) + ang_bins_list.append(ang_bins_i) + ang_bins = torch.cat(ang_bins_list, 1).view(-1, 1, self.num_ang_bins) + ang_bins = self.angular_smooth(ang_bins).view(-1, self.num_ang_bins) + values, indices = ang_bins.max(1) + indices_left = (self.num_ang_bins + indices - 1) % self.num_ang_bins + indices_right = (indices + 1) % self.num_ang_bins + left = torch.gather(ang_bins, 1, indices_left.reshape(-1, 1)).reshape(-1) + center = values + right = torch.gather(ang_bins, 1, indices_right.reshape(-1, 1)).reshape(-1) + c_subpix = 0.5 * (left - right) / (left + right - 2.0 * center) + angle = -((2.0 * pi * (indices.to(patch.dtype) + c_subpix) / float(self.num_ang_bins)) - pi) + return angle + + +class OriNet(nn.Module): + """Network, which estimates the canonical orientation of the given 32x32 patches, in radians. + + Zero angle points towards right. This is based on the original code from paper + "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"". + See :cite:`AffNet2018` for more details. + + Args: + pretrained: Download and set pretrained weights to the model. + eps: to avoid division by zero in atan2. + + Returns: + Angle in radians. + + Shape: + - Input: (B, 1, 32, 32) + - Output: (B) + + Examples: + >>> input = torch.rand(16, 1, 32, 32) + >>> orinet = OriNet() + >>> angle = orinet(input) # 16 + + """ + + def __init__(self, pretrained: bool = False, eps: float = 1e-8) -> None: + super().__init__() + self.features = nn.Sequential( + nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(16, affine=False), + nn.ReLU(), + nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(16, affine=False), + nn.ReLU(), + nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(32, affine=False), + nn.ReLU(), + nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(64, affine=False), + nn.ReLU(), + nn.Dropout(0.25), + nn.Conv2d(64, 2, kernel_size=8, stride=1, padding=1, bias=True), + nn.Tanh(), + nn.AdaptiveAvgPool2d(1), + ) + self.eps = eps + # use torch.hub to load pretrained model + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["orinet"], map_location=torch.device("cpu")) + self.load_state_dict(pretrained_dict["state_dict"], strict=False) + self.eval() + + @staticmethod + def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: + """Utility function that normalizes the input by batch.""" + sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True) + # WARNING: we need to .detach() input, otherwise the gradients produced by + # the patches extractor with F.grid_sample are very noisy, making the detector + # training totally unstable. + return (x - mp.detach()) / (sp.detach() + eps) + + def forward(self, patch: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + patch: :math:`(B, 1, H, W)` + + Returns: + angle in radians: :math:`(B)` + + """ + xy = self.features(self._normalize_input(patch)).view(-1, 2) + angle = torch.atan2(xy[:, 0] + 1e-8, xy[:, 1] + self.eps) + return angle + + +class LAFOrienter(nn.Module): + """Module, which extracts patches using input images and local affine frames (LAFs). + + Then runs :class:`~kornia.feature.PatchDominantGradientOrientation` or + :class:`~kornia.feature.OriNet` on patches and then rotates the LAFs by the estimated angles + + Args: + patch_size: + num_angular_bins: + angle_detector: Patch orientation estimator, e.g. :class:`~kornia.feature.PatchDominantGradientOrientation` + or OriNet. + + """ # pylint: disable + + def __init__( + self, patch_size: int = 32, num_angular_bins: int = 36, angle_detector: Optional[nn.Module] = None + ) -> None: + super().__init__() + self.patch_size = patch_size + self.num_ang_bins = num_angular_bins + self.angle_detector: nn.Module + if angle_detector is None: + self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins) + else: + self.angle_detector = angle_detector + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(patch_size={self.patch_size}, angle_detector={self.angle_detector})" + + def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: + """Run forward. + + Args: + laf: :math:`(B, N, 2, 3)` + img: :math:`(B, 1, H, W)` + + Returns: + LAF_out: :math:`(B, N, 2, 3)` + + """ + KORNIA_CHECK_LAF(laf) + KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"]) + if laf.size(0) != img.size(0): + raise ValueError(f"Batch size of laf and img should be the same. Got {img.size(0)}, {laf.size(0)}") + B, N = laf.shape[:2] + patches: torch.Tensor = extract_patches_from_pyramid(img, laf, self.patch_size).view( + -1, 1, self.patch_size, self.patch_size + ) + angles_radians: torch.Tensor = self.angle_detector(patches).view(B, N) + prev_angle = get_laf_orientation(laf).view_as(angles_radians) + laf_out: torch.Tensor = set_laf_orientation(laf, rad2deg(angles_radians) + prev_angle) + return laf_out diff --git a/python_embeded/Lib/site-packages/kornia/feature/sold2/__init__.py b/python_embeded/Lib/site-packages/kornia/feature/sold2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80d43bfd3e8b2304d2ca59f6d2e9d6de8355506b --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/sold2/__init__.py @@ -0,0 +1,19 @@ +# 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. +# + +from .sold2 import SOLD2 +from .sold2_detector import SOLD2_detector diff --git a/python_embeded/Lib/site-packages/kornia/feature/sold2/backbones.py b/python_embeded/Lib/site-packages/kornia/feature/sold2/backbones.py new file mode 100644 index 0000000000000000000000000000000000000000..6cec74c41538b4e61e9b7de26eb577e915843eb9 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/sold2/backbones.py @@ -0,0 +1,446 @@ +# 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. +# + +"""Implements several backbone networks.""" + +import functools +import operator +from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Type, Union + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.functional import pixel_shuffle, softmax + +from kornia.core import Module, Tensor + + +class HourglassConfig(NamedTuple): + depth: int + num_stacks: int + num_blocks: int + num_classes: int + input_channels: int + head: Type[Module] + + +# [Hourglass backbone classes] +class HourglassBackbone(Module): + """Hourglass network, taken from https://github.com/zhou13/lcnn. + + Args: + input_channel: number of input channels. + depth: number of residual blocks per hourglass module. + num_stacks: number of hourglass modules stacked together. + num_blocks: number of layers in each residual block. + num_classes: number of heads for the output of a hourglass module. + + """ + + def __init__( + self, input_channel: int = 1, depth: int = 4, num_stacks: int = 2, num_blocks: int = 1, num_classes: int = 5 + ) -> None: + super().__init__() + self.head = MultitaskHead + self.net = hg(HourglassConfig(depth, num_stacks, num_blocks, num_classes, input_channel, head=self.head)) + + def forward(self, input_images: Tensor) -> Tensor: + return self.net(input_images) + + +class MultitaskHead(Module): + def __init__(self, input_channels: int) -> None: + super().__init__() + + m = int(input_channels / 4) + head_size = [[2], [1], [2]] + heads = [] + _iter: list[int] = functools.reduce(operator.iconcat, head_size, []) + for output_channels in _iter: + heads.append( + nn.Sequential( + nn.Conv2d(input_channels, m, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(m, output_channels, kernel_size=1), + ) + ) + self.heads = nn.ModuleList(heads) + + def forward(self, x: Tensor) -> Tensor: + return torch.cat([head(x) for head in self.heads], dim=1) + + +class Bottleneck2D(Module): + def __init__( + self, inplanes: int, planes: int, stride: Union[int, Tuple[int, int]] = 1, downsample: Optional[Module] = None + ) -> None: + super().__init__() + + self.bn1 = nn.BatchNorm2d(inplanes) + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1) + self.bn2 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1) + self.bn3 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d(planes, planes * 2, kernel_size=1) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.bn1(x) + out = self.relu(out) + out = self.conv1(out) + + out = self.bn2(out) + out = self.relu(out) + out = self.conv2(out) + + out = self.bn3(out) + out = self.relu(out) + out = self.conv3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + + return out + + +class Hourglass(Module): + def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2) -> None: + super().__init__() + self.depth = depth + self.block = block + self.expansion = expansion + self.hg = self._make_hour_glass(block, num_blocks, planes, depth) + + def _make_residual(self, block: Type[Bottleneck2D], num_blocks: int, planes: int) -> Module: + layers = [] + for _ in range(0, num_blocks): + layers.append(block(planes * self.expansion, planes)) + return nn.Sequential(*layers) + + def _make_hour_glass(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int) -> nn.ModuleList: + hgl = [] + for i in range(depth): + res = [] + for _ in range(3): + res.append(self._make_residual(block, num_blocks, planes)) + if i == 0: + res.append(self._make_residual(block, num_blocks, planes)) + hgl.append(nn.ModuleList(res)) + return nn.ModuleList(hgl) + + def _hour_glass_forward(self, n: int, x: Tensor) -> Tensor: + up1 = self.hg[n - 1][0](x) # type: ignore[index] + low1 = F.max_pool2d(x, 2, stride=2) + low1 = self.hg[n - 1][1](low1) # type: ignore[index] + + if n > 1: + low2 = self._hour_glass_forward(n - 1, low1) + else: + low2 = self.hg[n - 1][3](low1) # type: ignore[index] + low3 = self.hg[n - 1][2](low2) # type: ignore[index] + up2 = F.interpolate(low3, size=up1.shape[2:]) + out = up1 + up2 + return out + + def forward(self, x: Tensor) -> Tensor: + return self._hour_glass_forward(self.depth, x) + + +class HourglassNet(Module): + """Hourglass model from Newell et al ECCV 2016.""" + + def __init__( + self, + block: Type[Bottleneck2D], + head: Type[Module], + depth: int, + num_stacks: int, + num_blocks: int, + num_classes: int, + input_channels: int, + expansion: int = 2, + ) -> None: + super().__init__() + + self.inplanes = 64 + self.num_feats = 128 + self.num_stacks = num_stacks + self.expansion = expansion + self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=2, padding=3) + self.bn1 = nn.BatchNorm2d(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.layer1 = self._make_residual(block, self.inplanes, 1) + self.layer2 = self._make_residual(block, self.inplanes, 1) + self.layer3 = self._make_residual(block, self.num_feats, 1) + self.maxpool = nn.MaxPool2d(2, stride=2) + + # Build hourglass modules + ch = self.num_feats * self.expansion + hgl, res, fc, score, fc_, score_ = [], [], [], [], [], [] + for i in range(num_stacks): + hgl.append(Hourglass(block, num_blocks, self.num_feats, depth)) + res.append(self._make_residual(block, self.num_feats, num_blocks)) + fc.append(self._make_fc(ch, ch)) + score.append(head(ch)) + if i < num_stacks - 1: + fc_.append(nn.Conv2d(ch, ch, kernel_size=1)) + score_.append(nn.Conv2d(num_classes, ch, kernel_size=1)) + self.hg = nn.ModuleList(hgl) + self.res = nn.ModuleList(res) + self.fc = nn.ModuleList(fc) + self.score = nn.ModuleList(score) + self.fc_ = nn.ModuleList(fc_) + self.score_ = nn.ModuleList(score_) + + def _make_residual( + self, block: Type[Bottleneck2D], planes: int, blocks: int, stride: Union[int, Tuple[int, int]] = 1 + ) -> Module: + downsample = None + if stride != 1 or self.inplanes != planes * self.expansion: + downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes * self.expansion, kernel_size=1, stride=stride)) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * self.expansion + for _ in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def _make_fc(self, inplanes: int, outplanes: int) -> Module: + bn = nn.BatchNorm2d(inplanes) + conv = nn.Conv2d(inplanes, outplanes, kernel_size=1) + return nn.Sequential(conv, bn, self.relu) + + def forward(self, x: Tensor) -> Tensor: + out = [] + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + x = self.layer1(x) + x = self.maxpool(x) + x = self.layer2(x) + x = self.layer3(x) + + for i in range(self.num_stacks): + y = self.hg[i](x) + y = self.res[i](y) + y = self.fc[i](y) + score = self.score[i](y) + out.append(score) + if i < self.num_stacks - 1: + fc_ = self.fc_[i](y) + score_ = self.score_[i](score) + x = x + fc_ + score_ + + return y + + +def hg(cfg: HourglassConfig) -> HourglassNet: + """Create HourglassNet.""" + return HourglassNet( + Bottleneck2D, + head=cfg.head, + depth=cfg.depth, + num_stacks=cfg.num_stacks, + num_blocks=cfg.num_blocks, + num_classes=cfg.num_classes, + input_channels=cfg.input_channels, + ) + + +# [Backbone decoders] +class SuperpointDecoder(Module): + """Junction decoder based on the SuperPoint architecture. + + Args: + input_feat_dim: channel size of the input features. + + Returns: + the junction heatmap, with shape (B, H, W). + + """ + + def __init__(self, input_feat_dim: int = 128, grid_size: int = 8) -> None: + super().__init__() + self.relu = nn.ReLU(inplace=True) + # Perform strided convolution when using lcnn backbone. + self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=2, padding=1) + self.convPb = nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0) + self.grid_size = grid_size + + def forward(self, input_features: Tensor) -> Tensor: + feat = self.relu(self.convPa(input_features)) + semi = self.convPb(feat) + + # Convert from semi-dense to dense heatmap + junc_prob = softmax(semi, dim=1) + junc_pred = pixel_shuffle(junc_prob[:, :-1, :, :], self.grid_size)[:, 0] + return junc_pred + + +class PixelShuffleDecoder(Module): + """Pixel shuffle decoder used to predict the line heatmap. + + Args: + input_feat_dim: channel size of the input features. + num_upsample: how many upsamples are performed. + output_channel: number of output channels. + + Returns: + the (B, 1, H, W) line heatmap. + + """ + + def __init__(self, input_feat_dim: int = 128, num_upsample: int = 2, output_channel: int = 2) -> None: + super().__init__() + # Get channel parameters + self.channel_conf = self.get_channel_conf(num_upsample) + + # Define the pixel shuffle + self.pixshuffle = nn.PixelShuffle(2) + + # Process the feature + conv_block_lst = [] + # The input block + conv_block_lst.append( + nn.Sequential( + nn.Conv2d(input_feat_dim, self.channel_conf[0], kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(self.channel_conf[0]), + nn.ReLU(inplace=True), + ) + ) + + # Intermediate block + for channel in self.channel_conf[1:-1]: + conv_block_lst.append( + nn.Sequential( + nn.Conv2d(channel, channel, kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(channel), + nn.ReLU(inplace=True), + ) + ) + + # Output block + conv_block_lst.append( + nn.Sequential(nn.Conv2d(self.channel_conf[-1], output_channel, kernel_size=1, stride=1, padding=0)) + ) + self.conv_block_lst = nn.ModuleList(conv_block_lst) + + def get_channel_conf(self, num_upsample: int) -> List[int]: + """Get num of channels based on number of upsampling.""" + if num_upsample == 2: + return [256, 64, 16] + return [256, 64, 16, 4] + + def forward(self, input_features: Tensor) -> Tensor: + # Iterate til output block + out = input_features + for block in self.conv_block_lst[:-1]: + out = block(out) + out = self.pixshuffle(out) + + # Output layer + out = self.conv_block_lst[-1](out) + heatmap = softmax(out, dim=1)[:, 1, :, :] + + return heatmap + + +class SuperpointDescriptor(Module): + """Descriptor decoder based on the SuperPoint arcihtecture. + + Args: + input_feat_dim: channel size of the input features. + + Returns: + the semi-dense descriptors with shape (B, 128, H/4, W/4). + + """ + + def __init__(self, input_feat_dim: int = 128) -> None: + super().__init__() + self.relu = nn.ReLU(inplace=True) + self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1) + self.convPb = nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0) + + def forward(self, input_features: Tensor) -> Tensor: + feat = self.relu(self.convPa(input_features)) + semi = self.convPb(feat) + + return semi + + +# [Combination of all previous models in one] + + +class SOLD2Net(Module): + """Full network for SOLD². + + Args: + model_cfg: the configuration as a Dict. + + Returns: + a Dict with the following values: + junctions: heatmap of junctions. + heatmap: line heatmap. + descriptors: semi-dense descriptors. + + """ + + def __init__(self, model_cfg: Dict[str, Any]) -> None: + super().__init__() + self.cfg = model_cfg + + # Backbone + self.backbone_net = HourglassBackbone(**self.cfg["backbone_cfg"]) + feat_channel = 256 + + # Junction decoder + self.junction_decoder = SuperpointDecoder(feat_channel, self.cfg["grid_size"]) + + # Line heatmap decoder + self.heatmap_decoder = PixelShuffleDecoder(feat_channel, num_upsample=2) + + # Descriptor decoder + if "use_descriptor" in self.cfg: + self.descriptor_decoder = SuperpointDescriptor(feat_channel) + + def forward(self, input_images: Tensor) -> Dict[str, Tensor]: + # The backbone + features = self.backbone_net(input_images) + + # junction decoder + junctions = self.junction_decoder(features) + + # heatmap decoder + heatmaps = self.heatmap_decoder(features) + + outputs = {"junctions": junctions, "heatmap": heatmaps} + + # Descriptor decoder + if "use_descriptor" in self.cfg: + outputs["descriptors"] = self.descriptor_decoder(features) + + return outputs diff --git a/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2.py b/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2.py new file mode 100644 index 0000000000000000000000000000000000000000..0fccbac9d8da41724b0f070f433de3b7d3568ba0 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2.py @@ -0,0 +1,356 @@ +# 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. +# + +import warnings +from typing import Any, Dict, Optional, Tuple + +import torch +import torch.nn.functional as F + +from kornia.core import Module, Tensor, concatenate, pad, stack +from kornia.core.check import KORNIA_CHECK_SHAPE +from kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfg +from kornia.geometry.conversions import normalize_pixel_coordinates +from kornia.utils import dataclass_to_dict, dict_to_dataclass + +from .backbones import SOLD2Net +from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions + +urls: Dict[str, str] = {} +urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth" + + +class SOLD2(Module): + r"""Module, which detects and describe line segments in an image. + + This is based on the original code from the paper "SOLD²: Self-supervised + Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details. + + Args: + config: Dict specifying parameters. None will load the default parameters, + which are tuned for images in the range 400~800 px. + pretrained: If True, download and set pretrained weights to the model. + + Returns: + The raw junction and line heatmaps, the semi-dense descriptor map, + as well as the list of detected line segments (ij coordinates convention). + + Example: + >>> images = torch.rand(2, 1, 512, 512) + >>> sold2 = SOLD2() + >>> outputs = sold2(images) + >>> line_seg1 = outputs["line_segments"][0] + >>> line_seg2 = outputs["line_segments"][1] + >>> desc1 = outputs["dense_desc"][0] + >>> desc2 = outputs["dense_desc"][1] + >>> matches = sold2.match(line_seg1, line_seg2, desc1[None], desc2[None]) + + """ + + def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None: + if isinstance(config, dict): + warnings.warn( + "Usage of config as a plain dictionary is deprecated in favor of" + " `kornia.features.sold2.structures.DetectorCfg`. The support of plain dictionaries" + "as config will be removed in kornia v0.8.0 (December 2024).", + category=DeprecationWarning, + stacklevel=2, + ) + config = dict_to_dataclass(config, DetectorCfg) + super().__init__() + # Initialize some parameters + self.config = config if config is not None else DetectorCfg() + self.config.use_descriptor = True # Only difference to SOLD2_detector DetectorCfg + self.grid_size = self.config.grid_size + self.junc_detect_thresh = self.config.detection_thresh + self.max_num_junctions = self.config.max_num_junctions + + # Load the pre-trained model + self.model = SOLD2Net(dataclass_to_dict(self.config)) + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu")) + state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"]) + self.model.load_state_dict(state_dict) + self.eval() + + # Initialize the line detector + self.line_detector = LineSegmentDetectionModule(self.config.line_detector_cfg) + + # Initialize the line matcher + self.line_matcher = WunschLineMatcher(self.config.line_matcher_cfg) + + def forward(self, img: Tensor) -> Dict[str, Any]: + """Run forward. + + Args: + img: batched images with shape :math:`(B, 1, H, W)`. + + Returns: + line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`. + junction_heatmap: raw junction heatmap of shape :math:`(B, H, W)`. + line_heatmap: raw line heatmap of shape :math:`(B, H, W)`. + dense_desc: the semi-dense descriptor map of shape :math:`(B, 128, H/4, W/4)`. + + """ + KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"]) + outputs = {} + + # Forward pass of the CNN backbone + net_outputs = self.model(img) + outputs["junction_heatmap"] = net_outputs["junctions"] + outputs["line_heatmap"] = net_outputs["heatmap"] + outputs["dense_desc"] = net_outputs["descriptors"] + + # Loop through all images + lines = [] + for junc_prob, heatmap in zip(net_outputs["junctions"], net_outputs["heatmap"]): + # Get the junctions + junctions = prob_to_junctions(junc_prob, self.grid_size, self.junc_detect_thresh, self.max_num_junctions) + + # Run the line detector + line_map, junctions, _ = self.line_detector.detect(junctions, heatmap) + lines.append(line_map_to_segments(junctions, line_map)) + outputs["line_segments"] = lines + + return outputs + + def match(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor: + """Find the best matches between two sets of line segments and their corresponding descriptors. + + Args: + line_seg1: list of line segments in image 1, with shape [num_lines, 2, 2]. + line_seg2: list of line segments in image 2, with shape [num_lines, 2, 2]. + desc1: semi-dense descriptor map of image 1, with shape [1, 128, H/4, W/4]. + desc2: semi-dense descriptor map of image 2, with shape [1, 128, H/4, W/4]. + + Returns: + A np.array of size [num_lines1] indicating the index in line_seg2 of the matched line, + for each line in line_seg1. -1 means that the line is not matched. + + """ + return self.line_matcher(line_seg1, line_seg2, desc1, desc2) + + def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]: + del state_dict["w_junc"] + del state_dict["w_heatmap"] + del state_dict["w_desc"] + state_dict["heatmap_decoder.conv_block_lst.2.0.weight"] = state_dict["heatmap_decoder.conv_block_lst.2.weight"] + state_dict["heatmap_decoder.conv_block_lst.2.0.bias"] = state_dict["heatmap_decoder.conv_block_lst.2.bias"] + del state_dict["heatmap_decoder.conv_block_lst.2.weight"] + del state_dict["heatmap_decoder.conv_block_lst.2.bias"] + return state_dict + + +class WunschLineMatcher(Module): + """Class matching two sets of line segments with the Needleman-Wunsch algorithm. + + TODO: move it later in kornia.feature.matching + """ + + def __init__(self, config: Optional[LineMatcherCfg] = None) -> None: + super().__init__() + # Initialize the parameters + if config is None: + config = LineMatcherCfg() + self.config = config + self.cross_check = self.config.cross_check + self.num_samples = self.config.num_samples + self.min_dist_pts = self.config.min_dist_pts + self.top_k_candidates = self.config.top_k_candidates + self.grid_size = self.config.grid_size + self.line_score = self.config.line_score + + def forward(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor: + """Find the best matches between two sets of line segments and their corresponding descriptors.""" + KORNIA_CHECK_SHAPE(line_seg1, ["N", "2", "2"]) + KORNIA_CHECK_SHAPE(line_seg2, ["N", "2", "2"]) + KORNIA_CHECK_SHAPE(desc1, ["B", "D", "H", "H"]) + KORNIA_CHECK_SHAPE(desc2, ["B", "D", "H", "H"]) + device = desc1.device + img_size1 = (desc1.shape[2] * self.grid_size, desc1.shape[3] * self.grid_size) + img_size2 = (desc2.shape[2] * self.grid_size, desc2.shape[3] * self.grid_size) + + # Default case when an image has no lines + if len(line_seg1) == 0: + return torch.empty(0, dtype=torch.int, device=device) + if len(line_seg2) == 0: + return -torch.ones(len(line_seg1), dtype=torch.int, device=device) + + # Sample points regularly along each line + line_points1, valid_points1 = self.sample_line_points(line_seg1) + line_points2, valid_points2 = self.sample_line_points(line_seg2) + line_points1 = line_points1.reshape(-1, 2) + line_points2 = line_points2.reshape(-1, 2) + + # Extract the descriptors for each point + grid1 = keypoints_to_grid(line_points1, img_size1) + grid2 = keypoints_to_grid(line_points2, img_size2) + desc1 = F.normalize(F.grid_sample(desc1, grid1, align_corners=False)[0, :, :, 0], dim=0) + desc2 = F.normalize(F.grid_sample(desc2, grid2, align_corners=False)[0, :, :, 0], dim=0) + + # Precompute the distance between line points for every pair of lines + # Assign a score of -1 for invalid points + scores = desc1.t() @ desc2 + scores[~valid_points1.flatten()] = -1 + scores[:, ~valid_points2.flatten()] = -1 + scores = scores.reshape(len(line_seg1), self.num_samples, len(line_seg2), self.num_samples) + scores = scores.permute(0, 2, 1, 3) + # scores.shape = (n_lines1, n_lines2, num_samples, num_samples) + + # Pre-filter the line candidates and find the best match for each line + matches = self.filter_and_match_lines(scores) + + # [Optionally] filter matches with mutual nearest neighbor filtering + if self.cross_check: + matches2 = self.filter_and_match_lines(scores.permute(1, 0, 3, 2)) + mutual = matches2[matches] == torch.arange(len(line_seg1), device=device) + matches[~mutual] = -1 + + return matches + + def sample_line_points(self, line_seg: Tensor) -> Tuple[Tensor, Tensor]: + """Regularly sample points along each line segments, with a minimal distance between each point. + + Pad the remaining points. + + Args: + line_seg: an Nx2x2 Tensor. + + Returns: + line_points: an N x num_samples x 2 Tensor. + valid_points: a boolean N x num_samples Tensor. + """ + KORNIA_CHECK_SHAPE(line_seg, ["N", "2", "2"]) + num_lines = len(line_seg) + line_lengths = torch.norm(line_seg[:, 0] - line_seg[:, 1], dim=1) + dev = line_seg.device + # Sample the points separated by at least min_dist_pts along each line + # The number of samples depends on the length of the line + num_samples_lst = torch.clamp( + torch.div(line_lengths, self.min_dist_pts, rounding_mode="floor"), 2, self.num_samples + ).int() + line_points = torch.empty((num_lines, self.num_samples, 2), dtype=torch.float, device=dev) + valid_points = torch.empty((num_lines, self.num_samples), dtype=torch.bool, device=dev) + for n_samp in range(2, self.num_samples + 1): + # Consider all lines where we can fit up to n_samp points + cur_mask = num_samples_lst == n_samp + cur_line_seg = line_seg[cur_mask] + line_points_x = batched_linspace(cur_line_seg[:, 0, 0], cur_line_seg[:, 1, 0], n_samp, dim=-1) + line_points_y = batched_linspace(cur_line_seg[:, 0, 1], cur_line_seg[:, 1, 1], n_samp, dim=-1) + cur_line_points = stack([line_points_x, line_points_y], -1) + + # Pad + cur_line_points = pad(cur_line_points, (0, 0, 0, self.num_samples - n_samp)) + cur_valid_points = torch.ones(len(cur_line_seg), self.num_samples, dtype=torch.bool, device=dev) + cur_valid_points[:, n_samp:] = False + + line_points[cur_mask] = cur_line_points + valid_points[cur_mask] = cur_valid_points + + return line_points, valid_points + + def filter_and_match_lines(self, scores: Tensor) -> Tensor: + """Use scores to keep the top k best lines. + + Compute the Needleman- Wunsch algorithm on each candidate pairs, and keep the highest score. + + Args: + scores: a (N, M, n, n) Tensor containing the pairwise scores + of the elements to match. + + Returns: + matches: a (N) Tensor containing the indices of the best match + """ + KORNIA_CHECK_SHAPE(scores, ["M", "N", "n", "n"]) + + # Pre-filter the pairs and keep the top k best candidate lines + line_scores1 = scores.max(3)[0] + valid_scores1 = line_scores1 != -1 + line_scores1 = (line_scores1 * valid_scores1).sum(2) / valid_scores1.sum(2) + line_scores2 = scores.max(2)[0] + valid_scores2 = line_scores2 != -1 + line_scores2 = (line_scores2 * valid_scores2).sum(2) / valid_scores2.sum(2) + line_scores = (line_scores1 + line_scores2) / 2 + topk_lines = torch.argsort(line_scores, dim=1)[:, -self.top_k_candidates :] + # topk_lines.shape = (n_lines1, top_k_candidates) + + top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1) + + # Consider the reversed line segments as well + top_scores = concatenate([top_scores, torch.flip(top_scores, dims=[-1])], 1) + + # Compute the line distance matrix with Needleman-Wunsch algo and + # retrieve the closest line neighbor + n_lines1, top2k, n, m = top_scores.shape + top_scores = top_scores.reshape((n_lines1 * top2k, n, m)) + nw_scores = self.needleman_wunsch(top_scores) + nw_scores = nw_scores.reshape(n_lines1, top2k) + matches = torch.remainder(torch.argmax(nw_scores, dim=1), top2k // 2) + matches = topk_lines[torch.arange(n_lines1), matches] + return matches + + def needleman_wunsch(self, scores: Tensor) -> Tensor: + """Batched implementation of the Needleman-Wunsch algorithm. + + The cost of the InDel operation is set to 0 by subtracting the gap + penalty to the scores. + + Args: + scores: a (B, N, M) Tensor containing the pairwise scores + of the elements to match. + """ + KORNIA_CHECK_SHAPE(scores, ["B", "N", "M"]) + b, n, m = scores.shape + + # Recalibrate the scores to get a gap score of 0 + gap = 0.1 + nw_scores = scores - gap + dev = scores.device + # Run the dynamic programming algorithm + nw_grid = torch.zeros(b, n + 1, m + 1, dtype=torch.float, device=dev) + for i in range(n): + for j in range(m): + nw_grid[:, i + 1, j + 1] = torch.maximum( + torch.maximum(nw_grid[:, i + 1, j], nw_grid[:, i, j + 1]), nw_grid[:, i, j] + nw_scores[:, i, j] + ) + + return nw_grid[:, -1, -1] + + +def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor: + """Convert a list of keypoints into a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate. + + Args: + keypoints: a tensor [N, 2] of N keypoints (ij coordinates convention). + img_size: the original image size (H, W) + + """ + KORNIA_CHECK_SHAPE(keypoints, ["N", "2"]) + n_points = len(keypoints) + grid_points = normalize_pixel_coordinates(keypoints[:, [1, 0]], img_size[0], img_size[1]) + grid_points = grid_points.view(-1, n_points, 1, 2) + return grid_points + + +def batched_linspace(start: Tensor, end: Tensor, step: int, dim: int) -> Tensor: + """Batch version of torch.normalize (similar to the numpy one).""" + intervals = ((end - start) / (step - 1)).unsqueeze(dim) + broadcast_size = [1] * len(intervals.shape) + broadcast_size[dim] = step + samples = torch.arange(step, dtype=torch.float, device=start.device).reshape(broadcast_size) + samples = start.unsqueeze(dim) + samples * intervals + return samples diff --git a/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2_detector.py b/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..33354e034763213ec03820848e76b3bb9d225b9f --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/sold2/sold2_detector.py @@ -0,0 +1,583 @@ +# 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. +# + +import math +import warnings +from typing import Any, Dict, Optional, Tuple + +import torch + +from kornia.core import Module, Tensor, concatenate, sin, stack, tensor, where, zeros +from kornia.core.check import KORNIA_CHECK_SHAPE +from kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfg +from kornia.geometry.bbox import nms +from kornia.utils import dataclass_to_dict, dict_to_dataclass, torch_meshgrid + +from .backbones import SOLD2Net + +urls: Dict[str, str] = {} +urls["wireframe"] = "https://cvg-data.inf.ethz.ch/SOLD2/sold2_wireframe.tar" + + +class SOLD2_detector(Module): + r"""Module, which detects line segments in an image. + + This is based on the original code from the paper "SOLD²: Self-supervised + Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details. + + Args: + config (DetectorCfg): Configuration object containing all parameters. None will load the default parameters, + which are tuned for images in the range 400~800 px. Using a dataclass ensures type safety and clearer + parameter management. + pretrained (bool): If True, download and set pretrained weights to the model. + + Returns: + The raw junction and line heatmaps, as well as the list of detected line segments (ij coordinates convention). + + Example: + >>> img = torch.rand(1, 1, 512, 512) + >>> sold2_detector = SOLD2_detector(pretrained=False) + >>> line_segments = sold2_detector(img)["line_segments"] + + """ + + def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None: + if isinstance(config, dict): + warnings.warn( + "Usage of config as a plain dictionary is deprecated in favor of" + "`kornia.features.sold2.structures.DetectorCfg`. The support of plain" + "dictionaries as config will be removed in kornia v0.8.0 (December 2024).", + category=DeprecationWarning, + stacklevel=2, + ) + config = dict_to_dataclass(config, DetectorCfg) + super().__init__() + # Initialize some parameters + self.config = config if config is not None else DetectorCfg() + self.grid_size = self.config.grid_size + self.junc_detect_thresh = self.config.detection_thresh + self.max_num_junctions = self.config.max_num_junctions + + # Load the pre-trained model + self.model = SOLD2Net(dataclass_to_dict(self.config)) + + if pretrained: + pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu")) + state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"]) + self.model.load_state_dict(state_dict) + self.eval() + + # Initialize the line detector with a configuration from the dataclass + self.line_detector = LineSegmentDetectionModule(self.config.line_detector_cfg) + + def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]: + del state_dict["w_junc"] + del state_dict["w_heatmap"] + del state_dict["w_desc"] + state_dict["heatmap_decoder.conv_block_lst.2.0.weight"] = state_dict["heatmap_decoder.conv_block_lst.2.weight"] + state_dict["heatmap_decoder.conv_block_lst.2.0.bias"] = state_dict["heatmap_decoder.conv_block_lst.2.bias"] + del state_dict["heatmap_decoder.conv_block_lst.2.weight"] + del state_dict["heatmap_decoder.conv_block_lst.2.bias"] + return state_dict + + def forward(self, img: Tensor) -> Dict[str, Any]: + """Run forward. + + Args: + img: batched images with shape :math:`(B, 1, H, W)`. + + Returns: + line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`. + junction_heatmap: raw junction heatmap of shape :math:`(B, H, W)`. + line_heatmap: raw line heatmap of shape :math:`(B, H, W)`. + + """ + KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"]) + outputs = {} + + # Forward pass of the CNN backbone + net_outputs = self.model(img) + outputs["junction_heatmap"] = net_outputs["junctions"] + outputs["line_heatmap"] = net_outputs["heatmap"] + + # Loop through all images + lines = [] + for junc_prob, heatmap in zip(net_outputs["junctions"], net_outputs["heatmap"]): + # Get the junctions + junctions = prob_to_junctions(junc_prob, self.grid_size, self.junc_detect_thresh, self.max_num_junctions) + + # Run the line detector + line_map, junctions, _ = self.line_detector.detect(junctions, heatmap) + lines.append(line_map_to_segments(junctions, line_map)) + outputs["line_segments"] = lines + + return outputs + + +class LineSegmentDetectionModule: + r"""Module extracting line segments from junctions and line heatmaps. + + Args: + config (LineDetectorCfg): Configuration dataclass containing all settings required for line segment detection. + - detect_thresh (float): Probability threshold for mean activation (0. ~ 1.). + - num_samples (int): Number of sampling locations along the line segments. + - inlier_thresh (float): Minimum inlier ratio to satisfy (0. ~ 1.) => 0. means no threshold. + - heatmap_low_thresh (float): Lowest threshold for pixel considered as a candidate in junction recovery. + - heatmap_high_thresh (float): Higher threshold for NMS in junction recovery. + - max_local_patch_radius (float): Maximum patch to be considered in local maximum search. + - lambda_radius (float): Lambda factor in linear local maximum search formulation. + - use_candidate_suppression (bool): Apply candidate suppression to break long segments into sub-segments. + - nms_dist_tolerance (float): Distance tolerance for NMS. Decides whether the junctions are on the line. + - use_heatmap_refinement (bool): Whether to use heatmap refinement methods. + - heatmap_refine_cfg: Configuration for heatmap refinement methods. + - use_junction_refinement (bool): Whether to use junction refinement methods. + - junction_refine_cfg: Configuration for junction refinement methods. + + Example: + >>> config = LineDetectorCfg(detect_thresh=0.6, use_heatmap_refinement=True) + >>> module = LineSegmentDetectionModule(config) + >>> junctions, heatmap = torch.rand(10, 2), torch.rand(256, 256) + >>> line_map, junctions, _ = module.detect(junctions, heatmap) + + """ + + def __init__(self, config: Optional[LineDetectorCfg] = None) -> None: + # Load LineDetectorCfg + if config is None: + config = LineDetectorCfg() + self.config = config + + # Line detection parameters + self.detect_thresh = self.config.detect_thresh + # self.detect_thresh = detect_thresh + + # Line sampling parameters + self.num_samples = self.config.num_samples + self.inlier_thresh = self.config.inlier_thresh + self.local_patch_radius = self.config.max_local_patch_radius + self.lambda_radius = self.config.lambda_radius + + # Detecting junctions on the boundary parameters + self.low_thresh = self.config.heatmap_low_thresh + self.high_thresh = self.config.heatmap_high_thresh + + # Pre-compute the linspace sampler + self.torch_sampler = torch.linspace(0, 1, self.num_samples) + + # Long line segment suppression configuration + self.use_candidate_suppression = self.config.use_candidate_suppression + self.nms_dist_tolerance = self.config.nms_dist_tolerance + + # Heatmap refinement configuration + self.use_heatmap_refinement = self.config.use_heatmap_refinement + self.heatmap_refine_cfg = self.config.heatmap_refine_cfg + if self.use_heatmap_refinement and self.heatmap_refine_cfg is None: + raise ValueError("[Error] Missing heatmap refinement config.") + + # Junction refinement configuration + self.use_junction_refinement = self.config.use_junction_refinement + self.junction_refine_cfg = self.config.junction_refine_cfg + if self.use_junction_refinement and self.junction_refine_cfg is None: + raise ValueError("[Error] Missing junction refinement config.") + + def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple[Tensor, Tensor, Tensor]: + """Perform line segment detection.""" + KORNIA_CHECK_SHAPE(heatmap, ["H", "W"]) + H, W = heatmap.shape + device = junctions.device + + # Perform the heatmap refinement + if self.use_heatmap_refinement and isinstance(self.heatmap_refine_cfg, HeatMapRefineCfg): + if self.heatmap_refine_cfg.mode == "global": + heatmap = self.refine_heatmap( + heatmap, self.heatmap_refine_cfg.ratio, self.heatmap_refine_cfg.valid_thresh + ) + elif self.heatmap_refine_cfg.mode == "local": + heatmap = self.refine_heatmap_local( + heatmap, + self.heatmap_refine_cfg.num_blocks, + self.heatmap_refine_cfg.overlap_ratio, + self.heatmap_refine_cfg.ratio, + self.heatmap_refine_cfg.valid_thresh, + ) + + # Initialize empty line map + num_junctions = len(junctions) + line_map_pred = zeros([num_junctions, num_junctions], device=device, dtype=torch.int32) + + # Stop if there are not enough junctions + if num_junctions < 2: + return line_map_pred, junctions, heatmap + + # Generate the candidate map + candidate_map = torch.triu( + torch.ones([num_junctions, num_junctions], device=device, dtype=torch.int32), diagonal=1 + ) + + # Optionally perform candidate filtering + if self.use_candidate_suppression: + candidate_map = self.candidate_suppression(junctions, candidate_map) + + # Fetch the candidates + candidate_indices = where(candidate_map) + candidate_index_map = concatenate([candidate_indices[0][..., None], candidate_indices[1][..., None]], -1) + + # Get the corresponding start and end junctions + candidate_junc_start = junctions[candidate_index_map[:, 0]] + candidate_junc_end = junctions[candidate_index_map[:, 1]] + + # Get the sampling locations (N x 64) + sampler = self.torch_sampler.to(device)[None] + cand_samples_h = candidate_junc_start[:, 0:1] * sampler + candidate_junc_end[:, 0:1] * (1 - sampler) + cand_samples_w = candidate_junc_start[:, 1:2] * sampler + candidate_junc_end[:, 1:2] * (1 - sampler) + + # Clip to image boundary + cand_h = torch.clamp(cand_samples_h, min=0, max=H - 1) + cand_w = torch.clamp(cand_samples_w, min=0, max=W - 1) + + # [Local maximum search] + # Compute normalized segment lengths + segments_length = torch.sqrt( + torch.sum((candidate_junc_start.to(torch.float32) - candidate_junc_end.to(torch.float32)) ** 2, dim=-1) + ) + normalized_seg_length = segments_length / (((H**2) + (W**2)) ** 0.5) + + # Perform local max search + num_cand = len(cand_h) + group_size = 10000 + if num_cand > group_size: + num_iter = math.ceil(num_cand / group_size) + sampled_feat_lst = [] + for iter_idx in range(num_iter): + if not iter_idx == num_iter - 1: + cand_h_ = cand_h[iter_idx * group_size : (iter_idx + 1) * group_size, :] + cand_w_ = cand_w[iter_idx * group_size : (iter_idx + 1) * group_size, :] + normalized_seg_length_ = normalized_seg_length[iter_idx * group_size : (iter_idx + 1) * group_size] + else: + cand_h_ = cand_h[iter_idx * group_size :, :] + cand_w_ = cand_w[iter_idx * group_size :, :] + normalized_seg_length_ = normalized_seg_length[iter_idx * group_size :] + sampled_feat_ = self.detect_local_max(heatmap, cand_h_, cand_w_, H, W, normalized_seg_length_, device) + sampled_feat_lst.append(sampled_feat_) + sampled_feat = concatenate(sampled_feat_lst, 0) + else: + sampled_feat = self.detect_local_max(heatmap, cand_h, cand_w, H, W, normalized_seg_length, device) + + # [Simple threshold detection] + # detection_results is a mask over all candidates + detection_results = torch.mean(sampled_feat, dim=-1) > self.detect_thresh + + # [Inlier threshold detection] + if self.inlier_thresh > 0: + inlier_ratio = torch.sum(sampled_feat > self.detect_thresh, dim=-1).to(heatmap.dtype) / self.num_samples + detection_results_inlier = inlier_ratio >= self.inlier_thresh + detection_results = detection_results * detection_results_inlier + + # Convert detection results back to line_map_pred + detected_junc_indexes = candidate_index_map[detection_results] + line_map_pred[detected_junc_indexes[:, 0], detected_junc_indexes[:, 1]] = 1 + line_map_pred[detected_junc_indexes[:, 1], detected_junc_indexes[:, 0]] = 1 + + # [Junction refinement] + if self.use_junction_refinement and len(detected_junc_indexes) > 0: + junctions, line_map_pred = self.refine_junction_perturb(junctions, line_map_pred, heatmap, H, W, device) + + return line_map_pred, junctions, heatmap + + def refine_heatmap(self, heatmap: Tensor, ratio: float = 0.2, valid_thresh: float = 1e-2) -> Tensor: + """Global heatmap refinement method.""" + # Grab the top 10% values + heatmap_values = heatmap[heatmap > valid_thresh] + sorted_values = torch.sort(heatmap_values, descending=True)[0] + top10_len = math.ceil(sorted_values.shape[0] * ratio) + max20 = torch.mean(sorted_values[:top10_len]) + heatmap = torch.clamp(heatmap / max20, min=0.0, max=1.0) + return heatmap + + def refine_heatmap_local( + self, + heatmap: Tensor, + num_blocks: int = 5, + overlap_ratio: float = 0.5, + ratio: float = 0.2, + valid_thresh: float = 2e-3, + ) -> Tensor: + """Local heatmap refinement method.""" + # Get the shape of the heatmap + H, W = heatmap.shape + increase_ratio = 1 - overlap_ratio + h_block = round(H / (1 + (num_blocks - 1) * increase_ratio)) + w_block = round(W / (1 + (num_blocks - 1) * increase_ratio)) + + # Iterate through each block + count_map = zeros(heatmap.shape, dtype=torch.int, device=heatmap.device) + heatmap_output = zeros(heatmap.shape, dtype=torch.float, device=heatmap.device) + for h_idx in range(num_blocks): + for w_idx in range(num_blocks): + # Fetch the heatmap + h_start = round(h_idx * h_block * increase_ratio) + w_start = round(w_idx * w_block * increase_ratio) + h_end = h_start + h_block if h_idx < num_blocks - 1 else H + w_end = w_start + w_block if w_idx < num_blocks - 1 else W + + subheatmap = heatmap[h_start:h_end, w_start:w_end] + if subheatmap.max() > valid_thresh: + subheatmap = self.refine_heatmap(subheatmap, ratio, valid_thresh=valid_thresh) + + # Aggregate it to the final heatmap + heatmap_output[h_start:h_end, w_start:w_end] += subheatmap + count_map[h_start:h_end, w_start:w_end] += 1 + heatmap_output = torch.clamp(heatmap_output / count_map, max=1.0, min=0.0) + + return heatmap_output + + def candidate_suppression(self, junctions: Tensor, candidate_map: Tensor) -> Tensor: + """Suppress overlapping long lines in the candidate segments.""" + # Define the distance tolerance + dist_tolerance = self.nms_dist_tolerance + + # Compute distance between junction pairs + # (num_junc x 1 x 2) - (1 x num_junc x 2) => num_junc x num_junc map + line_dist_map = torch.sum((torch.unsqueeze(junctions, dim=1) - junctions[None, ...]) ** 2, dim=-1) ** 0.5 + + # Fetch all the "detected lines" + seg_indexes = where(torch.triu(candidate_map, diagonal=1)) + start_point_idxs = seg_indexes[0] + end_point_idxs = seg_indexes[1] + start_points = junctions[start_point_idxs, :] + end_points = junctions[end_point_idxs, :] + + # Fetch corresponding entries + line_dists = line_dist_map[start_point_idxs, end_point_idxs] + + # Check whether they are on the line + dir_vecs = (end_points - start_points) / torch.norm(end_points - start_points, dim=-1)[..., None] + # Get the orthogonal distance + cand_vecs = junctions[None, ...] - start_points.unsqueeze(dim=1) + cand_vecs_norm = torch.norm(cand_vecs, dim=-1) + # Check whether they are projected directly onto the segment + proj = torch.einsum("bij,bjk->bik", cand_vecs, dir_vecs[..., None]) / line_dists[..., None, None] + # proj is num_segs x num_junction x 1 + proj_mask = (proj >= 0) * (proj <= 1) + cand_angles = torch.acos( + torch.einsum("bij,bjk->bik", cand_vecs, dir_vecs[..., None]) / cand_vecs_norm[..., None] + ) + cand_dists = cand_vecs_norm[..., None] * sin(cand_angles) + junc_dist_mask = cand_dists <= dist_tolerance + junc_mask = junc_dist_mask * proj_mask + + # Minus starting points + num_segs = len(start_point_idxs) + junc_counts = torch.sum(junc_mask, dim=[1, 2]) + junc_counts -= junc_mask[..., 0][torch.arange(0, num_segs), start_point_idxs].to(torch.int) + junc_counts -= junc_mask[..., 0][torch.arange(0, num_segs), end_point_idxs].to(torch.int) + + # Get the invalid candidate mask + final_mask = junc_counts > 0 + candidate_map[start_point_idxs[final_mask], end_point_idxs[final_mask]] = 0 + + return candidate_map + + def refine_junction_perturb( + self, junctions: Tensor, line_map: Tensor, heatmap: Tensor, H: int, W: int, device: torch.device + ) -> Tuple[Tensor, Tensor]: + """Refine the line endpoints in a similar way as in LSD.""" + # Fetch refinement parameters + if not isinstance(self.junction_refine_cfg, JunctionRefineCfg): + raise TypeError( + "Expected to have dataclass of type JunctionRefineCfg for junction." + f"Gotcha {type(self.junction_refine_cfg)}" + ) + num_perturbs = self.junction_refine_cfg.num_perturbs + perturb_interval = self.junction_refine_cfg.perturb_interval + side_perturbs = (num_perturbs - 1) // 2 + + # Fetch the 2D perturb mat + perturb_vec = torch.arange( + start=-perturb_interval * side_perturbs, + end=perturb_interval * (side_perturbs + 1), + step=perturb_interval, + device=device, + ) + + h1_grid, w1_grid, h2_grid, w2_grid = torch_meshgrid( + [perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing="ij" + ) + + perturb_tensor = concatenate( + [h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], -1 + ) + perturb_tensor_flat = perturb_tensor.view(-1, 2, 2) + + # Fetch all the detected lines + detected_seg_indexes = where(torch.triu(line_map, diagonal=1)) + start_points = junctions[detected_seg_indexes[0]] + end_points = junctions[detected_seg_indexes[1]] + line_segments = stack([start_points, end_points], 1) + + line_segment_candidates = line_segments.unsqueeze(dim=1) + perturb_tensor_flat[None] + # Clip the boundaries + line_segment_candidates[..., 0] = torch.clamp(line_segment_candidates[..., 0], min=0, max=H - 1) + line_segment_candidates[..., 1] = torch.clamp(line_segment_candidates[..., 1], min=0, max=W - 1) + + # Iterate through all the segments + refined_segment_lst = [] + num_segments = len(line_segments) + for idx in range(num_segments): + segment = line_segment_candidates[idx] + # Get the corresponding start and end junctions + candidate_junc_start = segment[:, 0] + candidate_junc_end = segment[:, 1] + + # Get the sampling locations (N x 64) + sampler = self.torch_sampler.to(device)[None] + cand_samples_h = candidate_junc_start[:, 0:1] * sampler + candidate_junc_end[:, 0:1] * (1 - sampler) + cand_samples_w = candidate_junc_start[:, 1:2] * sampler + candidate_junc_end[:, 1:2] * (1 - sampler) + + # Clip to image boundary + cand_h = torch.clamp(cand_samples_h, min=0, max=H - 1) + cand_w = torch.clamp(cand_samples_w, min=0, max=W - 1) + + # Perform bilinear sampling + segment_feat = self.detect_bilinear(heatmap, cand_h, cand_w) + segment_results = torch.mean(segment_feat, dim=-1) + max_idx = torch.argmax(segment_results) + refined_segment_lst.append(segment[max_idx][None]) + + # Concatenate back to segments + refined_segments = concatenate(refined_segment_lst, 0) + + # Convert back to junctions and line_map + junctions_new = concatenate([refined_segments[:, 0, :], refined_segments[:, 1, :]], 0) + junctions_new = torch.unique(junctions_new, dim=0) + line_map_new = self.segments_to_line_map(junctions_new, refined_segments) + + return junctions_new, line_map_new + + def segments_to_line_map(self, junctions: Tensor, segments: Tensor) -> Tensor: + """Convert the list of segments to line map.""" + # Create empty line map + num_junctions = len(junctions) + line_map = zeros([num_junctions, num_junctions], device=junctions.device) + + # Get the indices of paired junctions + _, idx_junc1 = where(torch.all(junctions[None] == segments[:, None, 0], dim=2)) + _, idx_junc2 = where(torch.all(junctions[None] == segments[:, None, 1], dim=2)) + + # Assign the labels + line_map[idx_junc1, idx_junc2] = 1 + line_map[idx_junc2, idx_junc1] = 1 + + return line_map + + def detect_bilinear(self, heatmap: Tensor, cand_h: Tensor, cand_w: Tensor) -> Tensor: + """Detect by bilinear sampling.""" + # Get the floor and ceiling locations + cand_h_floor = torch.floor(cand_h).to(torch.long) + cand_h_ceil = torch.ceil(cand_h).to(torch.long) + cand_w_floor = torch.floor(cand_w).to(torch.long) + cand_w_ceil = torch.ceil(cand_w).to(torch.long) + + # Perform the bilinear sampling + cand_samples_feat = ( + heatmap[cand_h_floor, cand_w_floor] * (cand_h_ceil - cand_h) * (cand_w_ceil - cand_w) + + heatmap[cand_h_floor, cand_w_ceil] * (cand_h_ceil - cand_h) * (cand_w - cand_w_floor) + + heatmap[cand_h_ceil, cand_w_floor] * (cand_h - cand_h_floor) * (cand_w_ceil - cand_w) + + heatmap[cand_h_ceil, cand_w_ceil] * (cand_h - cand_h_floor) * (cand_w - cand_w_floor) + ) + + return cand_samples_feat + + def detect_local_max( + self, + heatmap: Tensor, + cand_h: Tensor, + cand_w: Tensor, + H: int, + W: int, + normalized_seg_length: Tensor, + device: torch.device, + ) -> Tensor: + """Detect by local maximum search.""" + # Compute the distance threshold + dist_thresh = 0.5 * (2**0.5) + self.lambda_radius * normalized_seg_length + # Make it N x 64 + dist_thresh = torch.repeat_interleave(dist_thresh[..., None], self.num_samples, dim=-1) + + # Compute the candidate points + cand_points = concatenate([cand_h[..., None], cand_w[..., None]], -1) + cand_points_round = torch.round(cand_points) # N x 64 x 2 + + # Construct local patches 9x9 = 81 + patch_mask = zeros([int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device) + patch_center = tensor([[self.local_patch_radius, self.local_patch_radius]], device=device, dtype=torch.float32) + H_patch_points, W_patch_points = where(patch_mask >= 0) + patch_points = concatenate([H_patch_points[..., None], W_patch_points[..., None]], -1) + # Fetch the circle region + patch_center_dist = torch.sqrt(torch.sum((patch_points - patch_center) ** 2, dim=-1)) + patch_points = patch_points[patch_center_dist <= self.local_patch_radius, :] + # Shift [0, 0] to the center + patch_points = patch_points - self.local_patch_radius + + # Construct local patch mask + patch_points_shifted = torch.unsqueeze(cand_points_round, dim=2) + patch_points[None, None] + patch_dist = torch.sqrt(torch.sum((torch.unsqueeze(cand_points, dim=2) - patch_points_shifted) ** 2, dim=-1)) + patch_dist_mask = patch_dist < dist_thresh[..., None] + + # Get all points => num_points_center x num_patch_points x 2 + points_H = torch.clamp(patch_points_shifted[:, :, :, 0], min=0, max=H - 1).to(torch.long) + points_W = torch.clamp(patch_points_shifted[:, :, :, 1], min=0, max=W - 1).to(torch.long) + points = concatenate([points_H[..., None], points_W[..., None]], -1) + + # Sample the feature (N x 64 x 81) + sampled_feat = heatmap[points[:, :, :, 0], points[:, :, :, 1]] + # Filtering using the valid mask + sampled_feat = sampled_feat * patch_dist_mask.to(torch.float32) + if len(sampled_feat) == 0: + sampled_feat_lmax = torch.empty(0, self.num_samples) + else: + sampled_feat_lmax = torch.max(sampled_feat, dim=-1)[0] + + return sampled_feat_lmax + + +def line_map_to_segments(junctions: Tensor, line_map: Tensor) -> Tensor: + """Convert a junction connectivity map to a Nx2x2 tensor of segments.""" + junc_loc1, junc_loc2 = where(torch.triu(line_map)) + segments = stack([junctions[junc_loc1], junctions[junc_loc2]], 1) + return segments + + +def prob_to_junctions(prob: Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> Tensor: + """Extract junctions from a probability map, apply NMS, and extract the top k candidates.""" + # Extract the junctions + junctions = stack(where(prob >= prob_thresh), -1).float() + if len(junctions) == 0: + return junctions + + # Perform NMS + boxes = concatenate([junctions - dist / 2, junctions + dist / 2], 1) + scores = prob[prob >= prob_thresh] + remainings = nms(boxes, scores, 0.001) + junctions = junctions[remainings] + + # Keep only the topk values + if top_k > 0: + k = min(len(junctions), top_k) + junctions = junctions[:k] + + return junctions diff --git a/python_embeded/Lib/site-packages/kornia/feature/sold2/structures.py b/python_embeded/Lib/site-packages/kornia/feature/sold2/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..f725523fef4985445b49fd8834d9c66f9f4dbd86 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia/feature/sold2/structures.py @@ -0,0 +1,81 @@ +# 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. +# + +from dataclasses import dataclass, field + + +@dataclass +class HeatMapRefineCfg: + mode: str = "local" + ratio: float = 0.2 + valid_thresh: float = 0.001 + num_blocks: int = 20 + overlap_ratio: float = 0.5 + + +@dataclass +class JunctionRefineCfg: + num_perturbs: int = 9 + perturb_interval: float = 0.25 + + +@dataclass +class LineDetectorCfg: + detect_thresh: float = 0.5 + num_samples: int = 64 + inlier_thresh: float = 0.99 + use_candidate_suppression: bool = True + nms_dist_tolerance: float = 3.0 + heatmap_low_thresh: float = 0.15 + heatmap_high_thresh: float = 0.2 + max_local_patch_radius: float = 3 + lambda_radius: float = 2.0 + use_heatmap_refinement: bool = True + heatmap_refine_cfg: HeatMapRefineCfg = field(default_factory=HeatMapRefineCfg) + use_junction_refinement: bool = True + junction_refine_cfg: JunctionRefineCfg = field(default_factory=JunctionRefineCfg) + + +@dataclass +class LineMatcherCfg: + cross_check: bool = True + num_samples: int = 5 + min_dist_pts: int = 8 + top_k_candidates: int = 10 + grid_size: int = 4 + line_score: bool = False # True to compute saliency on a line + + +@dataclass +class BackboneCfg: + input_channel: int = 1 + depth: int = 4 + num_stacks: int = 2 + num_blocks: int = 1 + num_classes: int = 5 + + +@dataclass +class DetectorCfg: + backbone_cfg: BackboneCfg = field(default_factory=BackboneCfg) + use_descriptor: bool = False + grid_size: int = 8 + keep_border_valid: bool = True + detection_thresh: float = 0.0153846 # = 1/65: threshold of junction detection + max_num_junctions: int = 500 # maximum number of junctions per image + line_detector_cfg: LineDetectorCfg = field(default_factory=LineDetectorCfg) + line_matcher_cfg: LineMatcherCfg = field(default_factory=LineMatcherCfg) diff --git a/python_embeded/Lib/site-packages/kornia_rs-0.1.9.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/kornia_rs-0.1.9.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/python_embeded/Lib/site-packages/kornia_rs-0.1.9.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/__init__.py b/python_embeded/Lib/site-packages/lazy_loader/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.py b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..540fd731f20cc99ca8570cc4c4b2bf75a166797e --- /dev/null +++ b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.py @@ -0,0 +1,5 @@ +import lazy_loader as lazy + +__getattr__, __lazy_dir__, __all__ = lazy.attach( + __name__, submod_attrs={"some_func": ["some_func"]} +) diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.pyi b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d3349bb667ed72831d7b585cce512209cc533c07 --- /dev/null +++ b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/__init__.pyi @@ -0,0 +1 @@ +from .some_func import some_func diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/some_func.py b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/some_func.py new file mode 100644 index 0000000000000000000000000000000000000000..10e99ed0ab8be6458a54c62a9c2cf19a5f99145f --- /dev/null +++ b/python_embeded/Lib/site-packages/lazy_loader/tests/fake_pkg/some_func.py @@ -0,0 +1,3 @@ +def some_func(): + """Function with same name as submodule.""" + pass diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/import_np_parallel.py b/python_embeded/Lib/site-packages/lazy_loader/tests/import_np_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..50dc0d0081001613247d31162d69273b42a2c761 --- /dev/null +++ b/python_embeded/Lib/site-packages/lazy_loader/tests/import_np_parallel.py @@ -0,0 +1,13 @@ +import threading +import time + +import lazy_loader as lazy + + +def import_np(): + time.sleep(0.5) + lazy.load("numpy") + + +for _ in range(10): + threading.Thread(target=import_np).start() diff --git a/python_embeded/Lib/site-packages/lazy_loader/tests/test_lazy_loader.py b/python_embeded/Lib/site-packages/lazy_loader/tests/test_lazy_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..19187bab54b2ba6fa80741ab35d9b510886fe474 --- /dev/null +++ b/python_embeded/Lib/site-packages/lazy_loader/tests/test_lazy_loader.py @@ -0,0 +1,192 @@ +import importlib +import os +import subprocess +import sys +import types +from unittest import mock + +import pytest + +import lazy_loader as lazy + + +def test_lazy_import_basics(): + math = lazy.load("math") + anything_not_real = lazy.load("anything_not_real") + + # Now test that accessing attributes does what it should + assert math.sin(math.pi) == pytest.approx(0, 1e-6) + # poor-mans pytest.raises for testing errors on attribute access + try: + anything_not_real.pi + raise AssertionError() # Should not get here + except ModuleNotFoundError: + pass + assert isinstance(anything_not_real, lazy.DelayedImportErrorModule) + # see if it changes for second access + try: + anything_not_real.pi + raise AssertionError() # Should not get here + except ModuleNotFoundError: + pass + + +def test_lazy_import_subpackages(): + with pytest.warns(RuntimeWarning): + hp = lazy.load("html.parser") + assert "html" in sys.modules + assert type(sys.modules["html"]) == type(pytest) + assert isinstance(hp, importlib.util._LazyModule) + assert "html.parser" in sys.modules + assert sys.modules["html.parser"] == hp + + +def test_lazy_import_impact_on_sys_modules(): + math = lazy.load("math") + anything_not_real = lazy.load("anything_not_real") + + assert isinstance(math, types.ModuleType) + assert "math" in sys.modules + assert isinstance(anything_not_real, lazy.DelayedImportErrorModule) + assert "anything_not_real" not in sys.modules + + # only do this if numpy is installed + pytest.importorskip("numpy") + np = lazy.load("numpy") + assert isinstance(np, types.ModuleType) + assert "numpy" in sys.modules + + np.pi # trigger load of numpy + + assert isinstance(np, types.ModuleType) + assert "numpy" in sys.modules + + +def test_lazy_import_nonbuiltins(): + np = lazy.load("numpy") + sp = lazy.load("scipy") + if not isinstance(np, lazy.DelayedImportErrorModule): + assert np.sin(np.pi) == pytest.approx(0, 1e-6) + if isinstance(sp, lazy.DelayedImportErrorModule): + try: + sp.pi + raise AssertionError() + except ModuleNotFoundError: + pass + + +def test_lazy_attach(): + name = "mymod" + submods = ["mysubmodule", "anothersubmodule"] + myall = {"not_real_submod": ["some_var_or_func"]} + + locls = { + "attach": lazy.attach, + "name": name, + "submods": submods, + "myall": myall, + } + s = "__getattr__, __lazy_dir__, __all__ = attach(name, submods, myall)" + + exec(s, {}, locls) + expected = { + "attach": lazy.attach, + "name": name, + "submods": submods, + "myall": myall, + "__getattr__": None, + "__lazy_dir__": None, + "__all__": None, + } + assert locls.keys() == expected.keys() + for k, v in expected.items(): + if v is not None: + assert locls[k] == v + + +def test_attach_same_module_and_attr_name(): + from lazy_loader.tests import fake_pkg + + # Grab attribute twice, to ensure that importing it does not + # override function by module + assert isinstance(fake_pkg.some_func, types.FunctionType) + assert isinstance(fake_pkg.some_func, types.FunctionType) + + # Ensure imports from submodule still work + from lazy_loader.tests.fake_pkg.some_func import some_func + + assert isinstance(some_func, types.FunctionType) + + +FAKE_STUB = """ +from . import rank +from ._gaussian import gaussian +from .edges import sobel, scharr, prewitt, roberts +""" + + +def test_stub_loading(tmp_path): + stub = tmp_path / "stub.pyi" + stub.write_text(FAKE_STUB) + _get, _dir, _all = lazy.attach_stub("my_module", str(stub)) + expect = {"gaussian", "sobel", "scharr", "prewitt", "roberts", "rank"} + assert set(_dir()) == set(_all) == expect + + +def test_stub_loading_parity(): + from lazy_loader.tests import fake_pkg + + from_stub = lazy.attach_stub(fake_pkg.__name__, fake_pkg.__file__) + stub_getter, stub_dir, stub_all = from_stub + assert stub_all == fake_pkg.__all__ + assert stub_dir() == fake_pkg.__lazy_dir__() + assert stub_getter("some_func") == fake_pkg.some_func + + +def test_stub_loading_errors(tmp_path): + stub = tmp_path / "stub.pyi" + stub.write_text("from ..mod import func\n") + + with pytest.raises(ValueError, match="Only within-module imports are supported"): + lazy.attach_stub("name", str(stub)) + + with pytest.raises(ValueError, match="Cannot load imports from non-existent stub"): + lazy.attach_stub("name", "not a file") + + stub2 = tmp_path / "stub2.pyi" + stub2.write_text("from .mod import *\n") + with pytest.raises(ValueError, match=".*does not support star import"): + lazy.attach_stub("name", str(stub2)) + + +def test_require_kwarg(): + have_importlib_metadata = importlib.util.find_spec("importlib.metadata") is not None + dot = "." if have_importlib_metadata else "_" + # Test with a module that definitely exists, behavior hinges on requirement + with mock.patch(f"importlib{dot}metadata.version") as version: + version.return_value = "1.0.0" + math = lazy.load("math", require="somepkg >= 2.0") + assert isinstance(math, lazy.DelayedImportErrorModule) + + math = lazy.load("math", require="somepkg >= 1.0") + assert math.sin(math.pi) == pytest.approx(0, 1e-6) + + # We can fail even after a successful import + math = lazy.load("math", require="somepkg >= 2.0") + assert isinstance(math, lazy.DelayedImportErrorModule) + + # When a module can be loaded but the version can't be checked, + # raise a ValueError + with pytest.raises(ValueError): + lazy.load("math", require="somepkg >= 1.0") + + +def test_parallel_load(): + pytest.importorskip("numpy") + + subprocess.run( + [ + sys.executable, + os.path.join(os.path.dirname(__file__), "import_np_parallel.py"), + ] + ) diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/__init__.py b/python_embeded/Lib/site-packages/llvmlite/binding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69327b7e15f3820d1c8c78ce3cb584e9b87495a --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/__init__.py @@ -0,0 +1,19 @@ +""" +Things that rely on the LLVM library +""" +from .dylib import * +from .executionengine import * +from .initfini import * +from .linker import * +from .module import * +from .options import * +from .newpassmanagers import * +from .passmanagers import * +from .targets import * +from .transforms import * +from .value import * +from .typeref import * +from .analysis import * +from .object_file import * +from .context import * +from .orcjit import * diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/analysis.py b/python_embeded/Lib/site-packages/llvmlite/binding/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..8477b87f33697abb477952fb6fc32cffd1509855 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/analysis.py @@ -0,0 +1,69 @@ +""" +A collection of analysis utilities +""" + +from ctypes import POINTER, c_char_p, c_int + +from llvmlite.binding import ffi +from llvmlite.binding.module import parse_assembly + + +def get_function_cfg(func, show_inst=True): + """Return a string of the control-flow graph of the function in DOT + format. If the input `func` is not a materialized function, the module + containing the function is parsed to create an actual LLVM module. + The `show_inst` flag controls whether the instructions of each block + are printed. + """ + assert func is not None + from llvmlite import ir + if isinstance(func, ir.Function): + mod = parse_assembly(str(func.module)) + func = mod.get_function(func.name) + + # Assume func is a materialized function + with ffi.OutputString() as dotstr: + ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst) + return str(dotstr) + + +def view_dot_graph(graph, filename=None, view=False): + """ + View the given DOT source. If view is True, the image is rendered + and viewed by the default application in the system. The file path of + the output is returned. If view is False, a graphviz.Source object is + returned. If view is False and the environment is in a IPython session, + an IPython image object is returned and can be displayed inline in the + notebook. + + This function requires the graphviz package. + + Args + ---- + - graph [str]: a DOT source code + - filename [str]: optional. if given and view is True, this specifies + the file path for the rendered output to write to. + - view [bool]: if True, opens the rendered output file. + + """ + # Optionally depends on graphviz package + import graphviz as gv + + src = gv.Source(graph) + if view: + # Returns the output file path + return src.render(filename, view=view) + else: + # Attempts to show the graph in IPython notebook + try: + __IPYTHON__ + except NameError: + return src + else: + import IPython.display as display + format = 'svg' + return display.SVG(data=src.pipe(format)) + + +# Ctypes binding +ffi.lib.LLVMPY_WriteCFG.argtypes = [ffi.LLVMValueRef, POINTER(c_char_p), c_int] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/common.py b/python_embeded/Lib/site-packages/llvmlite/binding/common.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2334bb7137589f5e5d19820aa30298b34df2ca --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/common.py @@ -0,0 +1,34 @@ +import atexit + + +def _encode_string(s): + encoded = s.encode('utf-8') + return encoded + + +def _decode_string(b): + return b.decode('utf-8') + + +_encode_string.__doc__ = """Encode a string for use by LLVM.""" +_decode_string.__doc__ = """Decode a LLVM character (byte)string.""" + + +_shutting_down = [False] + + +def _at_shutdown(): + _shutting_down[0] = True + + +atexit.register(_at_shutdown) + + +def _is_shutting_down(_shutting_down=_shutting_down): + """ + Whether the interpreter is currently shutting down. + For use in finalizers, __del__ methods, and similar; it is advised + to early bind this function rather than look it up when calling it, + since at shutdown module globals may be cleared. + """ + return _shutting_down[0] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/context.py b/python_embeded/Lib/site-packages/llvmlite/binding/context.py new file mode 100644 index 0000000000000000000000000000000000000000..12b7a05e21b79cc8577617d5141a94bddd3a66ad --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/context.py @@ -0,0 +1,39 @@ +from llvmlite.binding import ffi + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled +from ctypes import c_bool + + +def create_context(): + return ContextRef( + ffi.lib.LLVMPY_ContextCreate(opaque_pointers_enabled)) + + +def get_global_context(): + return GlobalContextRef( + ffi.lib.LLVMPY_GetGlobalContext(opaque_pointers_enabled)) + + +class ContextRef(ffi.ObjectRef): + def __init__(self, context_ptr): + super(ContextRef, self).__init__(context_ptr) + + def _dispose(self): + ffi.lib.LLVMPY_ContextDispose(self) + + +class GlobalContextRef(ContextRef): + def _dispose(self): + pass + + +# FIXME: Remove argtypes once typed pointers are no longer supported. +ffi.lib.LLVMPY_GetGlobalContext.argtypes = [c_bool] +ffi.lib.LLVMPY_GetGlobalContext.restype = ffi.LLVMContextRef + +# FIXME: Remove argtypes once typed pointers are no longer supported. +ffi.lib.LLVMPY_ContextCreate.argtypes = [c_bool] +ffi.lib.LLVMPY_ContextCreate.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextDispose.argtypes = [ffi.LLVMContextRef] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/dylib.py b/python_embeded/Lib/site-packages/llvmlite/binding/dylib.py new file mode 100644 index 0000000000000000000000000000000000000000..c9443b38e47a67ce3558ad4bec49b0d6123a8f0d --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/dylib.py @@ -0,0 +1,45 @@ +from ctypes import c_void_p, c_char_p, c_bool, POINTER + +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string + + +def address_of_symbol(name): + """ + Get the in-process address of symbol named *name*. + An integer is returned, or None if the symbol isn't found. + """ + return ffi.lib.LLVMPY_SearchAddressOfSymbol(_encode_string(name)) + + +def add_symbol(name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + ffi.lib.LLVMPY_AddSymbol(_encode_string(name), c_void_p(address)) + + +def load_library_permanently(filename): + """ + Load an external library + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_LoadLibraryPermanently( + _encode_string(filename), outerr): + raise RuntimeError(str(outerr)) + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_AddSymbol.argtypes = [ + c_char_p, + c_void_p, +] + +ffi.lib.LLVMPY_SearchAddressOfSymbol.argtypes = [c_char_p] +ffi.lib.LLVMPY_SearchAddressOfSymbol.restype = c_void_p + +ffi.lib.LLVMPY_LoadLibraryPermanently.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_LoadLibraryPermanently.restype = c_bool diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/executionengine.py b/python_embeded/Lib/site-packages/llvmlite/binding/executionengine.py new file mode 100644 index 0000000000000000000000000000000000000000..68be0de4633cc3457903b2495bd9939a82efafd2 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/executionengine.py @@ -0,0 +1,330 @@ +import platform +from ctypes import (POINTER, c_char_p, c_bool, c_void_p, + c_int, c_uint64, c_size_t, CFUNCTYPE, string_at, cast, + py_object, Structure) + +from llvmlite.binding import ffi, targets, object_file + + +# Just check these weren't optimized out of the DLL. +ffi.lib.LLVMPY_LinkInMCJIT + + +def create_mcjit_compiler(module, target_machine, use_lmm=None): + """ + Create a MCJIT ExecutionEngine from the given *module* and + *target_machine*. + + *lmm* controls whether the llvmlite memory manager is used. If not supplied, + the default choice for the platform will be used (``True`` on 64-bit ARM + systems, ``False`` otherwise). + """ + if use_lmm is None: + use_lmm = platform.machine() in ('arm64', 'aarch64') + + with ffi.OutputString() as outerr: + engine = ffi.lib.LLVMPY_CreateMCJITCompiler( + module, target_machine, use_lmm, outerr) + if not engine: + raise RuntimeError(str(outerr)) + + target_machine._owned = True + return ExecutionEngine(engine, module=module) + + +def check_jit_execution(): + """ + Check the system allows execution of in-memory JITted functions. + An exception is raised otherwise. + """ + errno = ffi.lib.LLVMPY_TryAllocateExecutableMemory() + if errno != 0: + raise OSError(errno, + "cannot allocate executable memory. " + "This may be due to security restrictions on your " + "system, such as SELinux or similar mechanisms." + ) + + +class ExecutionEngine(ffi.ObjectRef): + """An ExecutionEngine owns all Modules associated with it. + Deleting the engine will remove all associated modules. + It is an error to delete the associated modules. + """ + _object_cache = None + + def __init__(self, ptr, module): + """ + Module ownership is transferred to the EE + """ + self._modules = set([module]) + self._td = None + module._owned = True + ffi.ObjectRef.__init__(self, ptr) + + def get_function_address(self, name): + """ + Return the address of the function named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii")) + + def get_global_value_address(self, name): + """ + Return the address of the global value named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetGlobalValueAddress(self, name.encode("ascii")) + + def add_global_mapping(self, gv, addr): + ffi.lib.LLVMPY_AddGlobalMapping(self, gv, addr) + + def add_module(self, module): + """ + Ownership of module is transferred to the execution engine + """ + if module in self._modules: + raise KeyError("module already added to this engine") + ffi.lib.LLVMPY_AddModule(self, module) + module._owned = True + self._modules.add(module) + + def finalize_object(self): + """ + Make sure all modules owned by the execution engine are fully processed + and "usable" for execution. + """ + ffi.lib.LLVMPY_FinalizeObject(self) + + def run_static_constructors(self): + """ + Run static constructors which initialize module-level static objects. + """ + ffi.lib.LLVMPY_RunStaticConstructors(self) + + def run_static_destructors(self): + """ + Run static destructors which perform module-level cleanup of static + resources. + """ + ffi.lib.LLVMPY_RunStaticDestructors(self) + + def remove_module(self, module): + """ + Ownership of module is returned + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_RemoveModule(self, module, outerr): + raise RuntimeError(str(outerr)) + self._modules.remove(module) + module._owned = False + + @property + def target_data(self): + """ + The TargetData for this execution engine. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def enable_jit_events(self): + """ + Enable JIT events for profiling of generated code. + Return value indicates whether connection to profiling tool + was successful. + """ + ret = ffi.lib.LLVMPY_EnableJITEvents(self) + return ret + + def _find_module_ptr(self, module_ptr): + """ + Find the ModuleRef corresponding to the given pointer. + """ + ptr = cast(module_ptr, c_void_p).value + for module in self._modules: + if cast(module._ptr, c_void_p).value == ptr: + return module + return None + + def add_object_file(self, obj_file): + """ + Add object file to the jit. object_file can be instance of + :class:ObjectFile or a string representing file system path + """ + if isinstance(obj_file, str): + obj_file = object_file.ObjectFileRef.from_path(obj_file) + + ffi.lib.LLVMPY_MCJITAddObjectFile(self, obj_file) + + def set_object_cache(self, notify_func=None, getbuffer_func=None): + """ + Set the object cache "notifyObjectCompiled" and "getBuffer" + callbacks to the given Python functions. + """ + self._object_cache_notify = notify_func + self._object_cache_getbuffer = getbuffer_func + # Lifetime of the object cache is managed by us. + self._object_cache = _ObjectCacheRef(self) + # Note this doesn't keep a reference to self, to avoid reference + # cycles. + ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache) + + def _raw_object_cache_notify(self, data): + """ + Low-level notify hook. + """ + if self._object_cache_notify is None: + return + module_ptr = data.contents.module_ptr + buf_ptr = data.contents.buf_ptr + buf_len = data.contents.buf_len + buf = string_at(buf_ptr, buf_len) + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + self._object_cache_notify(module, buf) + + def _raw_object_cache_getbuffer(self, data): + """ + Low-level getbuffer hook. + """ + if self._object_cache_getbuffer is None: + return + module_ptr = data.contents.module_ptr + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + + buf = self._object_cache_getbuffer(module) + if buf is not None: + # Create a copy, which will be freed by the caller + data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf)) + data[0].buf_len = len(buf) + + def _dispose(self): + # The modules will be cleaned up by the EE + for mod in self._modules: + mod.detach() + if self._td is not None: + self._td.detach() + self._modules.clear() + self._object_cache = None + self._capi.LLVMPY_DisposeExecutionEngine(self) + + +class _ObjectCacheRef(ffi.ObjectRef): + """ + Internal: an ObjectCache instance for use within an ExecutionEngine. + """ + + def __init__(self, obj): + ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook, + _getbuffer_c_hook, + obj) + ffi.ObjectRef.__init__(self, ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeObjectCache(self) + + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_CreateMCJITCompiler.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMTargetMachineRef, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateMCJITCompiler.restype = ffi.LLVMExecutionEngineRef + +ffi.lib.LLVMPY_RemoveModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_RemoveModule.restype = c_bool + +ffi.lib.LLVMPY_AddModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef +] + +ffi.lib.LLVMPY_AddGlobalMapping.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMValueRef, + c_void_p] + +ffi.lib.LLVMPY_FinalizeObject.argtypes = [ffi.LLVMExecutionEngineRef] + +ffi.lib.LLVMPY_GetExecutionEngineTargetData.argtypes = [ + ffi.LLVMExecutionEngineRef +] +ffi.lib.LLVMPY_GetExecutionEngineTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_TryAllocateExecutableMemory.argtypes = [] +ffi.lib.LLVMPY_TryAllocateExecutableMemory.restype = c_int + +ffi.lib.LLVMPY_GetFunctionAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetFunctionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetGlobalValueAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetGlobalValueAddress.restype = c_uint64 + +ffi.lib.LLVMPY_MCJITAddObjectFile.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectFileRef +] + + +class _ObjectCacheData(Structure): + _fields_ = [ + ('module_ptr', ffi.LLVMModuleRef), + ('buf_ptr', c_void_p), + ('buf_len', c_size_t), + ] + + +_ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) +_ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) + +# XXX The ctypes function wrappers are created at the top-level, otherwise +# there are issues when creating CFUNCTYPEs in child processes on CentOS 5 +# 32 bits. +_notify_c_hook = _ObjectCacheNotifyFunc( + ExecutionEngine._raw_object_cache_notify) +_getbuffer_c_hook = _ObjectCacheGetBufferFunc( + ExecutionEngine._raw_object_cache_getbuffer) + +ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc, + _ObjectCacheGetBufferFunc, + py_object] +ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef + +ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_CreateByteString.restype = c_void_p +ffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/ffi.py b/python_embeded/Lib/site-packages/llvmlite/binding/ffi.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3320af73cb5c12d7e6f57842cf6a4f83a9b967 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/ffi.py @@ -0,0 +1,395 @@ +import sys +import ctypes +import threading +import importlib.resources as _impres + +from llvmlite.binding.common import _decode_string, _is_shutting_down +from llvmlite.utils import get_library_name + + +def _make_opaque_ref(name): + newcls = type(name, (ctypes.Structure,), {}) + return ctypes.POINTER(newcls) + + +LLVMContextRef = _make_opaque_ref("LLVMContext") +LLVMModuleRef = _make_opaque_ref("LLVMModule") +LLVMValueRef = _make_opaque_ref("LLVMValue") +LLVMTypeRef = _make_opaque_ref("LLVMType") +LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine") +LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder") +LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager") +LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData") +LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo") +LLVMTargetRef = _make_opaque_ref("LLVMTarget") +LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine") +LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer") +LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator") +LLVMElementIterator = _make_opaque_ref("LLVMElementIterator") +LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator") +LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator") +LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator") +LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator") +LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator") +LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator") +LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator") +LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator") +LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator") +LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache") +LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile") +LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator") +LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef") +LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef") + +LLVMPipelineTuningOptionsRef = _make_opaque_ref("LLVMPipeLineTuningOptions") +LLVMModulePassManagerRef = _make_opaque_ref("LLVMModulePassManager") +LLVMFunctionPassManagerRef = _make_opaque_ref("LLVMFunctionPassManager") +LLVMPassBuilderRef = _make_opaque_ref("LLVMPassBuilder") + + +class _LLVMLock: + """A Lock to guarantee thread-safety for the LLVM C-API. + + This class implements __enter__ and __exit__ for acquiring and releasing + the lock as a context manager. + + Also, callbacks can be attached so that every time the lock is acquired + and released the corresponding callbacks will be invoked. + """ + def __init__(self): + # The reentrant lock is needed for callbacks that re-enter + # the Python interpreter. + self._lock = threading.RLock() + self._cblist = [] + + def register(self, acq_fn, rel_fn): + """Register callbacks that are invoked immediately after the lock is + acquired (``acq_fn()``) and immediately before the lock is released + (``rel_fn()``). + """ + self._cblist.append((acq_fn, rel_fn)) + + def unregister(self, acq_fn, rel_fn): + """Remove the registered callbacks. + """ + self._cblist.remove((acq_fn, rel_fn)) + + def __enter__(self): + self._lock.acquire() + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + acq_fn() + + def __exit__(self, *exc_details): + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + rel_fn() + self._lock.release() + + +class _suppress_cleanup_errors: + def __init__(self, context): + self._context = context + + def __enter__(self): + return self._context.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + try: + return self._context.__exit__(exc_type, exc_value, traceback) + except PermissionError: + pass # Resource dylibs can't be deleted on Windows. + + +class _lib_wrapper(object): + """Wrap libllvmlite with a lock such that only one thread may access it at + a time. + + This class duck-types a CDLL. + """ + __slots__ = ['_lib_handle', '_fntab', '_lock'] + + def __init__(self): + self._lib_handle = None + self._fntab = {} + self._lock = _LLVMLock() + + def _load_lib(self): + try: + with _suppress_cleanup_errors(_importlib_resources_path( + __name__.rpartition(".")[0], + get_library_name())) as lib_path: + self._lib_handle = ctypes.CDLL(str(lib_path)) + # Check that we can look up expected symbols. + _ = self._lib_handle.LLVMPY_GetVersionInfo() + except (OSError, AttributeError) as e: + # OSError may be raised if the file cannot be opened, or is not + # a shared library. + # AttributeError is raised if LLVMPY_GetVersionInfo does not + # exist. + raise OSError("Could not find/load shared object file") from e + + @property + def _lib(self): + # Not threadsafe. + if not self._lib_handle: + self._load_lib() + return self._lib_handle + + def __getattr__(self, name): + try: + return self._fntab[name] + except KeyError: + # Lazily wraps new functions as they are requested + cfn = getattr(self._lib, name) + wrapped = _lib_fn_wrapper(self._lock, cfn) + self._fntab[name] = wrapped + return wrapped + + @property + def _name(self): + """The name of the library passed in the CDLL constructor. + + For duck-typing a ctypes.CDLL + """ + return self._lib._name + + @property + def _handle(self): + """The system handle used to access the library. + + For duck-typing a ctypes.CDLL + """ + return self._lib._handle + + +class _lib_fn_wrapper(object): + """Wraps and duck-types a ctypes.CFUNCTYPE to provide + automatic locking when the wrapped function is called. + + TODO: we can add methods to mark the function as threadsafe + and remove the locking-step on call when marked. + """ + __slots__ = ['_lock', '_cfn'] + + def __init__(self, lock, cfn): + self._lock = lock + self._cfn = cfn + + @property + def argtypes(self): + return self._cfn.argtypes + + @argtypes.setter + def argtypes(self, argtypes): + self._cfn.argtypes = argtypes + + @property + def restype(self): + return self._cfn.restype + + @restype.setter + def restype(self, restype): + self._cfn.restype = restype + + def __call__(self, *args, **kwargs): + with self._lock: + return self._cfn(*args, **kwargs) + + +def _importlib_resources_path_repl(package, resource): + """Replacement implementation of `import.resources.path` to avoid + deprecation warning following code at importlib_resources/_legacy.py + as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy + + Notes on differences from importlib.resources implementation: + + The `_common.normalize_path(resource)` call is skipped because it is an + internal API and it is unnecessary for the use here. What it does is + ensuring `resource` is a str and that it does not contain path separators. + """ # noqa E501 + return _impres.as_file(_impres.files(package) / resource) + + +_importlib_resources_path = (_importlib_resources_path_repl + if sys.version_info[:2] >= (3, 10) + else _impres.path) + + +lib = _lib_wrapper() + + +def register_lock_callback(acq_fn, rel_fn): + """Register callback functions for lock acquire and release. + *acq_fn* and *rel_fn* are callables that take no arguments. + """ + lib._lock.register(acq_fn, rel_fn) + + +def unregister_lock_callback(acq_fn, rel_fn): + """Remove the registered callback functions for lock acquire and release. + The arguments are the same as used in `register_lock_callback()`. + """ + lib._lock.unregister(acq_fn, rel_fn) + + +class _DeadPointer(object): + """ + Dummy class to make error messages more helpful. + """ + + +class OutputString(object): + """ + Object for managing the char* output of LLVM APIs. + """ + _as_parameter_ = _DeadPointer() + + @classmethod + def from_return(cls, ptr): + """Constructing from a pointer returned from the C-API. + The pointer must be allocated with LLVMPY_CreateString. + + Note + ---- + Because ctypes auto-converts *restype* of *c_char_p* into a python + string, we must use *c_void_p* to obtain the raw pointer. + """ + return cls(init=ctypes.cast(ptr, ctypes.c_char_p)) + + def __init__(self, owned=True, init=None): + self._ptr = init if init is not None else ctypes.c_char_p(None) + self._as_parameter_ = ctypes.byref(self._ptr) + self._owned = owned + + def close(self): + if self._ptr is not None: + if self._owned: + lib.LLVMPY_DisposeString(self._ptr) + self._ptr = None + del self._as_parameter_ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + # Avoid errors trying to rely on globals and modules at interpreter + # shutdown. + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __str__(self): + if self._ptr is None: + return "" + s = self._ptr.value + assert s is not None + return _decode_string(s) + + def __bool__(self): + return bool(self._ptr) + + __nonzero__ = __bool__ + + @property + def bytes(self): + """Get the raw bytes of content of the char pointer. + """ + return self._ptr.value + + +def ret_string(ptr): + """To wrap string return-value from C-API. + """ + if ptr is not None: + return str(OutputString.from_return(ptr)) + + +def ret_bytes(ptr): + """To wrap bytes return-value from C-API. + """ + if ptr is not None: + return OutputString.from_return(ptr).bytes + + +class ObjectRef(object): + """ + A wrapper around a ctypes pointer to a LLVM object ("resource"). + """ + _closed = False + _as_parameter_ = _DeadPointer() + # Whether this object pointer is owned by another one. + _owned = False + + def __init__(self, ptr): + if ptr is None: + raise ValueError("NULL pointer") + self._ptr = ptr + self._as_parameter_ = ptr + self._capi = lib + + def close(self): + """ + Close this object and do any required clean-up actions. + """ + try: + if not self._closed and not self._owned: + self._dispose() + finally: + self.detach() + + def detach(self): + """ + Detach the underlying LLVM resource without disposing of it. + """ + if not self._closed: + del self._as_parameter_ + self._closed = True + self._ptr = None + + def _dispose(self): + """ + Dispose of the underlying LLVM resource. Should be overriden + by subclasses. Automatically called by close(), __del__() and + __exit__() (unless the resource has been detached). + """ + + @property + def closed(self): + """ + Whether this object has been closed. A closed object can't + be used anymore. + """ + return self._closed + + def __enter__(self): + assert hasattr(self, "close") + if self._closed: + raise RuntimeError("%s instance already closed" % (self.__class__,)) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __bool__(self): + return bool(self._ptr) + + def __eq__(self, other): + if not hasattr(other, "_ptr"): + return False + return ctypes.addressof(self._ptr[0]) == \ + ctypes.addressof(other._ptr[0]) + + __nonzero__ = __bool__ + + # XXX useful? + def __hash__(self): + return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value) diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/initfini.py b/python_embeded/Lib/site-packages/llvmlite/binding/initfini.py new file mode 100644 index 0000000000000000000000000000000000000000..42c03dfc0626865f8fc7361715a02aa7c0407a56 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/initfini.py @@ -0,0 +1,73 @@ +from ctypes import c_uint + +from llvmlite.binding import ffi + + +def initialize(): + """ + Initialize the LLVM core. + """ + ffi.lib.LLVMPY_InitializeCore() + + +def initialize_all_targets(): + """ + Initialize all targets. Necessary before targets can be looked up + via the :class:`Target` class. + """ + ffi.lib.LLVMPY_InitializeAllTargetInfos() + ffi.lib.LLVMPY_InitializeAllTargets() + ffi.lib.LLVMPY_InitializeAllTargetMCs() + + +def initialize_all_asmprinters(): + """ + Initialize all code generators. Necessary before generating + any assembly or machine code via the :meth:`TargetMachine.emit_object` + and :meth:`TargetMachine.emit_assembly` methods. + """ + ffi.lib.LLVMPY_InitializeAllAsmPrinters() + + +def initialize_native_target(): + """ + Initialize the native (host) target. Necessary before doing any + code generation. + """ + ffi.lib.LLVMPY_InitializeNativeTarget() + + +def initialize_native_asmprinter(): + """ + Initialize the native ASM printer. + """ + ffi.lib.LLVMPY_InitializeNativeAsmPrinter() + + +def initialize_native_asmparser(): + """ + Initialize the native ASM parser. + """ + ffi.lib.LLVMPY_InitializeNativeAsmParser() + + +def shutdown(): + ffi.lib.LLVMPY_Shutdown() + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_GetVersionInfo.restype = c_uint + + +def _version_info(): + v = [] + x = ffi.lib.LLVMPY_GetVersionInfo() + while x: + v.append(x & 0xff) + x >>= 8 + return tuple(reversed(v)) + + +llvm_version_info = _version_info() diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/linker.py b/python_embeded/Lib/site-packages/llvmlite/binding/linker.py new file mode 100644 index 0000000000000000000000000000000000000000..33c6bfa44e0ac87f338141a2b35bd9d595456f70 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/linker.py @@ -0,0 +1,20 @@ +from ctypes import c_int, c_char_p, POINTER +from llvmlite.binding import ffi + + +def link_modules(dst, src): + with ffi.OutputString() as outerr: + err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) + # The underlying module was destroyed + src.detach() + if err: + raise RuntimeError(str(outerr)) + + +ffi.lib.LLVMPY_LinkModules.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_LinkModules.restype = c_int diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/module.py b/python_embeded/Lib/site-packages/llvmlite/binding/module.py new file mode 100644 index 0000000000000000000000000000000000000000..7998b9825df408faef94f8bf9fa830e96ed05311 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/module.py @@ -0,0 +1,349 @@ +from ctypes import (c_char_p, byref, POINTER, c_bool, create_string_buffer, + c_size_t, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.linker import link_modules +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.value import ValueRef, TypeRef +from llvmlite.binding.context import get_global_context + + +def parse_assembly(llvmir, context=None): + """ + Create Module from a LLVM IR string + """ + if context is None: + context = get_global_context() + llvmir = _encode_string(llvmir) + strbuf = c_char_p(llvmir) + with ffi.OutputString() as errmsg: + mod = ModuleRef( + ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), + context) + if errmsg: + mod.close() + raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) + return mod + + +def parse_bitcode(bitcode, context=None): + """ + Create Module from a LLVM *bitcode* (a bytes object). + """ + if context is None: + context = get_global_context() + buf = c_char_p(bitcode) + bufsize = len(bitcode) + with ffi.OutputString() as errmsg: + mod = ModuleRef(ffi.lib.LLVMPY_ParseBitcode( + context, buf, bufsize, errmsg), context) + if errmsg: + mod.close() + raise RuntimeError( + "LLVM bitcode parsing error\n{0}".format(errmsg)) + return mod + + +class ModuleRef(ffi.ObjectRef): + """ + A reference to a LLVM module. + """ + + def __init__(self, module_ptr, context): + super(ModuleRef, self).__init__(module_ptr) + self._context = context + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintModuleToString(self, outstr) + return str(outstr) + + def as_bitcode(self): + """ + Return the module's LLVM bitcode, as a bytes object. + """ + ptr = c_char_p(None) + size = c_size_t(-1) + ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) + if not ptr: + raise MemoryError + try: + assert size.value >= 0 + return string_at(ptr, size.value) + finally: + ffi.lib.LLVMPY_DisposeString(ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeModule(self) + + def get_function(self, name): + """ + Get a ValueRef pointing to the function named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'function', dict(module=self)) + + def get_global_variable(self, name): + """ + Get a ValueRef pointing to the global variable named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedGlobalVariable(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'global', dict(module=self)) + + def get_struct_type(self, name): + """ + Get a TypeRef pointing to a structure type named *name*. + NameError is raised if the struct type isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name)) + if not p: + raise NameError(name) + return TypeRef(p) + + def verify(self): + """ + Verify the module IR's correctness. RuntimeError is raised on error. + """ + with ffi.OutputString() as outmsg: + if ffi.lib.LLVMPY_VerifyModule(self, outmsg): + raise RuntimeError(str(outmsg)) + + @property + def name(self): + """ + The module's identifier. + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleName(self)) + + @name.setter + def name(self, value): + ffi.lib.LLVMPY_SetModuleName(self, _encode_string(value)) + + @property + def source_file(self): + """ + The module's original source file name + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleSourceFileName(self)) + + @property + def data_layout(self): + """ + This module's data layout specification, as a string. + """ + # LLVMGetDataLayout() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetDataLayout(self, outmsg) + return str(outmsg) + + @data_layout.setter + def data_layout(self, strrep): + ffi.lib.LLVMPY_SetDataLayout(self, + create_string_buffer( + strrep.encode('utf8'))) + + @property + def triple(self): + """ + This module's target "triple" specification, as a string. + """ + # LLVMGetTarget() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetTarget(self, outmsg) + return str(outmsg) + + @triple.setter + def triple(self, strrep): + ffi.lib.LLVMPY_SetTarget(self, + create_string_buffer( + strrep.encode('utf8'))) + + def link_in(self, other, preserve=False): + """ + Link the *other* module into this one. The *other* module will + be destroyed unless *preserve* is true. + """ + if preserve: + other = other.clone() + link_modules(self, other) + + @property + def global_variables(self): + """ + Return an iterator over this module's global variables. + The iterator will yield a ValueRef for each global variable. + + Note that global variables don't include functions + (a function is a "global value" but not a "global variable" in + LLVM parlance) + """ + it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) + return _GlobalsIterator(it, dict(module=self)) + + @property + def functions(self): + """ + Return an iterator over this module's functions. + The iterator will yield a ValueRef for each function. + """ + it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) + return _FunctionsIterator(it, dict(module=self)) + + @property + def struct_types(self): + """ + Return an iterator over the struct types defined in + the module. The iterator will yield a TypeRef. + """ + it = ffi.lib.LLVMPY_ModuleTypesIter(self) + return _TypesIterator(it, dict(module=self)) + + def clone(self): + return ModuleRef(ffi.lib.LLVMPY_CloneModule(self), self._context) + + +class _Iterator(ffi.ObjectRef): + + kind = None + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + self._parents = parents + assert self.kind is not None + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _GlobalsIterator(_Iterator): + + kind = 'global' + + def _dispose(self): + self._capi.LLVMPY_DisposeGlobalsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_GlobalsIterNext(self) + + +class _FunctionsIterator(_Iterator): + + kind = 'function' + + def _dispose(self): + self._capi.LLVMPY_DisposeFunctionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_FunctionsIterNext(self) + + +class _TypesIterator(_Iterator): + + kind = 'type' + + def _dispose(self): + self._capi.LLVMPY_DisposeTypesIter(self) + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + def _next(self): + return ffi.lib.LLVMPY_TypesIterNext(self) + + next = __next__ + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef, + c_char_p, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef, + c_char_p, c_size_t, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef] + +ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p), + POINTER(c_size_t)] + +ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef, + c_char_p] +ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_VerifyModule.restype = c_bool + +ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator + +ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator] + +ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator] +ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator + +ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator + +ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator] + +ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator] + +ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator] +ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator] +ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleName.restype = c_char_p + +ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/newpassmanagers.py b/python_embeded/Lib/site-packages/llvmlite/binding/newpassmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a1493ede3796c2be0088779121e93a2988d941 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/newpassmanagers.py @@ -0,0 +1,357 @@ +from ctypes import c_bool, c_int, c_size_t +from enum import IntFlag +from llvmlite.binding import ffi + + +def create_new_module_pass_manager(): + return ModulePassManager() + + +def create_new_function_pass_manager(): + return FunctionPassManager() + + +def create_pass_builder(tm, pto): + return PassBuilder(tm, pto) + + +def create_pipeline_tuning_options(speed_level=2, size_level=0): + return PipelineTuningOptions(speed_level, size_level) + + +class RefPruneSubpasses(IntFlag): + PER_BB = 0b0001 # noqa: E221 + DIAMOND = 0b0010 # noqa: E221 + FANOUT = 0b0100 # noqa: E221 + FANOUT_RAISE = 0b1000 + ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE + + +class ModulePassManager(ffi.ObjectRef): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewModulePassManager() + super().__init__(ptr) + + def run(self, module, pb): + ffi.lib.LLVMPY_RunNewModulePassManager(self, module, pb) + + def add_verifier(self): + ffi.lib.LLVMPY_AddVerifierPass(self) + + def add_aa_eval_pass(self): + ffi.lib.LLVMPY_AddAAEvalPass_module(self) + + def add_simplify_cfg_pass(self): + ffi.lib.LLVMPY_AddSimplifyCFGPass_module(self) + + def add_loop_unroll_pass(self): + ffi.lib.LLVMPY_AddLoopUnrollPass_module(self) + + def add_loop_rotate_pass(self): + ffi.lib.LLVMPY_AddLoopRotatePass_module(self) + + def add_instruction_combine_pass(self): + ffi.lib.LLVMPY_AddInstructionCombinePass_module(self) + + def add_jump_threading_pass(self, threshold=-1): + ffi.lib.LLVMPY_AddJumpThreadingPass_module(self, threshold) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeNewModulePassManger(self) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_module(self, iflags, subgraph_limit) + + +class FunctionPassManager(ffi.ObjectRef): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewFunctionPassManager() + super().__init__(ptr) + + def run(self, fun, pb): + ffi.lib.LLVMPY_RunNewFunctionPassManager(self, fun, pb) + + def add_aa_eval_pass(self): + ffi.lib.LLVMPY_AddAAEvalPass_function(self) + + def add_simplify_cfg_pass(self): + ffi.lib.LLVMPY_AddSimplifyCFGPass_function(self) + + def add_loop_unroll_pass(self): + ffi.lib.LLVMPY_AddLoopUnrollPass_function(self) + + def add_loop_rotate_pass(self): + ffi.lib.LLVMPY_AddLoopRotatePass_function(self) + + def add_instruction_combine_pass(self): + ffi.lib.LLVMPY_AddInstructionCombinePass_function(self) + + def add_jump_threading_pass(self, threshold=-1): + ffi.lib.LLVMPY_AddJumpThreadingPass_function(self, threshold) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeNewFunctionPassManger(self) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_function(self, iflags, subgraph_limit) + + +class PipelineTuningOptions(ffi.ObjectRef): + + def __init__(self, speed_level=2, size_level=0): + self._speed_level = None + self._size_level = None + self.speed_level = speed_level + self.size_level = size_level + super().__init__(ffi.lib.LLVMPY_CreatePipelineTuningOptions()) + + @property + def speed_level(self): + return self._speed_level + + @speed_level.setter + def speed_level(self, value): + if not 0 <= value <= 3: + raise ValueError( + "Optimization level for speed should be 0, 1, 2, or 3") + self._speed_level = value + + @property + def size_level(self): + return self._size_level + + @size_level.setter + def size_level(self, value): + if not 0 <= value <= 2: + raise ValueError("Optimization level for size should be 0, 1, or 2") + if value != 0 and self.speed_level != 2: + raise ValueError( + "Optimization for size should be encoded with speed level == 2") + self._size_level = value + + @property + def loop_interleaving(self): + return ffi.lib.LLVMPY_PTOGetLoopInterleaving(self) + + @loop_interleaving.setter + def loop_interleaving(self, value): + ffi.lib.LLVMPY_PTOSetLoopInterleaving(self, value) + + @property + def loop_vectorization(self): + return ffi.lib.LLVMPY_PTOGetLoopVectorization(self) + + @loop_vectorization.setter + def loop_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetLoopVectorization(self, value) + + @property + def slp_vectorization(self): + return ffi.lib.LLVMPY_PTOGetSLPVectorization(self) + + @slp_vectorization.setter + def slp_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetSLPVectorization(self, value) + + @property + def loop_unrolling(self): + return ffi.lib.LLVMPY_PTOGetLoopUnrolling(self) + + @loop_unrolling.setter + def loop_unrolling(self, value): + ffi.lib.LLVMPY_PTOSetLoopUnrolling(self, value) + + # // FIXME: Available from llvm16 + # @property + # def inlining_threshold(self): + # return ffi.lib.LLVMPY_PTOGetInlinerThreshold(self) + + # @inlining_threshold.setter + # def inlining_threshold(self, value): + # ffi.lib.LLVMPY_PTOSetInlinerThreshold(self, value) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePipelineTuningOptions(self) + + +class PassBuilder(ffi.ObjectRef): + + def __init__(self, tm, pto): + super().__init__(ffi.lib.LLVMPY_CreatePassBuilder(tm, pto)) + self._pto = pto + self._tm = tm + + def getModulePassManager(self): + return ModulePassManager( + ffi.lib.LLVMPY_buildPerModuleDefaultPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def getFunctionPassManager(self): + return FunctionPassManager( + ffi.lib.LLVMPY_buildFunctionSimplificationPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePassBuilder(self) + + +# ============================================================================ +# FFI + +# ModulePassManager + +ffi.lib.LLVMPY_CreateNewModulePassManager.restype = ffi.LLVMModulePassManagerRef + +ffi.lib.LLVMPY_RunNewModulePassManager.argtypes = [ + ffi.LLVMModulePassManagerRef, ffi.LLVMModuleRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_AddVerifierPass.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_AddAAEvalPass_module.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_AddSimplifyCFGPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddLoopUnrollPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddLoopRotatePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddInstructionCombinePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_DisposeNewModulePassManger.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef, c_int, c_size_t, +] + +# FunctionPassManager + +ffi.lib.LLVMPY_CreateNewFunctionPassManager.restype = \ + ffi.LLVMFunctionPassManagerRef + +ffi.lib.LLVMPY_RunNewFunctionPassManager.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ffi.LLVMValueRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_AddAAEvalPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddSimplifyCFGPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddLoopUnrollPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddLoopRotatePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddInstructionCombinePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int,] + +ffi.lib.LLVMPY_DisposeNewFunctionPassManger.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int, c_size_t, +] + +# PipelineTuningOptions + +ffi.lib.LLVMPY_CreatePipelineTuningOptions.restype = \ + ffi.LLVMPipelineTuningOptionsRef + +ffi.lib.LLVMPY_PTOGetLoopInterleaving.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetSLPVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopUnrolling.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_DisposePipelineTuningOptions.argtypes = \ + [ffi.LLVMPipelineTuningOptionsRef,] + +# PassBuilder + +ffi.lib.LLVMPY_CreatePassBuilder.restype = ffi.LLVMPassBuilderRef +ffi.lib.LLVMPY_CreatePassBuilder.argtypes = [ffi.LLVMTargetMachineRef, + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_DisposePassBuilder.argtypes = [ffi.LLVMPassBuilderRef,] + +# Pipeline builders + +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.restype = \ + ffi.LLVMModulePassManagerRef +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] + +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.restype = \ + ffi.LLVMFunctionPassManagerRef +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/object_file.py b/python_embeded/Lib/site-packages/llvmlite/binding/object_file.py new file mode 100644 index 0000000000000000000000000000000000000000..2526ef3fa04839f21e7d17dcb16401d588c5f33a --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/object_file.py @@ -0,0 +1,82 @@ +from llvmlite.binding import ffi +from ctypes import (c_bool, c_char_p, c_char, c_size_t, string_at, c_uint64, + POINTER) + + +class SectionIteratorRef(ffi.ObjectRef): + def name(self): + return ffi.lib.LLVMPY_GetSectionName(self) + + def is_text(self): + return ffi.lib.LLVMPY_IsSectionText(self) + + def size(self): + return ffi.lib.LLVMPY_GetSectionSize(self) + + def address(self): + return ffi.lib.LLVMPY_GetSectionAddress(self) + + def data(self): + return string_at(ffi.lib.LLVMPY_GetSectionContents(self), self.size()) + + def is_end(self, object_file): + return ffi.lib.LLVMPY_IsSectionIteratorAtEnd(object_file, self) + + def next(self): + ffi.lib.LLVMPY_MoveToNextSection(self) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeSectionIterator(self) + + +class ObjectFileRef(ffi.ObjectRef): + @classmethod + def from_data(cls, data): + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + @classmethod + def from_path(cls, path): + with open(path, 'rb') as f: + data = f.read() + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + def sections(self): + it = SectionIteratorRef(ffi.lib.LLVMPY_GetSections(self)) + while not it.is_end(self): + yield it + it.next() + + def _dispose(self): + ffi.lib.LLVMPY_DisposeObjectFile(self) + + +ffi.lib.LLVMPY_CreateObjectFile.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_CreateObjectFile.restype = ffi.LLVMObjectFileRef + +ffi.lib.LLVMPY_DisposeObjectFile.argtypes = [ffi.LLVMObjectFileRef] + +ffi.lib.LLVMPY_GetSections.argtypes = [ffi.LLVMObjectFileRef] +ffi.lib.LLVMPY_GetSections.restype = ffi.LLVMSectionIteratorRef + +ffi.lib.LLVMPY_DisposeSectionIterator.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_MoveToNextSection.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.argtypes = [ + ffi.LLVMObjectFileRef, ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.restype = c_bool + +ffi.lib.LLVMPY_GetSectionName.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionName.restype = c_char_p + +ffi.lib.LLVMPY_GetSectionSize.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionSize.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionAddress.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionContents.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionContents.restype = POINTER(c_char) + +ffi.lib.LLVMPY_IsSectionText.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionText.restype = c_bool diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/options.py b/python_embeded/Lib/site-packages/llvmlite/binding/options.py new file mode 100644 index 0000000000000000000000000000000000000000..1baecf9a1ba3384bdd25a2e4c273473afe3890f7 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/options.py @@ -0,0 +1,17 @@ +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string +from ctypes import c_char_p + + +def set_option(name, option): + """ + Set the given LLVM "command-line" option. + + For example set_option("test", "-debug-pass=Structure") would display + all optimization passes when generating code. + """ + ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), + _encode_string(option)) + + +ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/orcjit.py b/python_embeded/Lib/site-packages/llvmlite/binding/orcjit.py new file mode 100644 index 0000000000000000000000000000000000000000..3630b08b560f04d53489d2a34db3af771dcf4377 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/orcjit.py @@ -0,0 +1,342 @@ +import ctypes +from ctypes import POINTER, c_bool, c_char_p, c_uint8, c_uint64, c_size_t + +from llvmlite.binding import ffi, targets + + +class _LinkElement(ctypes.Structure): + _fields_ = [("element_kind", c_uint8), + ("value", c_char_p), + ("value_len", c_size_t)] + + +class _SymbolAddress(ctypes.Structure): + _fields_ = [("name", c_char_p), ("address", c_uint64)] + + +class JITLibraryBuilder: + """ + Create a library for linking by OrcJIT + + OrcJIT operates like a linker: a number of compilation units and + dependencies are collected together and linked into a single dynamic library + that can export functions to other libraries or to be consumed directly as + entry points into JITted code. The native OrcJIT has a lot of memory + management complications so this API is designed to work well with Python's + garbage collection. + + The creation of a new library is a bit like a linker command line where + compilation units, mostly as LLVM IR, and previously constructed libraries + are linked together, then loaded into memory, and the addresses of exported + symbols are extracted. Any static initializers are run and the exported + addresses and a resource tracker is produced. As long as the resource + tracker is referenced somewhere in Python, the exported addresses will be + valid. Once the resource tracker is garbage collected, the static + destructors will run and library will be unloaded from memory. + """ + def __init__(self): + self.__entries = [] + self.__exports = set() + self.__imports = {} + + def add_ir(self, llvmir): + """ + Adds a compilation unit to the library using LLVM IR as the input + format. + + This takes a string or an object that can be converted to a string, + including IRBuilder, that contains LLVM IR. + """ + self.__entries.append((0, str(llvmir).encode('utf-8'))) + return self + + def add_native_assembly(self, asm): + """ + Adds a compilation unit to the library using native assembly as the + input format. + + This takes a string or an object that can be converted to a string that + contains native assembly, which will be + parsed by LLVM. + """ + self.__entries.append((1, str(asm).encode('utf-8'))) + return self + + def add_object_img(self, data): + """ + Adds a compilation unit to the library using pre-compiled object code. + + This takes the bytes of the contents of an object artifact which will be + loaded by LLVM. + """ + self.__entries.append((2, bytes(data))) + return self + + def add_object_file(self, file_path): + """ + Adds a compilation unit to the library using pre-compiled object file. + + This takes a string or path-like object that references an object file + which will be loaded by LLVM. + """ + with open(file_path, "rb") as f: + self.__entries.append((2, f.read())) + return self + + def add_jit_library(self, name): + """ + Adds an existing JIT library as prerequisite. + + The name of the library must match the one provided in a previous link + command. + """ + self.__entries.append((3, str(name).encode('utf-8'))) + return self + + def add_current_process(self): + """ + Allows the JITted library to access symbols in the current binary. + + That is, it allows exporting the current binary's symbols, including + loaded libraries, as imports to the JITted + library. + """ + self.__entries.append((3, b'')) + return self + + def import_symbol(self, name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + self.__imports[str(name)] = c_uint64(address) + return self + + def export_symbol(self, name): + """ + During linking, extract the address of a symbol that was defined in one + of the compilation units. + + This allows getting symbols, functions or global variables, out of the + JIT linked library. The addresses will be + available when the link method is called. + """ + self.__exports.add(str(name)) + return self + + def link(self, lljit, library_name): + """ + Link all the current compilation units into a JITted library and extract + the address of exported symbols. + + An instance of the OrcJIT instance must be provided and this will be the + scope that is used to find other JITted libraries that are dependencies + and also be the place where this library will be defined. + + After linking, the method will return a resource tracker that keeps the + library alive. This tracker also knows the addresses of any exported + symbols that were requested. + + The addresses will be valid as long as the resource tracker is + referenced. + + When the resource tracker is destroyed, the library will be cleaned up, + however, the name of the library cannot be reused. + """ + assert not lljit.closed, "Cannot add to closed JIT" + encoded_library_name = str(library_name).encode('utf-8') + assert len(encoded_library_name) > 0, "Library cannot be empty" + elements = (_LinkElement * len(self.__entries))() + for idx, (kind, value) in enumerate(self.__entries): + elements[idx].element_kind = c_uint8(kind) + elements[idx].value = c_char_p(value) + elements[idx].value_len = c_size_t(len(value)) + exports = (_SymbolAddress * len(self.__exports))() + for idx, name in enumerate(self.__exports): + exports[idx].name = name.encode('utf-8') + + imports = (_SymbolAddress * len(self.__imports))() + for idx, (name, addr) in enumerate(self.__imports.items()): + imports[idx].name = name.encode('utf-8') + imports[idx].address = addr + + with ffi.OutputString() as outerr: + tracker = lljit._capi.LLVMPY_LLJIT_Link( + lljit._ptr, + encoded_library_name, + elements, + len(self.__entries), + imports, + len(self.__imports), + exports, + len(self.__exports), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + return ResourceTracker(tracker, + library_name, + {name: exports[idx].address + for idx, name in enumerate(self.__exports)}) + + +class ResourceTracker(ffi.ObjectRef): + """ + A resource tracker is created for each loaded JIT library and keeps the + module alive. + + OrcJIT supports unloading libraries that are no longer used. This resource + tracker should be stored in any object that reference functions or constants + for a JITted library. When all references to the resource tracker are + dropped, this will trigger LLVM to unload the library and destroy any + functions. + + Failure to keep resource trackers while calling a function or accessing a + symbol can result in crashes or memory corruption. + + LLVM internally tracks references between different libraries, so only + "leaf" libraries need to be tracked. + """ + def __init__(self, ptr, name, addresses): + self.__addresses = addresses + self.__name = name + ffi.ObjectRef.__init__(self, ptr) + + def __getitem__(self, item): + """ + Get the address of an exported symbol as an integer + """ + return self.__addresses[item] + + @property + def name(self): + return self.__name + + def _dispose(self): + with ffi.OutputString() as outerr: + if self._capi.LLVMPY_LLJIT_Dylib_Tracker_Dispose(self, outerr): + raise RuntimeError(str(outerr)) + + +class LLJIT(ffi.ObjectRef): + """ + A OrcJIT-based LLVM JIT engine that can compile and run LLVM IR as a + collection of JITted dynamic libraries + + The C++ OrcJIT API has a lot of memory ownership patterns that do not work + with Python. This API attempts to provide ones that are safe at the expense + of some features. Each LLJIT instance is a collection of JIT-compiled + libraries. In the C++ API, there is a "main" library; this API does not + provide access to the main library. Use the JITLibraryBuilder to create a + new named library instead. + """ + def __init__(self, ptr): + self._td = None + ffi.ObjectRef.__init__(self, ptr) + + def lookup(self, dylib, fn): + """ + Find a function in this dynamic library and construct a new tracking + object for it + + If the library or function do not exist, an exception will occur. + + Parameters + ---------- + dylib : str or None + the name of the library containing the symbol + fn : str + the name of the function to get + """ + assert not self.closed, "Cannot lookup in closed JIT" + address = ctypes.c_uint64() + with ffi.OutputString() as outerr: + tracker = ffi.lib.LLVMPY_LLJITLookup(self, + dylib.encode("utf-8"), + fn.encode("utf-8"), + ctypes.byref(address), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + + return ResourceTracker(tracker, dylib, {fn: address.value}) + + @property + def target_data(self): + """ + The TargetData for this LLJIT instance. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_LLJITGetDataLayout(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def _dispose(self): + if self._td is not None: + self._td.detach() + self._capi.LLVMPY_LLJITDispose(self) + + +def create_lljit_compiler(target_machine=None, *, + use_jit_link=False, + suppress_errors=False): + """ + Create an LLJIT instance + """ + with ffi.OutputString() as outerr: + lljit = ffi.lib.LLVMPY_CreateLLJITCompiler(target_machine, + suppress_errors, + use_jit_link, + outerr) + if not lljit: + raise RuntimeError(str(outerr)) + + return LLJIT(lljit) + + +ffi.lib.LLVMPY_LLJITLookup.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + c_char_p, + POINTER(c_uint64), + POINTER(c_char_p), +] +ffi.lib.LLVMPY_LLJITLookup.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJITGetDataLayout.argtypes = [ + ffi.LLVMOrcLLJITRef, +] +ffi.lib.LLVMPY_LLJITGetDataLayout.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CreateLLJITCompiler.argtypes = [ + ffi.LLVMTargetMachineRef, + c_bool, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateLLJITCompiler.restype = ffi.LLVMOrcLLJITRef + +ffi.lib.LLVMPY_LLJITDispose.argtypes = [ + ffi.LLVMOrcLLJITRef, +] + + +ffi.lib.LLVMPY_LLJIT_Link.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + POINTER(_LinkElement), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Link.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.argtypes = [ + ffi.LLVMOrcDylibTrackerRef, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.restype = c_bool diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/passmanagers.py b/python_embeded/Lib/site-packages/llvmlite/binding/passmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..a9dbf8ac43e5dd42928d43cac4305aa6dc6dbf1f --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/passmanagers.py @@ -0,0 +1,946 @@ +from ctypes import (c_bool, c_char_p, c_int, c_size_t, Structure, byref, + POINTER) +from collections import namedtuple +from enum import IntFlag +from llvmlite.binding import ffi +from llvmlite.binding.initfini import llvm_version_info +import os +from tempfile import mkstemp +from llvmlite.binding.common import _encode_string + +llvm_version_major = llvm_version_info[0] + +_prunestats = namedtuple('PruneStats', + ('basicblock diamond fanout fanout_raise')) + + +class PruneStats(_prunestats): + """ Holds statistics from reference count pruning. + """ + + def __add__(self, other): + if not isinstance(other, PruneStats): + msg = 'PruneStats can only be added to another PruneStats, got {}.' + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock + other.basicblock, + self.diamond + other.diamond, + self.fanout + other.fanout, + self.fanout_raise + other.fanout_raise) + + def __sub__(self, other): + if not isinstance(other, PruneStats): + msg = ('PruneStats can only be subtracted from another PruneStats, ' + 'got {}.') + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock - other.basicblock, + self.diamond - other.diamond, + self.fanout - other.fanout, + self.fanout_raise - other.fanout_raise) + + +class _c_PruneStats(Structure): + _fields_ = [ + ('basicblock', c_size_t), + ('diamond', c_size_t), + ('fanout', c_size_t), + ('fanout_raise', c_size_t)] + + +def dump_refprune_stats(printout=False): + """ Returns a namedtuple containing the current values for the refop pruning + statistics. If kwarg `printout` is True the stats are printed to stderr, + default is False. + """ + + stats = _c_PruneStats(0, 0, 0, 0) + do_print = c_bool(printout) + + ffi.lib.LLVMPY_DumpRefPruneStats(byref(stats), do_print) + return PruneStats(stats.basicblock, stats.diamond, stats.fanout, + stats.fanout_raise) + + +def set_time_passes(enable): + """Enable or disable the pass timers. + + Parameters + ---------- + enable : bool + Set to True to enable the pass timers. + Set to False to disable the pass timers. + """ + ffi.lib.LLVMPY_SetTimePasses(c_bool(enable)) + + +def report_and_reset_timings(): + """Returns the pass timings report and resets the LLVM internal timers. + + Pass timers are enabled by ``set_time_passes()``. If the timers are not + enabled, this function will return an empty string. + + Returns + ------- + res : str + LLVM generated timing report. + """ + with ffi.OutputString() as buf: + ffi.lib.LLVMPY_ReportAndResetTimings(buf) + return str(buf) + + +def create_module_pass_manager(): + return ModulePassManager() + + +def create_function_pass_manager(module): + return FunctionPassManager(module) + + +class RefPruneSubpasses(IntFlag): + PER_BB = 0b0001 # noqa: E221 + DIAMOND = 0b0010 # noqa: E221 + FANOUT = 0b0100 # noqa: E221 + FANOUT_RAISE = 0b1000 + ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE + + +class PassManager(ffi.ObjectRef): + """PassManager + """ + + def _dispose(self): + self._capi.LLVMPY_DisposePassManager(self) + + def add_aa_eval_pass(self): + """ + See https://llvm.org/docs/Passes.html#aa-eval-exhaustive-alias-analysis-precision-evaluator + + LLVM 14: `llvm::createAAEvalPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAAEvalPass(self) + + def add_basic_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#basic-aa-basic-alias-analysis-stateless-aa-impl + + LLVM 14: `llvm::createBasicAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddBasicAAWrapperPass(self) + + def add_constant_merge_pass(self): + """ + See http://llvm.org/docs/Passes.html#constmerge-merge-duplicate-global-constants + + LLVM 14: `LLVMAddConstantMergePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddConstantMergePass(self) + + def add_dead_arg_elimination_pass(self): + """ + See http://llvm.org/docs/Passes.html#deadargelim-dead-argument-elimination + + LLVM 14: `LLVMAddDeadArgEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDeadArgEliminationPass(self) + + def add_dependence_analysis_pass(self): + """ + See https://llvm.org/docs/Passes.html#da-dependence-analysis + + LLVM 14: `llvm::createDependenceAnalysisWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDependenceAnalysisPass(self) + + def add_dot_call_graph_pass(self): + """ + See https://llvm.org/docs/Passes.html#dot-callgraph-print-call-graph-to-dot-file + + LLVM 14: `llvm::createCallGraphDOTPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass(self) + + def add_dot_cfg_printer_pass(self): + """ + See https://llvm.org/docs/Passes.html#dot-cfg-print-cfg-of-function-to-dot-file + + LLVM 14: `llvm::createCFGPrinterLegacyPassPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddCFGPrinterPass(self) + + def add_dot_dom_printer_pass(self, show_body=False): + """ + See https://llvm.org/docs/Passes.html#dot-dom-print-dominance-tree-of-function-to-dot-file + + LLVM 14: `llvm::createDomPrinterPass` and `llvm::createDomOnlyPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDotDomPrinterPass(self, show_body) + + def add_dot_postdom_printer_pass(self, show_body=False): + """ + See https://llvm.org/docs/Passes.html#dot-postdom-print-postdominance-tree-of-function-to-dot-file + + LLVM 14: `llvm::createPostDomPrinterPass` and `llvm::createPostDomOnlyPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDotPostDomPrinterPass(self, show_body) + + def add_globals_mod_ref_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#globalsmodref-aa-simple-mod-ref-analysis-for-globals + + LLVM 14: `llvm::createGlobalsAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalsModRefAAPass(self) + + def add_iv_users_pass(self): + """ + See https://llvm.org/docs/Passes.html#iv-users-induction-variable-users + + LLVM 14: `llvm::createIVUsersPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddIVUsersPass(self) + + def add_lint_pass(self): + """ + See https://llvm.org/docs/Passes.html#lint-statically-lint-checks-llvm-ir + + LLVM 14: `llvm::createLintLegacyPassPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLintPass(self) + + def add_lazy_value_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#lazy-value-info-lazy-value-information-analysis + + LLVM 14: `llvm::createLazyValueInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLazyValueInfoPass(self) + + def add_module_debug_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#module-debuginfo-decodes-module-level-debug-info + + LLVM 14: `llvm::createModuleDebugInfoPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass(self) + + def add_region_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#regions-detect-single-entry-single-exit-regions + + LLVM 14: `llvm::createRegionInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddRegionInfoPass(self) + + def add_scalar_evolution_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#scev-aa-scalarevolution-based-alias-analysis + + LLVM 14: `llvm::createSCEVAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddScalarEvolutionAAPass(self) + + def add_aggressive_dead_code_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#adce-aggressive-dead-code-elimination + + LLVM 14: `llvm::createAggressiveDCEPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAggressiveDCEPass(self) + + def add_always_inliner_pass(self, insert_lifetime=True): + """ + See https://llvm.org/docs/Passes.html#always-inline-inliner-for-always-inline-functions + + LLVM 14: `llvm::createAlwaysInlinerLegacyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAlwaysInlinerPass(self, insert_lifetime) + + def add_arg_promotion_pass(self, max_elements=3): + """ + See https://llvm.org/docs/Passes.html#argpromotion-promote-by-reference-arguments-to-scalars + + LLVM 14: `llvm::createArgumentPromotionPass` + """ # noqa E501 + raise RuntimeError('ArgumentPromotionPass unavailable in LLVM > 14') + + def add_break_critical_edges_pass(self): + """ + See https://llvm.org/docs/Passes.html#break-crit-edges-break-critical-edges-in-cfg + + LLVM 14: `llvm::createBreakCriticalEdgesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddBreakCriticalEdgesPass(self) + + def add_dead_store_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#dse-dead-store-elimination + + LLVM 14: `llvm::createDeadStoreEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDeadStoreEliminationPass(self) + + def add_reverse_post_order_function_attrs_pass(self): + """ + See https://llvm.org/docs/Passes.html#function-attrs-deduce-function-attributes + + LLVM 14: `llvm::createReversePostOrderFunctionAttrsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass(self) + + def add_function_attrs_pass(self): + """ + See http://llvm.org/docs/Passes.html#functionattrs-deduce-function-attributes + + LLVM 14: `LLVMAddFunctionAttrsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddFunctionAttrsPass(self) + + def add_function_inlining_pass(self, threshold): + """ + See http://llvm.org/docs/Passes.html#inline-function-integration-inlining + + LLVM 14: `createFunctionInliningPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddFunctionInliningPass(self, threshold) + + def add_global_dce_pass(self): + """ + See http://llvm.org/docs/Passes.html#globaldce-dead-global-elimination + + LLVM 14: `LLVMAddGlobalDCEPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalDCEPass(self) + + def add_global_optimizer_pass(self): + """ + See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer + + LLVM 14: `LLVMAddGlobalOptimizerPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalOptimizerPass(self) + + def add_ipsccp_pass(self): + """ + See http://llvm.org/docs/Passes.html#ipsccp-interprocedural-sparse-conditional-constant-propagation + + LLVM 14: `LLVMAddIPSCCPPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddIPSCCPPass(self) + + def add_dead_code_elimination_pass(self): + """ + See http://llvm.org/docs/Passes.html#dce-dead-code-elimination + LLVM 14: `llvm::createDeadCodeEliminationPass` + """ + ffi.lib.LLVMPY_AddDeadCodeEliminationPass(self) + + def add_aggressive_instruction_combining_pass(self): + """ + See https://llvm.org/docs/Passes.html#aggressive-instcombine-combine-expression-patterns + + LLVM 14: `llvm::createAggressiveInstCombinerPass` + """ # noqa E501 + if llvm_version_major > 15: + msg = "AggressiveInstrCombinerPass unavailable in LLVM > 15" + raise RuntimeError(msg) + + ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass(self) + + def add_internalize_pass(self): + """ + See https://llvm.org/docs/Passes.html#internalize-internalize-global-symbols + + LLVM 14: `llvm::createInternalizePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddInternalizePass(self) + + def add_cfg_simplification_pass(self): + """ + See http://llvm.org/docs/Passes.html#simplifycfg-simplify-the-cfg + + LLVM 14: `LLVMAddCFGSimplificationPass` + """ + ffi.lib.LLVMPY_AddCFGSimplificationPass(self) + + def add_jump_threading_pass(self, threshold=-1): + """ + See https://llvm.org/docs/Passes.html#jump-threading-jump-threading + + LLVM 14: `llvm::createJumpThreadingPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddJumpThreadingPass(self, threshold) + + def add_lcssa_pass(self): + """ + See https://llvm.org/docs/Passes.html#lcssa-loop-closed-ssa-form-pass + + LLVM 14: `llvm::createLCSSAPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLCSSAPass(self) + + def add_gvn_pass(self): + """ + See http://llvm.org/docs/Passes.html#gvn-global-value-numbering + + LLVM 14: `LLVMAddGVNPass` + """ + ffi.lib.LLVMPY_AddGVNPass(self) + + def add_instruction_combining_pass(self): + """ + See http://llvm.org/docs/Passes.html#passes-instcombine + + LLVM 14: `LLVMAddInstructionCombiningPass` + """ + ffi.lib.LLVMPY_AddInstructionCombiningPass(self) + + def add_licm_pass(self): + """ + See http://llvm.org/docs/Passes.html#licm-loop-invariant-code-motion + + LLVM 14: `LLVMAddLICMPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLICMPass(self) + + def add_loop_deletion_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-deletion-delete-dead-loops + + LLVM 14: `llvm::createLoopDeletionPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopDeletionPass(self) + + def add_loop_extractor_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-extract-extract-loops-into-new-functions + + LLVM 14: `llvm::createLoopExtractorPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopExtractorPass(self) + + def add_single_loop_extractor_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-extract-single-extract-at-most-one-loop-into-a-new-function + + LLVM 14: `llvm::createSingleLoopExtractorPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSingleLoopExtractorPass(self) + + def add_sccp_pass(self): + """ + See http://llvm.org/docs/Passes.html#sccp-sparse-conditional-constant-propagation + + LLVM 14: `LLVMAddSCCPPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSCCPPass(self) + + def add_loop_strength_reduce_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-reduce-loop-strength-reduction + + LLVM 14: `llvm::createLoopStrengthReducePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopStrengthReducePass(self) + + def add_loop_simplification_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-simplify-canonicalize-natural-loops + + LLVM 14: `llvm::createLoopSimplifyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopSimplificationPass(self) + + def add_loop_unroll_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-unroll-unroll-loops + + LLVM 14: `LLVMAddLoopUnrollPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnrollPass(self) + + def add_loop_unroll_and_jam_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-unroll-and-jam-unroll-and-jam-loops + + LLVM 14: `LLVMAddLoopUnrollAndJamPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnrollAndJamPass(self) + + def add_loop_unswitch_pass(self, + optimize_for_size=False, + has_branch_divergence=False): + """ + See https://llvm.org/docs/Passes.html#loop-unswitch-unswitch-loops + + LLVM 14: `llvm::createLoopUnswitchPass` + LLVM 15: `llvm::createSimpleLoopUnswitchLegacyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnswitchPass(self, optimize_for_size, + has_branch_divergence) + + def add_lower_atomic_pass(self): + """ + See https://llvm.org/docs/Passes.html#loweratomic-lower-atomic-intrinsics-to-non-atomic-form + + LLVM 14: `llvm::createLowerAtomicPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerAtomicPass(self) + + def add_lower_invoke_pass(self): + """ + See https://llvm.org/docs/Passes.html#lowerinvoke-lower-invokes-to-calls-for-unwindless-code-generators + + LLVM 14: `llvm::createLowerInvokePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerInvokePass(self) + + def add_lower_switch_pass(self): + """ + See https://llvm.org/docs/Passes.html#lowerswitch-lower-switchinsts-to-branches + + LLVM 14: `llvm::createLowerSwitchPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerSwitchPass(self) + + def add_memcpy_optimization_pass(self): + """ + See https://llvm.org/docs/Passes.html#memcpyopt-memcpy-optimization + + LLVM 14: `llvm::createMemCpyOptPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMemCpyOptimizationPass(self) + + def add_merge_functions_pass(self): + """ + See https://llvm.org/docs/Passes.html#mergefunc-merge-functions + + LLVM 14: `llvm::createMergeFunctionsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMergeFunctionsPass(self) + + def add_merge_returns_pass(self): + """ + See https://llvm.org/docs/Passes.html#mergereturn-unify-function-exit-nodes + + LLVM 14: `llvm::createUnifyFunctionExitNodesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMergeReturnsPass(self) + + def add_partial_inlining_pass(self): + """ + See https://llvm.org/docs/Passes.html#partial-inliner-partial-inliner + + LLVM 14: `llvm::createPartialInliningPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddPartialInliningPass(self) + + def add_prune_exception_handling_pass(self): + """ + See https://llvm.org/docs/Passes.html#prune-eh-remove-unused-exception-handling-info + + LLVM 14: `llvm::createPruneEHPass` + """ # noqa E501 + if llvm_version_major > 15: + raise RuntimeError("PruneEHPass unavailable in LLVM > 15") + ffi.lib.LLVMPY_AddPruneExceptionHandlingPass(self) + + def add_reassociate_expressions_pass(self): + """ + See https://llvm.org/docs/Passes.html#reassociate-reassociate-expressions + + LLVM 14: `llvm::createReassociatePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddReassociatePass(self) + + def add_demote_register_to_memory_pass(self): + """ + See https://llvm.org/docs/Passes.html#rel-lookup-table-converter-relative-lookup-table-converter + + LLVM 14: `llvm::createDemoteRegisterToMemoryPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass(self) + + def add_sroa_pass(self): + """ + See http://llvm.org/docs/Passes.html#scalarrepl-scalar-replacement-of-aggregates-dt + Note that this pass corresponds to the ``opt -sroa`` command-line option, + despite the link above. + + LLVM 14: `llvm::createSROAPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSROAPass(self) + + def add_sink_pass(self): + """ + See https://llvm.org/docs/Passes.html#sink-code-sinking + + LLVM 14: `llvm::createSinkingPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSinkPass(self) + + def add_strip_symbols_pass(self, only_debug=False): + """ + See https://llvm.org/docs/Passes.html#strip-strip-all-symbols-from-a-module + + LLVM 14: `llvm::createStripSymbolsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripSymbolsPass(self, only_debug) + + def add_strip_dead_debug_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-dead-debug-info-strip-debug-info-for-unused-symbols + + LLVM 14: `llvm::createStripDeadDebugInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDeadDebugInfoPass(self) + + def add_strip_dead_prototypes_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-dead-prototypes-strip-unused-function-prototypes + + LLVM 14: `llvm::createStripDeadPrototypesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDeadPrototypesPass(self) + + def add_strip_debug_declare_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-debug-declare-strip-all-llvm-dbg-declare-intrinsics + + LLVM 14: `llvm::createStripDebugDeclarePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass(self) + + def add_strip_nondebug_symbols_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-nondebug-strip-all-symbols-except-dbg-symbols-from-a-module + + LLVM 14: `llvm::createStripNonDebugSymbolsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripNondebugSymbolsPass(self) + + def add_tail_call_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#tailcallelim-tail-call-elimination + + LLVM 14: `llvm::createTailCallEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddTailCallEliminationPass(self) + + def add_type_based_alias_analysis_pass(self): + """ + LLVM 14: `LLVMAddTypeBasedAliasAnalysisPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass(self) + + def add_basic_alias_analysis_pass(self): + """ + See http://llvm.org/docs/AliasAnalysis.html#the-basicaa-pass + + LLVM 14: `LLVMAddBasicAliasAnalysisPass` + """ + ffi.lib.LLVMPY_AddBasicAliasAnalysisPass(self) + + def add_loop_rotate_pass(self): + """http://llvm.org/docs/Passes.html#loop-rotate-rotate-loops.""" + ffi.lib.LLVMPY_AddLoopRotatePass(self) + + def add_target_library_info(self, triple): + ffi.lib.LLVMPY_AddTargetLibraryInfoPass(self, _encode_string(triple)) + + def add_instruction_namer_pass(self): + """ + See https://llvm.org/docs/Passes.html#instnamer-assign-names-to-anonymous-instructions. + + LLVM 14: `llvm::createInstructionNamerPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddInstructionNamerPass(self) + + # Non-standard LLVM passes + + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddLegacyRefPrunePass(self, iflags, subgraph_limit) + + +class ModulePassManager(PassManager): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreatePassManager() + PassManager.__init__(self, ptr) + + def run(self, module, remarks_file=None, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given module. + + Parameters + ---------- + module : llvmlite.binding.ModuleRef + The module to be optimized inplace + remarks_file : str; optional + If not `None`, it is the file to store the optimization remarks. + remarks_format : str; optional + The format to write; YAML is default + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + if remarks_file is None: + return ffi.lib.LLVMPY_RunPassManager(self, module) + else: + r = ffi.lib.LLVMPY_RunPassManagerWithRemarks( + self, module, _encode_string(remarks_format), + _encode_string(remarks_filter), + _encode_string(remarks_file)) + if r == -1: + raise IOError("Failed to initialize remarks file.") + return r > 0 + + def run_with_remarks(self, module, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given module and returns the result and + the remarks data. + + Parameters + ---------- + module : llvmlite.binding.ModuleRef + The module to be optimized + remarks_format : str + The remarks output; YAML is the default + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + remarkdesc, remarkfile = mkstemp() + try: + with os.fdopen(remarkdesc, 'r'): + pass + r = self.run(module, remarkfile, remarks_format, remarks_filter) + if r == -1: + raise IOError("Failed to initialize remarks file.") + with open(remarkfile) as f: + return bool(r), f.read() + finally: + os.unlink(remarkfile) + + +class FunctionPassManager(PassManager): + + def __init__(self, module): + ptr = ffi.lib.LLVMPY_CreateFunctionPassManager(module) + self._module = module + module._owned = True + PassManager.__init__(self, ptr) + + def initialize(self): + """ + Initialize the FunctionPassManager. Returns True if it produced + any changes (?). + """ + return ffi.lib.LLVMPY_InitializeFunctionPassManager(self) + + def finalize(self): + """ + Finalize the FunctionPassManager. Returns True if it produced + any changes (?). + """ + return ffi.lib.LLVMPY_FinalizeFunctionPassManager(self) + + def run(self, function, remarks_file=None, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given function. + + Parameters + ---------- + function : llvmlite.binding.FunctionRef + The function to be optimized inplace + remarks_file : str; optional + If not `None`, it is the file to store the optimization remarks. + remarks_format : str; optional + The format of the remarks file; the default is YAML + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + if remarks_file is None: + return ffi.lib.LLVMPY_RunFunctionPassManager(self, function) + else: + r = ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks( + self, function, _encode_string(remarks_format), + _encode_string(remarks_filter), + _encode_string(remarks_file)) + if r == -1: + raise IOError("Failed to initialize remarks file.") + return bool(r) + + def run_with_remarks(self, function, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given function and returns the result + and the remarks data. + + Parameters + ---------- + function : llvmlite.binding.FunctionRef + The function to be optimized inplace + remarks_format : str; optional + The format of the remarks file; the default is YAML + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + # LLVM is going to need to close this file and then reopen it, so we + # can't use an unlinked temporary file. + remarkdesc, remarkfile = mkstemp() + try: + # We get an open handle, but we need LLVM to write first, so close + # it. + with os.fdopen(remarkdesc, 'r'): + pass + r = self.run(function, remarkfile, remarks_format, remarks_filter) + if r == -1: + raise IOError("Failed to initialize remarks file.") + with open(remarkfile) as f: + return bool(r), f.read() + finally: + os.unlink(remarkfile) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_CreatePassManager.restype = ffi.LLVMPassManagerRef + +ffi.lib.LLVMPY_CreateFunctionPassManager.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CreateFunctionPassManager.restype = ffi.LLVMPassManagerRef + +ffi.lib.LLVMPY_DisposePassManager.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_RunPassManager.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMModuleRef] +ffi.lib.LLVMPY_RunPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunPassManagerWithRemarks.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMModuleRef, + c_char_p, + c_char_p, + c_char_p] +ffi.lib.LLVMPY_RunPassManagerWithRemarks.restype = c_int + +ffi.lib.LLVMPY_InitializeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_InitializeFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_FinalizeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_FinalizeFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMValueRef] +ffi.lib.LLVMPY_RunFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.argtypes = [ + ffi.LLVMPassManagerRef, ffi.LLVMValueRef, c_char_p, c_char_p, c_char_p +] +ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.restype = c_int + +ffi.lib.LLVMPY_AddAAEvalPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddBasicAAWrapperPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddConstantMergePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDeadArgEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDependenceAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCFGPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDotDomPrinterPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] +ffi.lib.LLVMPY_AddDotPostDomPrinterPass.argtypes = [ + ffi.LLVMPassManagerRef, + c_bool] +ffi.lib.LLVMPY_AddGlobalsModRefAAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddInstructionCountPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddIVUsersPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLazyValueInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLintPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddRegionInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddScalarEvolutionAAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddAggressiveDCEPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddAlwaysInlinerPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] +ffi.lib.LLVMPY_AddBreakCriticalEdgesPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDeadStoreEliminationPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass.argtypes = [ + ffi.LLVMPassManagerRef] + +if llvm_version_major < 16: + ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass.argtypes = [ + ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_AddInternalizePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLCSSAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopDeletionPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSingleLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopStrengthReducePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopSimplificationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnrollPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnrollAndJamPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnswitchPass.argtypes = [ffi.LLVMPassManagerRef, c_bool, + c_bool] +ffi.lib.LLVMPY_AddLowerAtomicPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLowerInvokePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLowerSwitchPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMemCpyOptimizationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMergeFunctionsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMergeReturnsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddPartialInliningPass.argtypes = [ffi.LLVMPassManagerRef] + +if llvm_version_major < 16: + ffi.lib.LLVMPY_AddPruneExceptionHandlingPass.argtypes = [ + ffi.LLVMPassManagerRef + ] + +ffi.lib.LLVMPY_AddReassociatePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSinkPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripSymbolsPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] +ffi.lib.LLVMPY_AddStripDeadDebugInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripDeadPrototypesPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripNondebugSymbolsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTailCallEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddJumpThreadingPass.argtypes = [ffi.LLVMPassManagerRef, c_int] +ffi.lib.LLVMPY_AddFunctionAttrsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddFunctionInliningPass.argtypes = [ + ffi.LLVMPassManagerRef, c_int] +ffi.lib.LLVMPY_AddGlobalDCEPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddGlobalOptimizerPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddIPSCCPPass.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_AddDeadCodeEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCFGSimplificationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddGVNPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddInstructionCombiningPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLICMPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSCCPPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSROAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddBasicAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTargetLibraryInfoPass.argtypes = [ffi.LLVMPassManagerRef, + c_char_p] +ffi.lib.LLVMPY_AddInstructionNamerPass.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_AddLegacyRefPrunePass.argtypes = [ffi.LLVMPassManagerRef, c_int, + c_size_t] + +ffi.lib.LLVMPY_DumpRefPruneStats.argtypes = [POINTER(_c_PruneStats), c_bool] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/targets.py b/python_embeded/Lib/site-packages/llvmlite/binding/targets.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e5c13ead9d54ab976fbae21a09c2520bd3d459 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/targets.py @@ -0,0 +1,520 @@ +import os +from ctypes import (POINTER, c_char_p, c_longlong, c_int, c_size_t, + c_void_p, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.initfini import llvm_version_info +from llvmlite.binding.common import _decode_string, _encode_string +from collections import namedtuple + +# FIXME: Remove `opaque_pointers_enabled` once typed pointers are no longer +# supported. +from llvmlite import opaque_pointers_enabled + +Triple = namedtuple('Triple', ['Arch', 'SubArch', 'Vendor', + 'OS', 'Env', 'ObjectFormat']) + + +def get_process_triple(): + """ + Return a target triple suitable for generating code for the current process. + An example when the default triple from ``get_default_triple()`` is not be + suitable is when LLVM is compiled for 32-bit but the process is executing + in 64-bit mode. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetProcessTriple(out) + return str(out) + + +def get_triple_parts(triple: str): + """ + Return a tuple of the parts of the given triple. + """ + with ffi.OutputString() as arch, \ + ffi.OutputString() as vendor, \ + ffi.OutputString() as os, ffi.OutputString() as env: + ffi.lib.LLVMPY_GetTripleParts(triple.encode('utf8'), + arch, vendor, os, env) + arch = str(arch) + subarch = '' + for _str in triple.split('-'): + if _str.startswith(arch): + subarch = _str[len(arch):] + break + return Triple(arch, subarch, str(vendor), str(os), + str(env), get_object_format(triple)) + + +class FeatureMap(dict): + """ + Maps feature name to a boolean indicating the availability of the feature. + Extends ``dict`` to add `.flatten()` method. + """ + + def flatten(self, sort=True): + """ + Args + ---- + sort: bool + Optional. If True, the features are sorted by name; otherwise, + the ordering is unstable between python session due to hash + randomization. Defaults to True. + + Returns a string suitable for use as the ``features`` argument to + ``Target.create_target_machine()``. + + """ + iterator = sorted(self.items()) if sort else iter(self.items()) + flag_map = {True: '+', False: '-'} + return ','.join('{0}{1}'.format(flag_map[v], k) + for k, v in iterator) + + +def get_host_cpu_features(): + """ + Returns a dictionary-like object indicating the CPU features for current + architecture and whether they are enabled for this CPU. The key-value pairs + are the feature name as string and a boolean indicating whether the feature + is available. The returned value is an instance of ``FeatureMap`` class, + which adds a new method ``.flatten()`` for returning a string suitable for + use as the "features" argument to ``Target.create_target_machine()``. + + If LLVM has not implemented this feature or it fails to get the information, + this function will raise a RuntimeError exception. + """ + with ffi.OutputString() as out: + outdict = FeatureMap() + if not ffi.lib.LLVMPY_GetHostCPUFeatures(out): + return outdict + flag_map = {'+': True, '-': False} + content = str(out) + if content: # protect against empty string + for feat in content.split(','): + if feat: # protect against empty feature + outdict[feat[1:]] = flag_map[feat[0]] + return outdict + + +def get_default_triple(): + """ + Return the default target triple LLVM is configured to produce code for. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetDefaultTargetTriple(out) + return str(out) + + +def get_host_cpu_name(): + """ + Get the name of the host's CPU, suitable for using with + :meth:`Target.create_target_machine()`. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetHostCPUName(out) + return str(out) + + +# Adapted from https://github.com/llvm/llvm-project/blob/release/15.x/llvm/include/llvm/ADT/Triple.h#L269 # noqa +llvm_version_major = llvm_version_info[0] + + +if llvm_version_major >= 15: + _object_formats = { + 0: "Unknown", + 1: "COFF", + 2: "DXContainer", + 3: "ELF", + 4: "GOFF", + 5: "MachO", + 6: "SPIRV", + 7: "Wasm", + 8: "XCOFF", + } +else: + _object_formats = { + 0: "Unknown", + 1: "COFF", + 2: "ELF", + 3: "GOFF", + 4: "MachO", + 5: "Wasm", + 6: "XCOFF", + } + + +def get_object_format(triple=None): + """ + Get the object format for the given *triple* string (or the default + triple if omitted). + A string is returned + """ + if triple is None: + triple = get_default_triple() + res = ffi.lib.LLVMPY_GetTripleObjectFormat(_encode_string(triple)) + return _object_formats[res] + + +def create_target_data(layout): + """ + Create a TargetData instance for the given *layout* string. + """ + return TargetData(ffi.lib.LLVMPY_CreateTargetData(_encode_string(layout))) + + +class TargetData(ffi.ObjectRef): + """ + A TargetData provides structured access to a data layout. + Use :func:`create_target_data` to create instances. + """ + + def __str__(self): + if self._closed: + return "" + with ffi.OutputString() as out: + ffi.lib.LLVMPY_CopyStringRepOfTargetData(self, out) + return str(out) + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetData(self) + + def get_abi_size(self, ty): + """ + Get ABI size of LLVM type *ty*. + """ + return ffi.lib.LLVMPY_ABISizeOfType(self, ty) + + def get_element_offset(self, ty, position): + """ + Get byte offset of type's ty element at the given position + """ + + offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position) + if offset == -1: + raise ValueError("Could not determined offset of {}th " + "element of the type '{}'. Is it a struct" + "type?".format(position, str(ty))) + return offset + + def get_abi_alignment(self, ty): + """ + Get minimum ABI alignment of LLVM type *ty*. + """ + return ffi.lib.LLVMPY_ABIAlignmentOfType(self, ty) + + def get_pointee_abi_size(self, ty): + """ + Get ABI size of pointee type of LLVM pointer type *ty*. + """ + if opaque_pointers_enabled: + raise RuntimeError("Cannot get pointee type in opaque pointer " + "mode.") + size = ffi.lib.LLVMPY_ABISizeOfElementType(self, ty) + if size == -1: + raise RuntimeError("Not a pointer type: %s" % (ty,)) + return size + + def get_pointee_abi_alignment(self, ty): + """ + Get minimum ABI alignment of pointee type of LLVM pointer type *ty*. + """ + if opaque_pointers_enabled: + raise RuntimeError("Cannot get pointee type in opaque pointer " + "mode.") + size = ffi.lib.LLVMPY_ABIAlignmentOfElementType(self, ty) + if size == -1: + raise RuntimeError("Not a pointer type: %s" % (ty,)) + return size + + +RELOC = frozenset(['default', 'static', 'pic', 'dynamicnopic']) +CODEMODEL = frozenset(['default', 'jitdefault', 'small', 'kernel', 'medium', + 'large']) + + +class Target(ffi.ObjectRef): + _triple = '' + + # No _dispose() method since LLVMGetTargetFromTriple() returns a + # persistent object. + + @classmethod + def from_default_triple(cls): + """ + Create a Target instance for the default triple. + """ + triple = get_default_triple() + return cls.from_triple(triple) + + @classmethod + def from_triple(cls, triple): + """ + Create a Target instance for the given triple (a string). + """ + with ffi.OutputString() as outerr: + target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'), + outerr) + if not target: + raise RuntimeError(str(outerr)) + target = cls(target) + target._triple = triple + return target + + @property + def name(self): + s = ffi.lib.LLVMPY_GetTargetName(self) + return _decode_string(s) + + @property + def description(self): + s = ffi.lib.LLVMPY_GetTargetDescription(self) + return _decode_string(s) + + @property + def triple(self): + return self._triple + + def __str__(self): + return "".format(self.name, self.description) + + def create_target_machine(self, cpu='', features='', + opt=2, reloc='default', codemodel='jitdefault', + printmc=False, jit=False, abiname=''): + """ + Create a new TargetMachine for this target and the given options. + + Specifying codemodel='default' will result in the use of the "small" + code model. Specifying codemodel='jitdefault' will result in the code + model being picked based on platform bitness (32="small", 64="large"). + + The `printmc` option corresponds to llvm's `-print-machineinstrs`. + + The `jit` option should be set when the target-machine is to be used + in a JIT engine. + + The `abiname` option specifies the ABI. RISC-V targets with hard-float + needs to pass the ABI name to LLVM. + """ + assert 0 <= opt <= 3 + assert reloc in RELOC + assert codemodel in CODEMODEL + triple = self._triple + # MCJIT under Windows only supports ELF objects, see + # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html + # Note we still want to produce regular COFF files in AOT mode. + if os.name == 'nt' and codemodel == 'jitdefault': + triple += '-elf' + tm = ffi.lib.LLVMPY_CreateTargetMachine(self, + _encode_string(triple), + _encode_string(cpu), + _encode_string(features), + opt, + _encode_string(reloc), + _encode_string(codemodel), + int(printmc), + int(jit), + _encode_string(abiname), + ) + if tm: + return TargetMachine(tm) + else: + raise RuntimeError("Cannot create target machine") + + +class TargetMachine(ffi.ObjectRef): + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetMachine(self) + + def add_analysis_passes(self, pm): + """ + Register analysis passes for this target machine with a pass manager. + """ + ffi.lib.LLVMPY_AddAnalysisPasses(self, pm) + + def set_asm_verbosity(self, verbose): + """ + Set whether this target machine will emit assembly with human-readable + comments describing control flow, debug information, and so on. + """ + ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity(self, verbose) + + def emit_object(self, module): + """ + Represent the module as a code object, suitable for use with + the platform's linker. Returns a byte string. + """ + return self._emit_to_memory(module, use_object=True) + + def emit_assembly(self, module): + """ + Return the raw assembler of the module, as a string. + + llvm.initialize_native_asmprinter() must have been called first. + """ + return _decode_string(self._emit_to_memory(module, use_object=False)) + + def _emit_to_memory(self, module, use_object=False): + """Returns bytes of object code of the module. + + Args + ---- + use_object : bool + Emit object code or (if False) emit assembly code. + """ + with ffi.OutputString() as outerr: + mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module, + int(use_object), + outerr) + if not mb: + raise RuntimeError(str(outerr)) + + bufptr = ffi.lib.LLVMPY_GetBufferStart(mb) + bufsz = ffi.lib.LLVMPY_GetBufferSize(mb) + try: + return string_at(bufptr, bufsz) + finally: + ffi.lib.LLVMPY_DisposeMemoryBuffer(mb) + + @property + def target_data(self): + return TargetData(ffi.lib.LLVMPY_CreateTargetMachineData(self)) + + @property + def triple(self): + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetTargetMachineTriple(self, out) + return str(out) + + +def has_svml(): + """ + Returns True if SVML was enabled at FFI support compile time. + """ + if ffi.lib.LLVMPY_HasSVMLSupport() == 0: + return False + else: + return True + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_GetProcessTriple.argtypes = [POINTER(c_char_p)] +ffi.lib.LLVMPY_GetTripleParts.argtypes = [c_char_p, POINTER(c_char_p), + POINTER(c_char_p), POINTER(c_char_p), + POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUFeatures.argtypes = [POINTER(c_char_p)] +ffi.lib.LLVMPY_GetHostCPUFeatures.restype = c_int + +ffi.lib.LLVMPY_GetDefaultTargetTriple.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUName.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetTripleObjectFormat.argtypes = [c_char_p] +ffi.lib.LLVMPY_GetTripleObjectFormat.restype = c_int + +ffi.lib.LLVMPY_CreateTargetData.argtypes = [c_char_p] +ffi.lib.LLVMPY_CreateTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CopyStringRepOfTargetData.argtypes = [ + ffi.LLVMTargetDataRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_DisposeTargetData.argtypes = [ + ffi.LLVMTargetDataRef, +] + +ffi.lib.LLVMPY_ABISizeOfType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABISizeOfType.restype = c_longlong + +ffi.lib.LLVMPY_OffsetOfElement.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef, + c_int] +ffi.lib.LLVMPY_OffsetOfElement.restype = c_longlong + +ffi.lib.LLVMPY_ABIAlignmentOfType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABIAlignmentOfType.restype = c_longlong + +# FIXME: Remove me once typed pointers are no longer supported. +ffi.lib.LLVMPY_ABISizeOfElementType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABISizeOfElementType.restype = c_longlong + +# FIXME: Remove me once typed pointers are no longer supported. +ffi.lib.LLVMPY_ABIAlignmentOfElementType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABIAlignmentOfElementType.restype = c_longlong + +ffi.lib.LLVMPY_GetTargetFromTriple.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_GetTargetFromTriple.restype = ffi.LLVMTargetRef + +ffi.lib.LLVMPY_GetTargetName.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetName.restype = c_char_p + +ffi.lib.LLVMPY_GetTargetDescription.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetDescription.restype = c_char_p + +ffi.lib.LLVMPY_CreateTargetMachine.argtypes = [ + ffi.LLVMTargetRef, + # Triple + c_char_p, + # CPU + c_char_p, + # Features + c_char_p, + # OptLevel + c_int, + # Reloc + c_char_p, + # CodeModel + c_char_p, + # PrintMC + c_int, + # JIT + c_int, + # ABIName + c_char_p, +] +ffi.lib.LLVMPY_CreateTargetMachine.restype = ffi.LLVMTargetMachineRef + +ffi.lib.LLVMPY_DisposeTargetMachine.argtypes = [ffi.LLVMTargetMachineRef] + +ffi.lib.LLVMPY_GetTargetMachineTriple.argtypes = [ffi.LLVMTargetMachineRef, + POINTER(c_char_p)] + +ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity.argtypes = [ + ffi.LLVMTargetMachineRef, c_int] + +ffi.lib.LLVMPY_AddAnalysisPasses.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_TargetMachineEmitToMemory.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMModuleRef, + c_int, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_TargetMachineEmitToMemory.restype = ffi.LLVMMemoryBufferRef + +ffi.lib.LLVMPY_GetBufferStart.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferStart.restype = c_void_p + +ffi.lib.LLVMPY_GetBufferSize.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferSize.restype = c_size_t + +ffi.lib.LLVMPY_DisposeMemoryBuffer.argtypes = [ffi.LLVMMemoryBufferRef] + +ffi.lib.LLVMPY_CreateTargetMachineData.argtypes = [ + ffi.LLVMTargetMachineRef, +] +ffi.lib.LLVMPY_CreateTargetMachineData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_HasSVMLSupport.argtypes = [] +ffi.lib.LLVMPY_HasSVMLSupport.restype = c_int diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/transforms.py b/python_embeded/Lib/site-packages/llvmlite/binding/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..1795278f1ef15f8f455adb879484abf2d15f02ab --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/transforms.py @@ -0,0 +1,151 @@ +from ctypes import c_uint, c_bool +from llvmlite.binding import ffi +from llvmlite.binding import passmanagers + + +def create_pass_manager_builder(): + return PassManagerBuilder() + + +class PassManagerBuilder(ffi.ObjectRef): + __slots__ = () + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_PassManagerBuilderCreate() + ffi.ObjectRef.__init__(self, ptr) + + @property + def opt_level(self): + """ + The general optimization level as an integer between 0 and 3. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self) + + @opt_level.setter + def opt_level(self, level): + ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel(self, level) + + @property + def size_level(self): + """ + Whether and how much to optimize for size. An integer between 0 and 2. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel(self) + + @size_level.setter + def size_level(self, size): + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel(self, size) + + @property + def inlining_threshold(self): + """ + The integer threshold for inlining a function into another. The higher, + the more likely inlining a function is. This attribute is write-only. + """ + raise NotImplementedError("inlining_threshold is write-only") + + @inlining_threshold.setter + def inlining_threshold(self, threshold): + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold( + self, threshold) + + @property + def disable_unroll_loops(self): + """ + If true, disable loop unrolling. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops(self) + + @disable_unroll_loops.setter + def disable_unroll_loops(self, disable=True): + ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops(self, disable) + + @property + def loop_vectorize(self): + """ + If true, allow vectorizing loops. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self) + + @loop_vectorize.setter + def loop_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize(self, enable) + + @property + def slp_vectorize(self): + """ + If true, enable the "SLP vectorizer", which uses a different algorithm + from the loop vectorizer. Both may be enabled at the same time. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize(self) + + @slp_vectorize.setter + def slp_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize(self, enable) + + def _populate_module_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager(self, pm) + + def _populate_function_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager(self, pm) + + def populate(self, pm): + if isinstance(pm, passmanagers.ModulePassManager): + self._populate_module_pm(pm) + elif isinstance(pm, passmanagers.FunctionPassManager): + self._populate_function_pm(pm) + else: + raise TypeError(pm) + + def _dispose(self): + self._capi.LLVMPY_PassManagerBuilderDispose(self) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_PassManagerBuilderCreate.restype = ffi.LLVMPassManagerBuilderRef + +ffi.lib.LLVMPY_PassManagerBuilderDispose.argtypes = [ + ffi.LLVMPassManagerBuilderRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +# Unsigned int PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel, + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_uint] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_uint + +# Boolean PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_bool] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_bool diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/typeref.py b/python_embeded/Lib/site-packages/llvmlite/binding/typeref.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2e8fe1583aa91c5c468af828b3746ff057fbef --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/typeref.py @@ -0,0 +1,285 @@ +from ctypes import c_int, c_bool, c_void_p, c_uint64, c_uint, POINTER +import enum + +from llvmlite import ir +from llvmlite.binding import ffi + +# FIXME: Remove `opaque_pointers_enabled' when TP's are removed. +from llvmlite import opaque_pointers_enabled + + +class TypeKind(enum.IntEnum): + # The LLVMTypeKind enum from llvm-c/Core.h + + void = 0 + half = 1 + float = 2 + double = 3 + x86_fp80 = 4 + fp128 = 5 + ppc_fp128 = 6 + label = 7 + integer = 8 + function = 9 + struct = 10 + array = 11 + pointer = 12 + vector = 13 + metadata = 14 + x86_mmx = 15 + token = 16 + scalable_vector = 17 + bfloat = 18 + x86_amx = 19 + + +_TypeKindToIRType = { + # All TypeKind here must have a TypeRef.as_ir() implementation + TypeKind.void: ir.VoidType, + TypeKind.half: ir.HalfType, + TypeKind.float: ir.FloatType, + TypeKind.double: ir.DoubleType, + TypeKind.integer: ir.IntType, + TypeKind.function: ir.FunctionType, + TypeKind.pointer: ir.PointerType, + TypeKind.array: ir.ArrayType, + TypeKind.vector: ir.VectorType, + TypeKind.struct: ir.LiteralStructType, +} + + +class TypeRef(ffi.ObjectRef): + """A weak reference to a LLVM type + """ + @property + def name(self): + """ + Get type name + """ + return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) + + @property + def is_struct(self): + """ + Returns true if the type is a struct type. + """ + return ffi.lib.LLVMPY_TypeIsStruct(self) + + @property + def is_pointer(self): + """ + Returns true if the type is a pointer type. + """ + return ffi.lib.LLVMPY_TypeIsPointer(self) + + @property + def is_array(self): + """ + Returns true if the type is an array type. + """ + return ffi.lib.LLVMPY_TypeIsArray(self) + + @property + def is_vector(self): + """ + Returns true if the type is a vector type. + """ + return ffi.lib.LLVMPY_TypeIsVector(self) + + @property + def is_function(self): + """ + Returns true if the type is a function type. + """ + return ffi.lib.LLVMPY_TypeIsFunction(self) + + @property + def is_function_vararg(self): + """ + Returns true if a function type accepts a variable number of arguments. + When the type is not a function, raises exception. + """ + if self.type_kind != TypeKind.function: + raise ValueError("Type {} is not a function".format(self)) + return ffi.lib.LLVMPY_IsFunctionVararg(self) + + @property + def elements(self): + """ + Returns iterator over enclosing types + """ + if self.is_pointer and opaque_pointers_enabled: + raise ValueError("Type {} doesn't contain elements.".format(self)) + return _TypeListIterator(ffi.lib.LLVMPY_ElementIter(self)) + + # FIXME: Remove me once typed pointers support is removed. + @property + def element_type(self): + """ + Returns the pointed-to type. When the type is not a pointer, + raises exception. + """ + if not self.is_pointer: + raise ValueError("Type {} is not a pointer".format(self)) + return TypeRef(ffi.lib.LLVMPY_GetElementType(self)) + + @property + def element_count(self): + """ + Returns the number of elements in an array or a vector. For scalable + vectors, returns minimum number of elements. When the type is neither + an array nor a vector, raises exception. + """ + if not self.is_array and not self.is_vector: + raise ValueError("Type {} is not an array nor vector".format(self)) + return ffi.lib.LLVMPY_GetTypeElementCount(self) + + @property + def type_width(self): + """ + Return the basic size of this type if it is a primitive type. These are + fixed by LLVM and are not target-dependent. + This will return zero if the type does not have a size or is not a + primitive type. + + If this is a scalable vector type, the scalable property will be set and + the runtime size will be a positive integer multiple of the base size. + + Note that this may not reflect the size of memory allocated for an + instance of the type or the number of bytes that are written when an + instance of the type is stored to memory. + """ + return ffi.lib.LLVMPY_GetTypeBitWidth(self) + + @property + def type_kind(self): + """ + Returns the LLVMTypeKind enumeration of this type. + """ + return TypeKind(ffi.lib.LLVMPY_GetTypeKind(self)) + + @property + def is_packed_struct(self): + return ffi.lib.LLVMPY_IsPackedStruct(self) + + @property + def is_literal_struct(self): + return ffi.lib.LLVMPY_IsLiteralStruct(self) + + @property + def is_opaque_struct(self): + return ffi.lib.LLVMPY_IsOpaqueStruct(self) + + def get_function_parameters(self) -> tuple["TypeRef"]: + nparams = ffi.lib.LLVMPY_CountParamTypes(self) + if nparams > 0: + out_buffer = (ffi.LLVMTypeRef * nparams)(None) + ffi.lib.LLVMPY_GetParamTypes(self, out_buffer) + return tuple(map(TypeRef, out_buffer)) + else: + return () + + def get_function_return(self) -> "TypeRef": + return TypeRef(ffi.lib.LLVMPY_GetReturnType(self)) + + def as_ir(self, ir_ctx: ir.Context) -> ir.Type: + """Convert into a ``llvmlite.ir.Type``. + """ + try: + cls = _TypeKindToIRType[self.type_kind] + except KeyError: + msg = f"as_ir() unsupported for TypeRef of {self.type_kind}" + raise TypeError(msg) + else: + return cls.from_llvm(self, ir_ctx) + + def __str__(self): + return ffi.ret_string(ffi.lib.LLVMPY_PrintType(self)) + + +class _TypeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _TypeListIterator(_TypeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeElementIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ElementIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_PrintType.restype = c_void_p + +# FIXME: Remove me once typed pointers support is removed. +ffi.lib.LLVMPY_GetElementType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetElementType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_TypeIsPointer.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsPointer.restype = c_bool + +ffi.lib.LLVMPY_TypeIsArray.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsArray.restype = c_bool + +ffi.lib.LLVMPY_TypeIsVector.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsVector.restype = c_bool + +ffi.lib.LLVMPY_TypeIsStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsStruct.restype = c_bool + +ffi.lib.LLVMPY_TypeIsFunction.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsFunction.restype = c_bool + +ffi.lib.LLVMPY_IsPackedStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsPackedStruct.restype = c_bool + +ffi.lib.LLVMPY_IsOpaqueStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsOpaqueStruct.restype = c_bool + +ffi.lib.LLVMPY_IsLiteralStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsLiteralStruct.restype = c_bool + +ffi.lib.LLVMPY_GetReturnType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetReturnType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CountParamTypes.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_CountParamTypes.restype = c_uint + +ffi.lib.LLVMPY_GetParamTypes.argtypes = [ffi.LLVMTypeRef, + POINTER(ffi.LLVMTypeRef)] +ffi.lib.LLVMPY_GetParamTypes.restype = None + +ffi.lib.LLVMPY_IsFunctionVararg.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsFunctionVararg.restype = c_bool + +ffi.lib.LLVMPY_GetTypeKind.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeKind.restype = c_int + +ffi.lib.LLVMPY_GetTypeElementCount.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeElementCount.restype = c_int + +ffi.lib.LLVMPY_GetTypeBitWidth.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeBitWidth.restype = c_uint64 + +ffi.lib.LLVMPY_ElementIter.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ElementIter.restype = ffi.LLVMElementIterator + +ffi.lib.LLVMPY_ElementIterNext.argtypes = [ffi.LLVMElementIterator] +ffi.lib.LLVMPY_ElementIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_DisposeElementIter.argtypes = [ffi.LLVMElementIterator] diff --git a/python_embeded/Lib/site-packages/llvmlite/binding/value.py b/python_embeded/Lib/site-packages/llvmlite/binding/value.py new file mode 100644 index 0000000000000000000000000000000000000000..59102ec4f24b07e6fd63a0568396d57c98580ef2 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/binding/value.py @@ -0,0 +1,632 @@ +from ctypes import (POINTER, byref, cast, c_char_p, c_double, c_int, c_size_t, + c_uint, c_uint64, c_bool, c_void_p) +import enum + +from llvmlite.binding import ffi +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.typeref import TypeRef + + +class Linkage(enum.IntEnum): + # The LLVMLinkage enum from llvm-c/Core.h + + external = 0 + available_externally = 1 + linkonce_any = 2 + linkonce_odr = 3 + linkonce_odr_autohide = 4 + weak_any = 5 + weak_odr = 6 + appending = 7 + internal = 8 + private = 9 + dllimport = 10 + dllexport = 11 + external_weak = 12 + ghost = 13 + common = 14 + linker_private = 15 + linker_private_weak = 16 + + +class Visibility(enum.IntEnum): + # The LLVMVisibility enum from llvm-c/Core.h + + default = 0 + hidden = 1 + protected = 2 + + +class StorageClass(enum.IntEnum): + # The LLVMDLLStorageClass enum from llvm-c/Core.h + + default = 0 + dllimport = 1 + dllexport = 2 + + +class ValueKind(enum.IntEnum): + # The LLVMValueKind enum from llvm-c/Core.h + + argument = 0 + basic_block = 1 + memory_use = 2 + memory_def = 3 + memory_phi = 4 + + function = 5 + global_alias = 6 + global_ifunc = 7 + global_variable = 8 + block_address = 9 + constant_expr = 10 + constant_array = 11 + constant_struct = 12 + constant_vector = 13 + + undef_value = 14 + constant_aggregate_zero = 15 + constant_data_array = 16 + constant_data_vector = 17 + constant_int = 18 + constant_fp = 19 + constant_pointer_null = 20 + constant_token_none = 21 + + metadata_as_value = 22 + inline_asm = 23 + + instruction = 24 + poison_value = 25 + + +class ValueRef(ffi.ObjectRef): + """A weak reference to a LLVM value. + """ + + def __init__(self, ptr, kind, parents): + self._kind = kind + self._parents = parents + ffi.ObjectRef.__init__(self, ptr) + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintValueToString(self, outstr) + return str(outstr) + + @property + def module(self): + """ + The module this function or global variable value was obtained from. + """ + return self._parents.get('module') + + @property + def function(self): + """ + The function this argument or basic block value was obtained from. + """ + return self._parents.get('function') + + @property + def block(self): + """ + The block this instruction value was obtained from. + """ + return self._parents.get('block') + + @property + def instruction(self): + """ + The instruction this operand value was obtained from. + """ + return self._parents.get('instruction') + + @property + def is_global(self): + return self._kind == 'global' + + @property + def is_function(self): + return self._kind == 'function' + + @property + def is_block(self): + return self._kind == 'block' + + @property + def is_argument(self): + return self._kind == 'argument' + + @property + def is_instruction(self): + return self._kind == 'instruction' + + @property + def is_operand(self): + return self._kind == 'operand' + + @property + def is_constant(self): + return bool(ffi.lib.LLVMPY_IsConstant(self)) + + @property + def value_kind(self): + return ValueKind(ffi.lib.LLVMPY_GetValueKind(self)) + + @property + def name(self): + return _decode_string(ffi.lib.LLVMPY_GetValueName(self)) + + @name.setter + def name(self, val): + ffi.lib.LLVMPY_SetValueName(self, _encode_string(val)) + + @property + def linkage(self): + return Linkage(ffi.lib.LLVMPY_GetLinkage(self)) + + @linkage.setter + def linkage(self, value): + if not isinstance(value, Linkage): + value = Linkage[value] + ffi.lib.LLVMPY_SetLinkage(self, value) + + @property + def visibility(self): + return Visibility(ffi.lib.LLVMPY_GetVisibility(self)) + + @visibility.setter + def visibility(self, value): + if not isinstance(value, Visibility): + value = Visibility[value] + ffi.lib.LLVMPY_SetVisibility(self, value) + + @property + def storage_class(self): + return StorageClass(ffi.lib.LLVMPY_GetDLLStorageClass(self)) + + @storage_class.setter + def storage_class(self, value): + if not isinstance(value, StorageClass): + value = StorageClass[value] + ffi.lib.LLVMPY_SetDLLStorageClass(self, value) + + def add_function_attribute(self, attr): + """Only works on function value + + Parameters + ----------- + attr : str + attribute name + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + attrname = str(attr) + attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName( + _encode_string(attrname), len(attrname)) + if attrval == 0: + raise ValueError('no such attribute {!r}'.format(attrname)) + ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) + + @property + def type(self): + """ + This value's LLVM type. + """ + # XXX what does this return? + return TypeRef(ffi.lib.LLVMPY_TypeOf(self)) + + @property + def global_value_type(self): + """ + Uses ``LLVMGlobalGetValueType()``. + Needed for opaque pointers in globals. + > For globals, use getValueType(). + See https://llvm.org/docs/OpaquePointers.html#migration-instructions + """ + assert self.is_global or self.is_function + return TypeRef(ffi.lib.LLVMPY_GlobalGetValueType(self)) + + @property + def is_declaration(self): + """ + Whether this value (presumably global) is defined in the current + module. + """ + if not (self.is_global or self.is_function): + raise ValueError('expected global or function value, got %s' + % (self._kind,)) + return ffi.lib.LLVMPY_IsDeclaration(self) + + @property + def attributes(self): + """ + Return an iterator over this value's attributes. + The iterator will yield a string for each attribute. + """ + itr = iter(()) + if self.is_function: + it = ffi.lib.LLVMPY_FunctionAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_instruction: + if self.opcode == 'call': + it = ffi.lib.LLVMPY_CallInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.opcode == 'invoke': + it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_global: + it = ffi.lib.LLVMPY_GlobalAttributesIter(self) + itr = _AttributeSetIterator(it) + elif self.is_argument: + it = ffi.lib.LLVMPY_ArgumentAttributesIter(self) + itr = _AttributeSetIterator(it) + return itr + + @property + def blocks(self): + """ + Return an iterator over this function's blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionBlocksIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _BlocksIterator(it, parents) + + @property + def arguments(self): + """ + Return an iterator over this function's arguments. + The iterator will yield a ValueRef for each argument. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionArgumentsIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _ArgumentsIterator(it, parents) + + @property + def instructions(self): + """ + Return an iterator over this block's instructions. + The iterator will yield a ValueRef for each instruction. + """ + if not self.is_block: + raise ValueError('expected block value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_BlockInstructionsIter(self) + parents = self._parents.copy() + parents.update(block=self) + return _InstructionsIterator(it, parents) + + @property + def operands(self): + """ + Return an iterator over this instruction's operands. + The iterator will yield a ValueRef for each operand. + """ + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_InstructionOperandsIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _OperandsIterator(it, parents) + + @property + def opcode(self): + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + return ffi.ret_string(ffi.lib.LLVMPY_GetOpcodeName(self)) + + @property + def incoming_blocks(self): + """ + Return an iterator over this phi instruction's incoming blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_instruction or self.opcode != 'phi': + raise ValueError('expected phi instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_PhiIncomingBlocksIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _IncomingBlocksIterator(it, parents) + + def get_constant_value(self, signed_int=False, round_fp=False): + """ + Return the constant value, either as a literal (when supported) + or as a string. + + Parameters + ----------- + signed_int : bool + if True and the constant is an integer, returns a signed version + round_fp : bool + if True and the constant is a floating point value, rounds the + result upon accuracy loss (e.g., when querying an fp128 value). + By default, raises an exception on accuracy loss + """ + if not self.is_constant: + raise ValueError('expected constant value, got %s' + % (self._kind,)) + + if self.value_kind == ValueKind.constant_int: + # Python integers are also arbitrary-precision + little_endian = c_bool(False) + words = ffi.lib.LLVMPY_GetConstantIntNumWords(self) + ptr = ffi.lib.LLVMPY_GetConstantIntRawValue( + self, byref(little_endian)) + asbytes = bytes(cast(ptr, POINTER(c_uint64 * words)).contents) + return int.from_bytes( + asbytes, + ('little' if little_endian.value else 'big'), + signed=signed_int, + ) + elif self.value_kind == ValueKind.constant_fp: + # Convert floating-point values to double-precision (Python float) + accuracy_loss = c_bool(False) + value = ffi.lib.LLVMPY_GetConstantFPValue(self, + byref(accuracy_loss)) + if accuracy_loss.value and not round_fp: + raise ValueError( + 'Accuracy loss encountered in conversion of constant ' + f'value {str(self)}') + + return value + + # Otherwise, return the IR string + return str(self) + + +class _ValueIterator(ffi.ObjectRef): + + kind = None # derived classes must specify the Value kind value + # as class attribute + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + # Keep parent objects (module, function, etc) alive + self._parents = parents + if self.kind is None: + raise NotImplementedError('%s must specify kind attribute' + % (type(self).__name__,)) + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return vp + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeListIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeListIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeListIterNext(self)) + + +class _AttributeSetIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeSetIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeSetIterNext(self)) + + +class _BlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_BlocksIterNext(self) + + +class _ArgumentsIterator(_ValueIterator): + + kind = 'argument' + + def _dispose(self): + self._capi.LLVMPY_DisposeArgumentsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ArgumentsIterNext(self) + + +class _InstructionsIterator(_ValueIterator): + + kind = 'instruction' + + def _dispose(self): + self._capi.LLVMPY_DisposeInstructionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_InstructionsIterNext(self) + + +class _OperandsIterator(_ValueIterator): + + kind = 'operand' + + def _dispose(self): + self._capi.LLVMPY_DisposeOperandsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_OperandsIterNext(self) + + +class _IncomingBlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeIncomingBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_IncomingBlocksIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintValueToString.argtypes = [ + ffi.LLVMValueRef, + POINTER(c_char_p) +] + +ffi.lib.LLVMPY_GetGlobalParent.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetGlobalParent.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetValueName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueName.restype = c_char_p + +ffi.lib.LLVMPY_SetValueName.argtypes = [ffi.LLVMValueRef, c_char_p] + +ffi.lib.LLVMPY_TypeOf.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_TypeOf.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_GlobalGetValueType.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GlobalGetValueType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_GetTypeName.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeName.restype = c_void_p + +ffi.lib.LLVMPY_GetLinkage.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetLinkage.restype = c_int + +ffi.lib.LLVMPY_SetLinkage.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetVisibility.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetVisibility.restype = c_int + +ffi.lib.LLVMPY_SetVisibility.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetDLLStorageClass.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetDLLStorageClass.restype = c_int + +ffi.lib.LLVMPY_SetDLLStorageClass.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetEnumAttributeKindForName.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_GetEnumAttributeKindForName.restype = c_uint + +ffi.lib.LLVMPY_AddFunctionAttr.argtypes = [ffi.LLVMValueRef, c_uint] + +ffi.lib.LLVMPY_IsDeclaration.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsDeclaration.restype = c_int + +ffi.lib.LLVMPY_FunctionAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_CallInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_CallInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_InvokeInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InvokeInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_GlobalAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GlobalAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_ArgumentAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_ArgumentAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_FunctionBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionBlocksIter.restype = ffi.LLVMBlocksIterator + +ffi.lib.LLVMPY_FunctionArgumentsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionArgumentsIter.restype = ffi.LLVMArgumentsIterator + +ffi.lib.LLVMPY_BlockInstructionsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_BlockInstructionsIter.restype = ffi.LLVMInstructionsIterator + +ffi.lib.LLVMPY_InstructionOperandsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InstructionOperandsIter.restype = ffi.LLVMOperandsIterator + +ffi.lib.LLVMPY_PhiIncomingBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_PhiIncomingBlocksIter.restype = ffi.LLVMIncomingBlocksIterator + +ffi.lib.LLVMPY_DisposeAttributeListIter.argtypes = [ + ffi.LLVMAttributeListIterator] + +ffi.lib.LLVMPY_DisposeAttributeSetIter.argtypes = [ffi.LLVMAttributeSetIterator] + +ffi.lib.LLVMPY_DisposeBlocksIter.argtypes = [ffi.LLVMBlocksIterator] + +ffi.lib.LLVMPY_DisposeInstructionsIter.argtypes = [ffi.LLVMInstructionsIterator] + +ffi.lib.LLVMPY_DisposeOperandsIter.argtypes = [ffi.LLVMOperandsIterator] + +ffi.lib.LLVMPY_DisposeIncomingBlocksIter.argtypes = [ + ffi.LLVMIncomingBlocksIterator] + +ffi.lib.LLVMPY_AttributeListIterNext.argtypes = [ffi.LLVMAttributeListIterator] +ffi.lib.LLVMPY_AttributeListIterNext.restype = c_void_p + +ffi.lib.LLVMPY_AttributeSetIterNext.argtypes = [ffi.LLVMAttributeSetIterator] +ffi.lib.LLVMPY_AttributeSetIterNext.restype = c_void_p + +ffi.lib.LLVMPY_BlocksIterNext.argtypes = [ffi.LLVMBlocksIterator] +ffi.lib.LLVMPY_BlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ArgumentsIterNext.argtypes = [ffi.LLVMArgumentsIterator] +ffi.lib.LLVMPY_ArgumentsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_InstructionsIterNext.argtypes = [ffi.LLVMInstructionsIterator] +ffi.lib.LLVMPY_InstructionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_OperandsIterNext.argtypes = [ffi.LLVMOperandsIterator] +ffi.lib.LLVMPY_OperandsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_IncomingBlocksIterNext.argtypes = [ + ffi.LLVMIncomingBlocksIterator] +ffi.lib.LLVMPY_IncomingBlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetOpcodeName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetOpcodeName.restype = c_void_p + +ffi.lib.LLVMPY_IsConstant.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsConstant.restype = c_bool + +ffi.lib.LLVMPY_GetValueKind.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueKind.restype = c_int + +ffi.lib.LLVMPY_GetConstantIntRawValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantIntRawValue.restype = POINTER(c_uint64) + +ffi.lib.LLVMPY_GetConstantIntNumWords.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetConstantIntNumWords.restype = c_uint + +ffi.lib.LLVMPY_GetConstantFPValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantFPValue.restype = c_double diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/__init__.py b/python_embeded/Lib/site-packages/llvmlite/ir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9a5cbf607fa809cbdc83b36d643855b88c1bfb --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/__init__.py @@ -0,0 +1,11 @@ +""" +This subpackage implements the LLVM IR classes in pure python +""" + +from .types import * +from .values import * +from .module import * +from .builder import * +from .instructions import * +from .transforms import * +from .context import Context, global_context diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/_utils.py b/python_embeded/Lib/site-packages/llvmlite/ir/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ec69d552d4ecda13dbac1c297077dcd4fbdfa40e --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/_utils.py @@ -0,0 +1,80 @@ +from collections import defaultdict + + +class DuplicatedNameError(NameError): + pass + + +class NameScope(object): + def __init__(self): + self._useset = set(['']) + self._basenamemap = defaultdict(int) + + def is_used(self, name): + return name in self._useset + + def register(self, name, deduplicate=False): + if deduplicate: + name = self.deduplicate(name) + elif self.is_used(name): + raise DuplicatedNameError(name) + self._useset.add(name) + return name + + def deduplicate(self, name): + basename = name + while self.is_used(name): + ident = self._basenamemap[basename] + 1 + self._basenamemap[basename] = ident + name = "{0}.{1}".format(basename, ident) + return name + + def get_child(self): + return type(self)(parent=self) + + +class _StrCaching(object): + + def _clear_string_cache(self): + try: + del self.__cached_str + except AttributeError: + pass + + def __str__(self): + try: + return self.__cached_str + except AttributeError: + s = self.__cached_str = self._to_string() + return s + + +class _StringReferenceCaching(object): + + def get_reference(self): + try: + return self.__cached_refstr + except AttributeError: + s = self.__cached_refstr = self._get_reference() + return s + + +class _HasMetadata(object): + + def set_metadata(self, name, node): + """ + Attach unnamed metadata *node* to the metadata slot *name* of this + value. + """ + self.metadata[name] = node + + def _stringify_metadata(self, leading_comma=False): + if self.metadata: + buf = [] + if leading_comma: + buf.append("") + buf += ["!{0} {1}".format(k, v.get_reference()) + for k, v in self.metadata.items()] + return ', '.join(buf) + else: + return '' diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/builder.py b/python_embeded/Lib/site-packages/llvmlite/ir/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a32a23f0a485bf6a95c86ffb4dd37e7e7e56e77b --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/builder.py @@ -0,0 +1,1120 @@ +import contextlib +import functools + +from llvmlite.ir import instructions, types, values + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _unop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, arg, name='', flags=()): + instr = cls(self.block, arg.type, opname, [arg], name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name='', flags=()): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + instr = cls(self.block, lhs.type, opname, (lhs, rhs), name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop_with_overflow(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name=''): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + ty = lhs.type + if not isinstance(ty, types.IntType): + raise TypeError("expected an integer type, got %s" % (ty,)) + bool_ty = types.IntType(1) + + mod = self.module + fnty = types.FunctionType(types.LiteralStructType([ty, bool_ty]), + [ty, ty]) + fn = mod.declare_intrinsic("llvm.%s.with.overflow" % (opname,), + [ty], fnty) + ret = self.call(fn, [lhs, rhs], name=name) + return ret + + return wrapped + + return wrap + + +def _uniop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + instr = cls(self.block, operand.type, opname, [operand], name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _uniop_intrinsic_int(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_float(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance( + operand.type, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_with_flag(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, flag, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + if not (isinstance(flag.type, types.IntType) and + flag.type.width == 1): + raise TypeError("expected an i1 type, got %s" % flag.type) + fn = self.module.declare_intrinsic( + opname, [operand.type, flag.type]) + return self.call(fn, [operand, flag], name) + + return wrapped + + return wrap + + +def _triop_intrinsic(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, a, b, c, name=''): + if a.type != b.type or b.type != c.type: + raise TypeError( + "expected types to be the same, got %s, %s, %s" % ( + a.type, + b.type, + c.type)) + elif not isinstance( + a.type, + (types.HalfType, types.FloatType, types.DoubleType)): + raise TypeError( + "expected an floating point type, got %s" % + a.type) + fn = self.module.declare_intrinsic(opname, [a.type, b.type, c.type]) + return self.call(fn, [a, b, c], name) + + return wrapped + + return wrap + + +def _castop(opname, cls=instructions.CastInstr): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, val, typ, name=''): + if val.type == typ: + return val + instr = cls(self.block, opname, val, typ, name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _label_suffix(label, suffix): + """Returns (label + suffix) or a truncated version if it's too long. + Parameters + ---------- + label : str + Label name + suffix : str + Label suffix + """ + if len(label) > 50: + nhead = 25 + return ''.join([label[:nhead], '..', suffix]) + else: + return label + suffix + + +class IRBuilder(object): + def __init__(self, block=None): + self._block = block + self._anchor = len(block.instructions) if block else 0 + self.debug_metadata = None + + @property + def block(self): + """ + The current basic block. + """ + return self._block + + basic_block = block + + @property + def function(self): + """ + The current function. + """ + return self.block.parent + + @property + def module(self): + """ + The current module. + """ + return self.block.parent.module + + def position_before(self, instr): + """ + Position immediately before the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + + def position_after(self, instr): + """ + Position immediately after the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + 1 + + def position_at_start(self, block): + """ + Position at the start of the basic *block*. + """ + self._block = block + self._anchor = 0 + + def position_at_end(self, block): + """ + Position at the end of the basic *block*. + """ + self._block = block + self._anchor = len(block.instructions) + + def append_basic_block(self, name=''): + """ + Append a basic block, with the given optional *name*, to the current + function. The current block is not changed. The new block is returned. + """ + return self.function.append_basic_block(name) + + def remove(self, instr): + """Remove the given instruction.""" + idx = self._block.instructions.index(instr) + del self._block.instructions[idx] + if self._block.terminator == instr: + self._block.terminator = None + if self._anchor > idx: + self._anchor -= 1 + + @contextlib.contextmanager + def goto_block(self, block): + """ + A context manager which temporarily positions the builder at the end + of basic block *bb* (but before any terminator). + """ + old_block = self.basic_block + term = block.terminator + if term is not None: + self.position_before(term) + else: + self.position_at_end(block) + try: + yield + finally: + self.position_at_end(old_block) + + @contextlib.contextmanager + def goto_entry_block(self): + """ + A context manager which temporarily positions the builder at the + end of the function's entry block. + """ + with self.goto_block(self.function.entry_basic_block): + yield + + @contextlib.contextmanager + def _branch_helper(self, bbenter, bbexit): + self.position_at_end(bbenter) + yield bbexit + if self.basic_block.terminator is None: + self.branch(bbexit) + + @contextlib.contextmanager + def if_then(self, pred, likely=None): + """ + A context manager which sets up a conditional basic block based + on the given predicate (a i1 value). If the conditional block + is not explicitly terminated, a branch will be added to the next + block. + If *likely* is given, its boolean value indicates whether the + predicate is likely to be true or not, and metadata is issued + for LLVM's optimizers to account for that. + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbend) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + with self._branch_helper(bbif, bbend): + yield bbend + + self.position_at_end(bbend) + + @contextlib.contextmanager + def if_else(self, pred, likely=None): + """ + A context manager which sets up two conditional basic blocks based + on the given predicate (a i1 value). + A tuple of context managers is yield'ed. Each context manager + acts as a if_then() block. + *likely* has the same meaning as in if_then(). + + Typical use:: + with builder.if_else(pred) as (then, otherwise): + with then: + # emit instructions for when the predicate is true + with otherwise: + # emit instructions for when the predicate is false + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbelse = self.append_basic_block(name=_label_suffix(bb.name, '.else')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbelse) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + then = self._branch_helper(bbif, bbend) + otherwise = self._branch_helper(bbelse, bbend) + + yield then, otherwise + + self.position_at_end(bbend) + + def _insert(self, instr): + if self.debug_metadata is not None and 'dbg' not in instr.metadata: + instr.metadata['dbg'] = self.debug_metadata + self._block.instructions.insert(self._anchor, instr) + self._anchor += 1 + + def _set_terminator(self, term): + assert not self.block.is_terminated + self._insert(term) + self.block.terminator = term + return term + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, lhs, rhs, name=''): + """ + Left integer shift: + name = lhs << rhs + """ + + @_binop('lshr') + def lshr(self, lhs, rhs, name=''): + """ + Logical (unsigned) right integer shift: + name = lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, lhs, rhs, name=''): + """ + Arithmetic (signed) right integer shift: + name = lhs >> rhs + """ + + @_binop('add') + def add(self, lhs, rhs, name=''): + """ + Integer addition: + name = lhs + rhs + """ + + @_binop('fadd') + def fadd(self, lhs, rhs, name=''): + """ + Floating-point addition: + name = lhs + rhs + """ + + @_binop('sub') + def sub(self, lhs, rhs, name=''): + """ + Integer subtraction: + name = lhs - rhs + """ + + @_binop('fsub') + def fsub(self, lhs, rhs, name=''): + """ + Floating-point subtraction: + name = lhs - rhs + """ + + @_binop('mul') + def mul(self, lhs, rhs, name=''): + """ + Integer multiplication: + name = lhs * rhs + """ + + @_binop('fmul') + def fmul(self, lhs, rhs, name=''): + """ + Floating-point multiplication: + name = lhs * rhs + """ + + @_binop('udiv') + def udiv(self, lhs, rhs, name=''): + """ + Unsigned integer division: + name = lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, lhs, rhs, name=''): + """ + Signed integer division: + name = lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, lhs, rhs, name=''): + """ + Floating-point division: + name = lhs / rhs + """ + + @_binop('urem') + def urem(self, lhs, rhs, name=''): + """ + Unsigned integer remainder: + name = lhs % rhs + """ + + @_binop('srem') + def srem(self, lhs, rhs, name=''): + """ + Signed integer remainder: + name = lhs % rhs + """ + + @_binop('frem') + def frem(self, lhs, rhs, name=''): + """ + Floating-point remainder: + name = lhs % rhs + """ + + @_binop('or') + def or_(self, lhs, rhs, name=''): + """ + Bitwise integer OR: + name = lhs | rhs + """ + + @_binop('and') + def and_(self, lhs, rhs, name=''): + """ + Bitwise integer AND: + name = lhs & rhs + """ + + @_binop('xor') + def xor(self, lhs, rhs, name=''): + """ + Bitwise integer XOR: + name = lhs ^ rhs + """ + + @_binop_with_overflow('sadd') + def sadd_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('smul') + def smul_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('ssub') + def ssub_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + @_binop_with_overflow('uadd') + def uadd_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('umul') + def umul_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('usub') + def usub_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + # + # Unary APIs + # + + def not_(self, value, name=''): + """ + Bitwise integer complement: + name = ~value + """ + if isinstance(value.type, types.VectorType): + rhs = values.Constant(value.type, (-1,) * value.type.count) + else: + rhs = values.Constant(value.type, -1) + return self.xor(value, rhs, name=name) + + def neg(self, value, name=''): + """ + Integer negative: + name = -value + """ + return self.sub(values.Constant(value.type, 0), value, name=name) + + @_unop('fneg') + def fneg(self, arg, name='', flags=()): + """ + Floating-point negative: + name = -arg + """ + + # + # Comparison APIs + # + + def _icmp(self, prefix, cmpop, lhs, rhs, name): + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for icmp" % (cmpop,)) + if cmpop not in ('==', '!='): + op = prefix + op + instr = instructions.ICMPInstr(self.block, op, lhs, rhs, name=name) + self._insert(instr) + return instr + + def icmp_signed(self, cmpop, lhs, rhs, name=''): + """ + Signed integer comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('s', cmpop, lhs, rhs, name) + + def icmp_unsigned(self, cmpop, lhs, rhs, name=''): + """ + Unsigned integer (or pointer) comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('u', cmpop, lhs, rhs, name) + + def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point ordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'o' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def fcmp_unordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point unordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'u' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def select(self, cond, lhs, rhs, name='', flags=()): + """ + Ternary select operator: + name = cond ? lhs : rhs + """ + instr = instructions.SelectInstr(self.block, cond, lhs, rhs, name=name, + flags=flags) + self._insert(instr) + return instr + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, value, typ, name=''): + """ + Truncating integer downcast to a smaller type: + name = (typ) value + """ + + @_castop('zext') + def zext(self, value, typ, name=''): + """ + Zero-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('sext') + def sext(self, value, typ, name=''): + """ + Sign-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('fptrunc') + def fptrunc(self, value, typ, name=''): + """ + Floating-point downcast to a less precise type: + name = (typ) value + """ + + @_castop('fpext') + def fpext(self, value, typ, name=''): + """ + Floating-point upcast to a more precise type: + name = (typ) value + """ + + @_castop('bitcast') + def bitcast(self, value, typ, name=''): + """ + Pointer cast to a different pointer type: + name = (typ) value + """ + + @_castop('addrspacecast') + def addrspacecast(self, value, typ, name=''): + """ + Pointer cast to a different address space: + name = (typ) value + """ + + @_castop('fptoui') + def fptoui(self, value, typ, name=''): + """ + Convert floating-point to unsigned integer: + name = (typ) value + """ + + @_castop('uitofp') + def uitofp(self, value, typ, name=''): + """ + Convert unsigned integer to floating-point: + name = (typ) value + """ + + @_castop('fptosi') + def fptosi(self, value, typ, name=''): + """ + Convert floating-point to signed integer: + name = (typ) value + """ + + @_castop('sitofp') + def sitofp(self, value, typ, name=''): + """ + Convert signed integer to floating-point: + name = (typ) value + """ + + @_castop('ptrtoint') + def ptrtoint(self, value, typ, name=''): + """ + Cast pointer to integer: + name = (typ) value + """ + + @_castop('inttoptr') + def inttoptr(self, value, typ, name=''): + """ + Cast integer to pointer: + name = (typ) value + """ + + # + # Memory APIs + # + + def alloca(self, typ, size=None, name=''): + """ + Stack-allocate a slot for *size* elements of the given type. + (default one element) + """ + if size is None: + pass + elif isinstance(size, (values.Value, values.Constant)): + assert isinstance(size.type, types.IntType) + else: + # If it is not a Value instance, + # assume to be a Python integer. + size = values.Constant(types.IntType(32), size) + + al = instructions.AllocaInstr(self.block, typ, size, name) + self._insert(al) + return al + + def load(self, ptr, name='', align=None, typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadInstr(self.block, ptr, name, typ=typ) + ld.align = align + self._insert(ld) + return ld + + def store(self, value, ptr, align=None): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if not ptr.type.is_opaque and ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreInstr(self.block, value, ptr) + st.align = align + self._insert(st) + return st + + def load_atomic(self, ptr, ordering, align, name='', typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadAtomicInstr( + self.block, ptr, ordering, align, name, typ=typ) + self._insert(ld) + return ld + + def store_atomic(self, value, ptr, ordering, align): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreAtomicInstr( + self.block, value, ptr, ordering, align) + self._insert(st) + return st + + # + # Terminators APIs + # + + def switch(self, value, default): + """ + Create a switch-case with a single *default* target. + """ + swt = instructions.SwitchInstr(self.block, 'switch', value, default) + self._set_terminator(swt) + return swt + + def branch(self, target): + """ + Unconditional branch to *target*. + """ + br = instructions.Branch(self.block, "br", [target]) + self._set_terminator(br) + return br + + def cbranch(self, cond, truebr, falsebr): + """ + Conditional branch to *truebr* if *cond* is true, else to *falsebr*. + """ + br = instructions.ConditionalBranch(self.block, "br", + [cond, truebr, falsebr]) + self._set_terminator(br) + return br + + def branch_indirect(self, addr): + """ + Indirect branch to target *addr*. + """ + br = instructions.IndirectBranch(self.block, "indirectbr", addr) + self._set_terminator(br) + return br + + def ret_void(self): + """ + Return from function without a value. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret void")) + + def ret(self, value): + """ + Return from function with the given *value*. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret", value)) + + def resume(self, landingpad): + """ + Resume an in-flight exception. + """ + br = instructions.Branch(self.block, "resume", [landingpad]) + self._set_terminator(br) + return br + + # Call APIs + + def call(self, fn, args, name='', cconv=None, tail=False, fastmath=(), + attrs=(), arg_attrs=None): + """ + Call function *fn* with *args*: + name = fn(args...) + """ + inst = instructions.CallInstr(self.block, fn, args, name=name, + cconv=cconv, tail=tail, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self._insert(inst) + return inst + + def asm(self, ftype, asm, constraint, args, side_effect, name=''): + """ + Inline assembler. + """ + asm = instructions.InlineAsm(ftype, asm, constraint, side_effect) + return self.call(asm, args, name) + + def load_reg(self, reg_type, reg_name, name=''): + """ + Load a register value into an LLVM value. + Example: v = load_reg(IntType(32), "eax") + """ + ftype = types.FunctionType(reg_type, []) + return self.asm(ftype, "", "={%s}" % reg_name, [], False, name) + + def store_reg(self, value, reg_type, reg_name, name=''): + """ + Store an LLVM value inside a register + Example: + store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax") + """ + ftype = types.FunctionType(types.VoidType(), [reg_type]) + return self.asm(ftype, "", "{%s}" % reg_name, [value], True, name) + + def invoke(self, fn, args, normal_to, unwind_to, + name='', cconv=None, fastmath=(), attrs=(), arg_attrs=None): + inst = instructions.InvokeInstr(self.block, fn, args, normal_to, + unwind_to, name=name, cconv=cconv, + fastmath=fastmath, attrs=attrs, + arg_attrs=arg_attrs) + self._set_terminator(inst) + return inst + + # GEP APIs + + def gep(self, ptr, indices, inbounds=False, name='', source_etype=None): + """ + Compute effective address (getelementptr): + name = getelementptr ptr, + """ + instr = instructions.GEPInstr(self.block, ptr, indices, + inbounds=inbounds, name=name, + source_etype=source_etype) + self._insert(instr) + return instr + + # Vector Operations APIs + + def extract_element(self, vector, idx, name=''): + """ + Returns the value at position idx. + """ + instr = instructions.ExtractElement(self.block, vector, idx, name=name) + self._insert(instr) + return instr + + def insert_element(self, vector, value, idx, name=''): + """ + Returns vector with vector[idx] replaced by value. + The result is undefined if the idx is larger or equal the vector length. + """ + instr = instructions.InsertElement(self.block, vector, value, idx, + name=name) + self._insert(instr) + return instr + + def shuffle_vector(self, vector1, vector2, mask, name=''): + """ + Constructs a permutation of elements from *vector1* and *vector2*. + Returns a new vector in the same length of *mask*. + + * *vector1* and *vector2* must have the same element type. + * *mask* must be a constant vector of integer types. + """ + instr = instructions.ShuffleVector(self.block, vector1, vector2, mask, + name=name) + self._insert(instr) + return instr + + # Aggregate APIs + + def extract_value(self, agg, idx, name=''): + """ + Extract member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.ExtractValue(self.block, agg, idx, name=name) + self._insert(instr) + return instr + + def insert_value(self, agg, value, idx, name=''): + """ + Insert *value* into member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.InsertValue(self.block, agg, value, idx, name=name) + self._insert(instr) + return instr + + # PHI APIs + + def phi(self, typ, name='', flags=()): + inst = instructions.PhiInstr(self.block, typ, name=name, flags=flags) + self._insert(inst) + return inst + + # Special API + + def unreachable(self): + inst = instructions.Unreachable(self.block) + self._set_terminator(inst) + return inst + + def atomic_rmw(self, op, ptr, val, ordering, name=''): + inst = instructions.AtomicRMW( + self.block, op, ptr, val, ordering, name=name) + self._insert(inst) + return inst + + def cmpxchg(self, ptr, cmp, val, ordering, failordering=None, name=''): + """ + Atomic compared-and-set: + atomic { + old = *ptr + success = (old == cmp) + if (success) + *ptr = val + } + name = { old, success } + + If failordering is `None`, the value of `ordering` is used. + """ + failordering = ordering if failordering is None else failordering + inst = instructions.CmpXchg(self.block, ptr, cmp, val, ordering, + failordering, name=name) + self._insert(inst) + return inst + + def landingpad(self, typ, name='', cleanup=False): + inst = instructions.LandingPadInstr(self.block, typ, name, cleanup) + self._insert(inst) + return inst + + def assume(self, cond): + """ + Optimizer hint: assume *cond* is always true. + """ + fn = self.module.declare_intrinsic("llvm.assume") + return self.call(fn, [cond]) + + def fence(self, ordering, targetscope=None, name=''): + """ + Add a memory barrier, preventing certain reorderings of load and/or + store accesses with + respect to other processors and devices. + """ + inst = instructions.Fence(self.block, ordering, targetscope, name=name) + self._insert(inst) + return inst + + def comment(self, text): + """ + Puts a single-line comment into the generated IR. This will be ignored + by LLVM, but can be useful for debugging the output of a compiler. Adds + a comment to the source file. + + * *text* is a string that does not contain new line characters. + """ + inst = instructions.Comment(self.block, text) + self._insert(inst) + return inst + + @_uniop_intrinsic_int("llvm.bswap") + def bswap(self, cond): + """ + Used to byte swap integer values with an even number of bytes (positive + multiple of 16 bits) + """ + + @_uniop_intrinsic_int("llvm.bitreverse") + def bitreverse(self, cond): + """ + Reverse the bitpattern of an integer value; for example 0b10110110 + becomes 0b01101101. + """ + + @_uniop_intrinsic_int("llvm.ctpop") + def ctpop(self, cond): + """ + Counts the number of bits set in a value. + """ + + @_uniop_intrinsic_with_flag("llvm.ctlz") + def ctlz(self, cond, flag): + """ + Counts leading zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_uniop_intrinsic_with_flag("llvm.cttz") + def cttz(self, cond, flag): + """ + Counts trailing zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_triop_intrinsic("llvm.fma") + def fma(self, a, b, c): + """ + Perform the fused multiply-add operation. + """ + + def convert_from_fp16(self, a, to=None, name=''): + """ + Convert from an i16 to the given FP type + """ + if not to: + raise TypeError("expected a float return type") + if not isinstance(to, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % to) + if not (isinstance(a.type, types.IntType) and a.type.width == 16): + raise TypeError("expected an i16 type, got %s" % a.type) + + opname = 'llvm.convert.from.fp16' + fn = self.module.declare_intrinsic(opname, [to]) + return self.call(fn, [a], name) + + @_uniop_intrinsic_float("llvm.convert.to.fp16") + def convert_to_fp16(self, a): + """ + Convert the given FP number to an i16 + """ diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/context.py b/python_embeded/Lib/site-packages/llvmlite/ir/context.py new file mode 100644 index 0000000000000000000000000000000000000000..9a20610404ee5c97694da7181d61a13077cfd0e5 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/context.py @@ -0,0 +1,20 @@ +from llvmlite.ir import _utils +from llvmlite.ir import types + + +class Context(object): + def __init__(self): + self.scope = _utils.NameScope() + self.identified_types = {} + + def get_identified_type(self, name, packed=False): + if name not in self.identified_types: + self.scope.register(name) + ty = types.IdentifiedStructType(self, name, packed) + self.identified_types[name] = ty + else: + ty = self.identified_types[name] + return ty + + +global_context = Context() diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/instructions.py b/python_embeded/Lib/site-packages/llvmlite/ir/instructions.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0388bbd0e798f024dc48b44a97894fc3422278 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/instructions.py @@ -0,0 +1,920 @@ +""" +Implementation of LLVM IR instructions. +""" + +from llvmlite.ir import types +from llvmlite.ir.values import (Block, Function, Value, NamedValue, Constant, + MetaDataArgument, MetaDataString, AttributeSet, + Undefined, ArgumentAttributes) +from llvmlite.ir._utils import _HasMetadata + + +class Instruction(NamedValue, _HasMetadata): + def __init__(self, parent, typ, opname, operands, name='', flags=()): + super(Instruction, self).__init__(parent, typ, name=name) + assert isinstance(parent, Block) + assert isinstance(flags, (tuple, list)) + self.opname = opname + self.operands = operands + self.flags = list(flags) + self.metadata = {} + + @property + def function(self): + return self.parent.function + + @property + def module(self): + return self.parent.function.module + + def descr(self, buf): + opname = self.opname + if self.flags: + opname = ' '.join([opname] + self.flags) + operands = ', '.join([op.get_reference() for op in self.operands]) + typ = self.type + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1} {2}{3}\n" + .format(opname, typ, operands, metadata)) + + def replace_usage(self, old, new): + if old in self.operands: + ops = [] + for op in self.operands: + ops.append(new if op is old else op) + self.operands = tuple(ops) + self._clear_string_cache() + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type, + self.opname, self.operands) + + +class CallInstrAttributes(AttributeSet): + _known = frozenset(['convergent', 'noreturn', 'nounwind', 'readonly', + 'readnone', 'noinline', 'alwaysinline']) + + +TailMarkerOptions = frozenset(['tail', 'musttail', 'notail']) + + +class FastMathFlags(AttributeSet): + _known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', + 'afn', 'reassoc']) + + +class CallInstr(Instruction): + def __init__(self, parent, func, args, name='', cconv=None, tail=None, + fastmath=(), attrs=(), arg_attrs=None): + self.cconv = (func.calling_convention + if cconv is None and isinstance(func, Function) + else cconv) + + # For backwards compatibility with previous API of accepting a "truthy" + # value for a hint to the optimizer to potentially tail optimize. + if isinstance(tail, str) and tail in TailMarkerOptions: + pass + elif tail: + tail = "tail" + else: + tail = "" + + self.tail = tail + self.fastmath = FastMathFlags(fastmath) + self.attributes = CallInstrAttributes(attrs) + self.arg_attributes = {} + if arg_attrs: + for idx, attrs in arg_attrs.items(): + if not (0 <= idx < len(args)): + raise ValueError("Invalid argument index {}" + .format(idx)) + self.arg_attributes[idx] = ArgumentAttributes(attrs) + + # Fix and validate arguments + args = list(args) + for i in range(len(func.function_type.args)): + arg = args[i] + expected_type = func.function_type.args[i] + if (isinstance(expected_type, types.MetaDataType) and + arg.type != expected_type): + arg = MetaDataArgument(arg) + if arg.type != expected_type: + msg = ("Type of #{0} arg mismatch: {1} != {2}" + .format(1 + i, expected_type, arg.type)) + raise TypeError(msg) + args[i] = arg + + super(CallInstr, self).__init__(parent, func.function_type.return_type, + "call", [func] + list(args), name=name) + + @property + def callee(self): + return self.operands[0] + + @callee.setter + def callee(self, newcallee): + self.operands[0] = newcallee + + @property + def args(self): + return self.operands[1:] + + def replace_callee(self, newfunc): + if newfunc.function_type != self.callee.function_type: + raise TypeError("New function has incompatible type") + self.callee = newfunc + + @property + def called_function(self): + """The callee function""" + return self.callee + + def _descr(self, buf, add_metadata): + def descr_arg(i, a): + if i in self.arg_attributes: + attrs = ' '.join(self.arg_attributes[i]._to_list(a.type)) + ' ' + else: + attrs = '' + return '{0} {1}{2}'.format(a.type, attrs, a.get_reference()) + args = ', '.join([descr_arg(i, a) for i, a in enumerate(self.args)]) + + fnty = self.callee.function_type + # Only print function type if variable-argument + if fnty.var_arg: + ty = fnty + # Otherwise, just print the return type. + else: + # Fastmath flag work only in this case + ty = fnty.return_type + callee_ref = "{0} {1}".format(ty, self.callee.get_reference()) + if self.cconv: + callee_ref = "{0} {1}".format(self.cconv, callee_ref) + + tail_marker = "" + if self.tail: + tail_marker = "{0} ".format(self.tail) + + fn_attrs = ' ' + ' '.join(self.attributes._to_list(fnty.return_type))\ + if self.attributes else '' + + fm_attrs = ' ' + ' '.join(self.fastmath._to_list(fnty.return_type))\ + if self.fastmath else '' + + buf.append("{tail}{op}{fastmath} {callee}({args}){attr}{meta}\n".format( + tail=tail_marker, + op=self.opname, + callee=callee_ref, + fastmath=fm_attrs, + args=args, + attr=fn_attrs, + meta=(self._stringify_metadata(leading_comma=True) + if add_metadata else ""), + )) + + def descr(self, buf): + self._descr(buf, add_metadata=True) + + +class InvokeInstr(CallInstr): + def __init__(self, parent, func, args, normal_to, unwind_to, name='', + cconv=None, fastmath=(), attrs=(), arg_attrs=None): + assert isinstance(normal_to, Block) + assert isinstance(unwind_to, Block) + super(InvokeInstr, self).__init__(parent, func, args, name, cconv, + tail=False, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self.opname = "invoke" + self.normal_to = normal_to + self.unwind_to = unwind_to + + def descr(self, buf): + super(InvokeInstr, self)._descr(buf, add_metadata=False) + buf.append(" to label {0} unwind label {1}{metadata}\n".format( + self.normal_to.get_reference(), + self.unwind_to.get_reference(), + metadata=self._stringify_metadata(leading_comma=True), + )) + + +class Terminator(Instruction): + def __init__(self, parent, opname, operands): + super(Terminator, self).__init__(parent, types.VoidType(), opname, + operands) + + def descr(self, buf): + opname = self.opname + operands = ', '.join(["{0} {1}".format(op.type, op.get_reference()) + for op in self.operands]) + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1}{2}".format(opname, operands, metadata)) + + +class PredictableInstr(Instruction): + + def set_weights(self, weights): + operands = [MetaDataString(self.module, "branch_weights")] + for w in weights: + if w < 0: + raise ValueError("branch weight must be a positive integer") + operands.append(Constant(types.IntType(32), w)) + md = self.module.add_metadata(operands) + self.set_metadata("prof", md) + + +class Ret(Terminator): + def __init__(self, parent, opname, return_value=None): + operands = [return_value] if return_value is not None else [] + super(Ret, self).__init__(parent, opname, operands) + + @property + def return_value(self): + if self.operands: + return self.operands[0] + else: + return None + + def descr(self, buf): + return_value = self.return_value + metadata = self._stringify_metadata(leading_comma=True) + if return_value is not None: + buf.append("{0} {1} {2}{3}\n" + .format(self.opname, return_value.type, + return_value.get_reference(), + metadata)) + else: + buf.append("{0}{1}\n".format(self.opname, metadata)) + + +class Branch(Terminator): + pass + + +class ConditionalBranch(PredictableInstr, Terminator): + pass + + +class IndirectBranch(PredictableInstr, Terminator): + def __init__(self, parent, opname, addr): + super(IndirectBranch, self).__init__(parent, opname, [addr]) + self.destinations = [] + + @property + def address(self): + return self.operands[0] + + def add_destination(self, block): + assert isinstance(block, Block) + self.destinations.append(block) + + def descr(self, buf): + destinations = ["label {0}".format(blk.get_reference()) + for blk in self.destinations] + buf.append("indirectbr {0} {1}, [{2}] {3}\n".format( + self.address.type, + self.address.get_reference(), + ', '.join(destinations), + self._stringify_metadata(leading_comma=True), + )) + + +class SwitchInstr(PredictableInstr, Terminator): + + def __init__(self, parent, opname, val, default): + super(SwitchInstr, self).__init__(parent, opname, [val]) + self.default = default + self.cases = [] + + @property + def value(self): + return self.operands[0] + + def add_case(self, val, block): + assert isinstance(block, Block) + if not isinstance(val, Value): + val = Constant(self.value.type, val) + self.cases.append((val, block)) + + def descr(self, buf): + cases = ["{0} {1}, label {2}".format(val.type, val.get_reference(), + blk.get_reference()) + for val, blk in self.cases] + buf.append("switch {0} {1}, label {2} [{3}] {4}\n".format( + self.value.type, + self.value.get_reference(), + self.default.get_reference(), + ' '.join(cases), + self._stringify_metadata(leading_comma=True), + )) + + +class Resume(Terminator): + pass + + +class SelectInstr(Instruction): + def __init__(self, parent, cond, lhs, rhs, name='', flags=()): + assert lhs.type == rhs.type + super(SelectInstr, self).__init__(parent, lhs.type, "select", + [cond, lhs, rhs], name=name, + flags=flags) + + @property + def cond(self): + return self.operands[0] + + @property + def lhs(self): + return self.operands[1] + + @property + def rhs(self): + return self.operands[2] + + def descr(self, buf): + buf.append("select {0} {1} {2}, {3} {4}, {5} {6} {7}\n".format( + ' '.join(self.flags), + self.cond.type, self.cond.get_reference(), + self.lhs.type, self.lhs.get_reference(), + self.rhs.type, self.rhs.get_reference(), + self._stringify_metadata(leading_comma=True), + )) + + +class CompareInstr(Instruction): + # Define the following in subclasses + OPNAME = 'invalid-compare' + VALID_OP = {} + + def __init__(self, parent, op, lhs, rhs, name='', flags=[]): + if op not in self.VALID_OP: + raise ValueError("invalid comparison %r for %s" % (op, self.OPNAME)) + for flag in flags: + if flag not in self.VALID_FLAG: + raise ValueError("invalid flag %r for %s" % (flag, self.OPNAME)) + opname = self.OPNAME + if isinstance(lhs.type, types.VectorType): + typ = types.VectorType(types.IntType(1), lhs.type.count) + else: + typ = types.IntType(1) + super(CompareInstr, self).__init__(parent, typ, + opname, [lhs, rhs], flags=flags, + name=name) + self.op = op + + def descr(self, buf): + buf.append("{opname}{flags} {op} {ty} {lhs}, {rhs} {meta}\n".format( + opname=self.opname, + flags=''.join(' ' + it for it in self.flags), + op=self.op, + ty=self.operands[0].type, + lhs=self.operands[0].get_reference(), + rhs=self.operands[1].get_reference(), + meta=self._stringify_metadata(leading_comma=True), + )) + + +class ICMPInstr(CompareInstr): + OPNAME = 'icmp' + VALID_OP = { + 'eq': 'equal', + 'ne': 'not equal', + 'ugt': 'unsigned greater than', + 'uge': 'unsigned greater or equal', + 'ult': 'unsigned less than', + 'ule': 'unsigned less or equal', + 'sgt': 'signed greater than', + 'sge': 'signed greater or equal', + 'slt': 'signed less than', + 'sle': 'signed less or equal', + } + VALID_FLAG = set() + + +class FCMPInstr(CompareInstr): + OPNAME = 'fcmp' + VALID_OP = { + 'false': 'no comparison, always returns false', + 'oeq': 'ordered and equal', + 'ogt': 'ordered and greater than', + 'oge': 'ordered and greater than or equal', + 'olt': 'ordered and less than', + 'ole': 'ordered and less than or equal', + 'one': 'ordered and not equal', + 'ord': 'ordered (no nans)', + 'ueq': 'unordered or equal', + 'ugt': 'unordered or greater than', + 'uge': 'unordered or greater than or equal', + 'ult': 'unordered or less than', + 'ule': 'unordered or less than or equal', + 'une': 'unordered or not equal', + 'uno': 'unordered (either nans)', + 'true': 'no comparison, always returns true', + } + VALID_FLAG = {'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc', + 'fast'} + + +class CastInstr(Instruction): + def __init__(self, parent, op, val, typ, name=''): + super(CastInstr, self).__init__(parent, typ, op, [val], name=name) + + def descr(self, buf): + buf.append("{0} {1} {2} to {3} {4}\n".format( + self.opname, + self.operands[0].type, + self.operands[0].get_reference(), + self.type, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadInstr(Instruction): + + def __init__(self, parent, ptr, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load lacks type.") + super(LoadInstr, self).__init__(parent, typ, "load", [ptr], name=name) + self.align = None + + def descr(self, buf): + [val] = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("load {0}, {1} {2}{3}{4}\n".format( + self.type, + val.type, + val.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreInstr(Instruction): + def __init__(self, parent, val, ptr): + super(StoreInstr, self).__init__(parent, types.VoidType(), "store", + [val, ptr]) + + def descr(self, buf): + val, ptr = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("store {0} {1}, {2} {3}{4}{5}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadAtomicInstr(Instruction): + def __init__(self, parent, ptr, ordering, align, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load atomic lacks type.") + super(LoadAtomicInstr, self).__init__(parent, typ, "load atomic", + [ptr], name=name) + self.ordering = ordering + self.align = align + + def descr(self, buf): + [val] = self.operands + buf.append("load atomic {0}, {1} {2} {3}, align {4}{5}\n".format( + self.type, + val.type, + val.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreAtomicInstr(Instruction): + def __init__(self, parent, val, ptr, ordering, align): + super(StoreAtomicInstr, self).__init__(parent, types.VoidType(), + "store atomic", [val, ptr]) + self.ordering = ordering + self.align = align + + def descr(self, buf): + val, ptr = self.operands + buf.append("store atomic {0} {1}, {2} {3} {4}, align {5}{6}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class AllocaInstr(Instruction): + def __init__(self, parent, typ, count, name): + operands = [count] if count else () + super(AllocaInstr, self).__init__(parent, typ.as_pointer(), "alloca", + operands, name) + self.allocated_type = typ + self.align = None + + def descr(self, buf): + buf.append("{0} {1}".format(self.opname, self.allocated_type)) + if self.operands: + op, = self.operands + buf.append(", {0} {1}".format(op.type, op.get_reference())) + if self.align is not None: + buf.append(", align {0}".format(self.align)) + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + +class GEPInstr(Instruction): + def __init__(self, parent, ptr, indices, inbounds, name, + source_etype=None): + if source_etype is not None: + typ = ptr.type + self.source_etype = source_etype + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type + lasttyp = None + lastaddrspace = 0 + for i in indices: + lasttyp, typ = typ, typ.gep(i) + # inherit the addrspace from the last seen pointer + if isinstance(lasttyp, types.PointerType): + lastaddrspace = lasttyp.addrspace + + if (not isinstance(typ, types.PointerType) and + isinstance(lasttyp, types.PointerType)): + typ = lasttyp + else: + typ = typ.as_pointer(lastaddrspace) + self.source_etype = ptr.type.pointee + else: + raise ValueError("GEP lacks type.") + super(GEPInstr, self).__init__(parent, typ, "getelementptr", + [ptr] + list(indices), name=name) + self.pointer = ptr + self.indices = indices + self.inbounds = inbounds + + def descr(self, buf): + indices = ['{0} {1}'.format(i.type, i.get_reference()) + for i in self.indices] + op = "getelementptr inbounds" if self.inbounds else "getelementptr" + buf.append("{0} {1}, {2} {3}, {4} {5}\n".format( + op, + self.source_etype, + self.pointer.type, + self.pointer.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class PhiInstr(Instruction): + def __init__(self, parent, typ, name, flags=()): + super(PhiInstr, self).__init__(parent, typ, "phi", (), name=name, + flags=flags) + self.incomings = [] + + def descr(self, buf): + incs = ', '.join('[{0}, {1}]'.format(v.get_reference(), + b.get_reference()) + for v, b in self.incomings) + buf.append("phi {0} {1} {2} {3}\n".format( + ' '.join(self.flags), + self.type, + incs, + self._stringify_metadata(leading_comma=True), + )) + + def add_incoming(self, value, block): + assert isinstance(block, Block) + self.incomings.append((value, block)) + + def replace_usage(self, old, new): + self.incomings = [((new if val is old else val), blk) + for (val, blk) in self.incomings] + + +class ExtractElement(Instruction): + def __init__(self, parent, vector, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type.element + super(ExtractElement, self).__init__(parent, typ, "extractelement", + [vector, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class InsertElement(Instruction): + def __init__(self, parent, vector, value, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not value.type == vector.type.element: + raise TypeError( + "value needs to be of type {} not {}.".format( + vector.type.element, value.type)) + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type + super(InsertElement, self).__init__(parent, typ, "insertelement", + [vector, value, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class ShuffleVector(Instruction): + def __init__(self, parent, vector1, vector2, mask, name=''): + if not isinstance(vector1.type, types.VectorType): + raise TypeError("vector1 needs to be of VectorType.") + if vector2 != Undefined: + if vector2.type != vector1.type: + raise TypeError("vector2 needs to be " + + "Undefined or of the same type as vector1.") + if (not isinstance(mask, Constant) or + not isinstance(mask.type, types.VectorType) or + not (isinstance(mask.type.element, types.IntType) and + mask.type.element.width == 32)): + raise TypeError("mask needs to be a constant i32 vector.") + typ = types.VectorType(vector1.type.element, mask.type.count) + index_range = range(vector1.type.count + if vector2 == Undefined + else 2 * vector1.type.count) + if not all(ii.constant in index_range for ii in mask.constant): + raise IndexError( + "mask values need to be in {0}".format(index_range), + ) + super(ShuffleVector, self).__init__(parent, typ, "shufflevector", + [vector1, vector2, mask], name=name) + + def descr(self, buf): + buf.append("shufflevector {0} {1}\n".format( + ", ".join("{0} {1}".format(op.type, op.get_reference()) + for op in self.operands), + self._stringify_metadata(leading_comma=True), + )) + + +class ExtractValue(Instruction): + def __init__(self, parent, agg, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + + super(ExtractValue, self).__init__(parent, typ, "extractvalue", + [agg], name=name) + + self.aggregate = agg + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("extractvalue {0} {1}, {2} {3}\n".format( + self.aggregate.type, + self.aggregate.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class InsertValue(Instruction): + def __init__(self, parent, agg, elem, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + if elem.type != typ: + raise TypeError("Can only insert %s at %r in %s: got %s" + % (typ, list(indices), agg.type, elem.type)) + super(InsertValue, self).__init__(parent, agg.type, "insertvalue", + [agg, elem], name=name) + + self.aggregate = agg + self.value = elem + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("insertvalue {0} {1}, {2} {3}, {4} {5}\n".format( + self.aggregate.type, self.aggregate.get_reference(), + self.value.type, self.value.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class Unreachable(Instruction): + def __init__(self, parent): + super(Unreachable, self).__init__(parent, types.VoidType(), + "unreachable", (), name='') + + def descr(self, buf): + buf += (self.opname, "\n") + + +class InlineAsm(object): + def __init__(self, ftype, asm, constraint, side_effect=False): + self.type = ftype.return_type + self.function_type = ftype + self.asm = asm + self.constraint = constraint + self.side_effect = side_effect + + def descr(self, buf): + sideeffect = 'sideeffect' if self.side_effect else '' + fmt = 'asm {sideeffect} "{asm}", "{constraint}"\n' + buf.append(fmt.format(sideeffect=sideeffect, asm=self.asm, + constraint=self.constraint)) + + def get_reference(self): + buf = [] + self.descr(buf) + return "".join(buf) + + def __str__(self): + return "{0} {1}".format(self.type, self.get_reference()) + + +class AtomicRMW(Instruction): + def __init__(self, parent, op, ptr, val, ordering, name): + super(AtomicRMW, self).__init__(parent, val.type, "atomicrmw", + (ptr, val), name=name) + self.operation = op + self.ordering = ordering + + def descr(self, buf): + ptr, val = self.operands + fmt = ("atomicrmw {op} {ptrty} {ptr}, {valty} {val} {ordering} " + "{metadata}\n") + buf.append(fmt.format(op=self.operation, + ptrty=ptr.type, + ptr=ptr.get_reference(), + valty=val.type, + val=val.get_reference(), + ordering=self.ordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class CmpXchg(Instruction): + """This instruction has changed since llvm3.5. It is not compatible with + older llvm versions. + """ + + def __init__(self, parent, ptr, cmp, val, ordering, failordering, name): + outtype = types.LiteralStructType([val.type, types.IntType(1)]) + super(CmpXchg, self).__init__(parent, outtype, "cmpxchg", + (ptr, cmp, val), name=name) + self.ordering = ordering + self.failordering = failordering + + def descr(self, buf): + ptr, cmpval, val = self.operands + fmt = "cmpxchg {ptrty} {ptr}, {ty} {cmp}, {ty} {val} {ordering} " \ + "{failordering} {metadata}\n" + buf.append(fmt.format(ptrty=ptr.type, + ptr=ptr.get_reference(), + ty=cmpval.type, + cmp=cmpval.get_reference(), + val=val.get_reference(), + ordering=self.ordering, + failordering=self.failordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class _LandingPadClause(object): + def __init__(self, value): + self.value = value + + def __str__(self): + return "{kind} {type} {value}".format( + kind=self.kind, + type=self.value.type, + value=self.value.get_reference()) + + +class CatchClause(_LandingPadClause): + kind = 'catch' + + +class FilterClause(_LandingPadClause): + kind = 'filter' + + def __init__(self, value): + assert isinstance(value, Constant) + assert isinstance(value.type, types.ArrayType) + super(FilterClause, self).__init__(value) + + +class LandingPadInstr(Instruction): + def __init__(self, parent, typ, name='', cleanup=False): + super(LandingPadInstr, self).__init__(parent, typ, "landingpad", [], + name=name) + self.cleanup = cleanup + self.clauses = [] + + def add_clause(self, clause): + assert isinstance(clause, _LandingPadClause) + self.clauses.append(clause) + + def descr(self, buf): + fmt = "landingpad {type}{cleanup}{clauses}\n" + buf.append(fmt.format(type=self.type, + cleanup=' cleanup' if self.cleanup else '', + clauses=''.join(["\n {0}".format(clause) + for clause in self.clauses]), + )) + + +class Fence(Instruction): + """ + The `fence` instruction. + + As of LLVM 5.0.1: + + fence [syncscope("")] ; yields void + """ + + VALID_FENCE_ORDERINGS = {"acquire", "release", "acq_rel", "seq_cst"} + + def __init__(self, parent, ordering, targetscope=None, name=''): + super(Fence, self).__init__(parent, types.VoidType(), "fence", (), + name=name) + if ordering not in self.VALID_FENCE_ORDERINGS: + msg = "Invalid fence ordering \"{0}\"! Should be one of {1}." + raise ValueError(msg .format(ordering, + ", ".join(self.VALID_FENCE_ORDERINGS))) + self.ordering = ordering + self.targetscope = targetscope + + def descr(self, buf): + if self.targetscope is None: + syncscope = "" + else: + syncscope = 'syncscope("{0}") '.format(self.targetscope) + + fmt = "fence {syncscope}{ordering}\n" + buf.append(fmt.format(syncscope=syncscope, + ordering=self.ordering, + )) + + +class Comment(Instruction): + """ + A line comment. + """ + + def __init__(self, parent, text): + super(Comment, self).__init__(parent, types.VoidType(), ";", (), + name='') + assert "\n" not in text, "Comment cannot contain new line" + self.text = text + + def descr(self, buf): + buf.append(f"; {self.text}") diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/module.py b/python_embeded/Lib/site-packages/llvmlite/ir/module.py new file mode 100644 index 0000000000000000000000000000000000000000..692201bb442dc31e75ee1aebee70f937029bef4e --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/module.py @@ -0,0 +1,246 @@ +import collections + +from llvmlite.ir import context, values, types, _utils + + +class Module(object): + def __init__(self, name='', context=context.global_context): + self.context = context + self.name = name # name is for debugging/informational + self.data_layout = "" + self.scope = _utils.NameScope() + self.triple = 'unknown-unknown-unknown' + self.globals = collections.OrderedDict() + # Innamed metadata nodes. + self.metadata = [] + # Named metadata nodes + self.namedmetadata = {} + # Cache for metadata node deduplication + self._metadatacache = {} + + def _fix_metadata_operands(self, operands): + fixed_ops = [] + for op in operands: + if op is None: + # A literal None creates a null metadata value + op = types.MetaDataType()(None) + elif isinstance(op, str): + # A literal string creates a metadata string value + op = values.MetaDataString(self, op) + elif isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append(op) + return fixed_ops + + def _fix_di_operands(self, operands): + fixed_ops = [] + for name, op in operands: + if isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append((name, op)) + return fixed_ops + + def add_metadata(self, operands): + """ + Add an unnamed metadata to the module with the given *operands* + (a sequence of values) or return a previous equivalent metadata. + A MDValue instance is returned, it can then be associated to + e.g. an instruction. + """ + if not isinstance(operands, (list, tuple)): + raise TypeError("expected a list or tuple of metadata values, " + "got %r" % (operands,)) + operands = self._fix_metadata_operands(operands) + key = tuple(operands) + if key not in self._metadatacache: + n = len(self.metadata) + md = values.MDValue(self, operands, name=str(n)) + self._metadatacache[key] = md + else: + md = self._metadatacache[key] + return md + + def add_debug_info(self, kind, operands, is_distinct=False): + """ + Add debug information metadata to the module with the given + *operands* (a dict of values with string keys) or return + a previous equivalent metadata. *kind* is a string of the + debug information kind (e.g. "DICompileUnit"). + + A DIValue instance is returned, it can then be associated to e.g. + an instruction. + """ + operands = tuple(sorted(self._fix_di_operands(operands.items()))) + key = (kind, operands, is_distinct) + if key not in self._metadatacache: + n = len(self.metadata) + di = values.DIValue(self, is_distinct, kind, operands, name=str(n)) + self._metadatacache[key] = di + else: + di = self._metadatacache[key] + return di + + def add_named_metadata(self, name, element=None): + """ + Add a named metadata node to the module, if it doesn't exist, + or return the existing node. + If *element* is given, it will append a new element to + the named metadata node. If *element* is a sequence of values + (rather than a metadata value), a new unnamed node will first be + created. + + Example:: + module.add_named_metadata("llvm.ident", ["llvmlite/1.0"]) + """ + if name in self.namedmetadata: + nmd = self.namedmetadata[name] + else: + nmd = self.namedmetadata[name] = values.NamedMetaData(self) + if element is not None: + if not isinstance(element, values.Value): + element = self.add_metadata(element) + if not isinstance(element.type, types.MetaDataType): + raise TypeError("wrong type for metadata element: got %r" + % (element,)) + nmd.add(element) + return nmd + + def get_named_metadata(self, name): + """ + Return the metadata node with the given *name*. KeyError is raised + if no such node exists (contrast with add_named_metadata()). + """ + return self.namedmetadata[name] + + @property + def functions(self): + """ + A list of functions declared or defined in this module. + """ + return [v for v in self.globals.values() + if isinstance(v, values.Function)] + + @property + def global_values(self): + """ + An iterable of global values in this module. + """ + return self.globals.values() + + def get_global(self, name): + """ + Get a global value by name. + """ + return self.globals[name] + + def add_global(self, globalvalue): + """ + Add a new global value. + """ + assert globalvalue.name not in self.globals + self.globals[globalvalue.name] = globalvalue + + def get_unique_name(self, name=''): + """ + Get a unique global name with the following *name* hint. + """ + return self.scope.deduplicate(name) + + def declare_intrinsic(self, intrinsic, tys=(), fnty=None): + def _error(): + raise NotImplementedError("unknown intrinsic %r with %d types" + % (intrinsic, len(tys))) + + if intrinsic in {'llvm.cttz', 'llvm.ctlz', 'llvm.fma'}: + suffixes = [tys[0].intrinsic_name] + else: + suffixes = [t.intrinsic_name for t in tys] + name = '.'.join([intrinsic] + suffixes) + if name in self.globals: + return self.globals[name] + + if fnty is not None: + # General case: function type is given + pass + # Compute function type if omitted for common cases + elif len(tys) == 0 and intrinsic == 'llvm.assume': + fnty = types.FunctionType(types.VoidType(), [types.IntType(1)]) + elif len(tys) == 1: + if intrinsic == 'llvm.powi': + fnty = types.FunctionType(tys[0], [tys[0], types.IntType(32)]) + elif intrinsic == 'llvm.pow': + fnty = types.FunctionType(tys[0], tys * 2) + elif intrinsic == 'llvm.convert.from.fp16': + fnty = types.FunctionType(tys[0], [types.IntType(16)]) + elif intrinsic == 'llvm.convert.to.fp16': + fnty = types.FunctionType(types.IntType(16), tys) + else: + fnty = types.FunctionType(tys[0], tys) + elif len(tys) == 2: + if intrinsic == 'llvm.memset': + tys = [tys[0], types.IntType(8), tys[1], + types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic in {'llvm.cttz', 'llvm.ctlz'}: + tys = [tys[0], types.IntType(1)] + fnty = types.FunctionType(tys[0], tys) + else: + _error() + elif len(tys) == 3: + if intrinsic in ('llvm.memcpy', 'llvm.memmove'): + tys = tys + [types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic == 'llvm.fma': + tys = [tys[0]] * 3 + fnty = types.FunctionType(tys[0], tys) + else: + _error() + else: + _error() + return values.Function(self, fnty, name=name) + + def get_identified_types(self): + return self.context.identified_types + + def _get_body_lines(self): + # Type declarations + lines = [it.get_declaration() + for it in self.get_identified_types().values()] + # Global values (including function definitions) + lines += [str(v) for v in self.globals.values()] + return lines + + def _get_metadata_lines(self): + mdbuf = [] + for k, v in self.namedmetadata.items(): + mdbuf.append("!{name} = !{{ {operands} }}".format( + name=k, operands=', '.join(i.get_reference() + for i in v.operands))) + for md in self.metadata: + mdbuf.append(str(md)) + return mdbuf + + def _stringify_body(self): + # For testing + return "\n".join(self._get_body_lines()) + + def _stringify_metadata(self): + # For testing + return "\n".join(self._get_metadata_lines()) + + def __repr__(self): + lines = [] + # Header + lines += [ + '; ModuleID = "%s"' % (self.name,), + 'target triple = "%s"' % (self.triple,), + 'target datalayout = "%s"' % (self.data_layout,), + ''] + # Body + lines += self._get_body_lines() + # Metadata + lines += self._get_metadata_lines() + + return "\n".join(lines) diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/transforms.py b/python_embeded/Lib/site-packages/llvmlite/ir/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..321e3bb2794352b7095fa8594153ace931562bf0 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/transforms.py @@ -0,0 +1,64 @@ +from llvmlite.ir import CallInstr + + +class Visitor(object): + def visit(self, module): + self._module = module + for func in module.functions: + self.visit_Function(func) + + def visit_Function(self, func): + self._function = func + for bb in func.blocks: + self.visit_BasicBlock(bb) + + def visit_BasicBlock(self, bb): + self._basic_block = bb + for instr in bb.instructions: + self.visit_Instruction(instr) + + def visit_Instruction(self, instr): + raise NotImplementedError + + @property + def module(self): + return self._module + + @property + def function(self): + return self._function + + @property + def basic_block(self): + return self._basic_block + + +class CallVisitor(Visitor): + def visit_Instruction(self, instr): + if isinstance(instr, CallInstr): + self.visit_Call(instr) + + def visit_Call(self, instr): + raise NotImplementedError + + +class ReplaceCalls(CallVisitor): + def __init__(self, orig, repl): + super(ReplaceCalls, self).__init__() + self.orig = orig + self.repl = repl + self.calls = [] + + def visit_Call(self, instr): + if instr.callee == self.orig: + instr.replace_callee(self.repl) + self.calls.append(instr) + + +def replace_all_calls(mod, orig, repl): + """Replace all calls to `orig` to `repl` in module `mod`. + Returns the references to the returned calls + """ + rc = ReplaceCalls(orig, repl) + rc.visit(mod) + return rc.calls diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/types.py b/python_embeded/Lib/site-packages/llvmlite/ir/types.py new file mode 100644 index 0000000000000000000000000000000000000000..b992c18e2103145ce5b98020fdcee0be806ddbf4 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/types.py @@ -0,0 +1,734 @@ +""" +Classes that are LLVM types +""" + +import struct + +from llvmlite.ir._utils import _StrCaching + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled + + +def _wrapname(x): + return '"{0}"'.format(x.replace('\\', '\\5c').replace('"', '\\22')) + + +class Type(_StrCaching): + """ + The base class for all LLVM types. + """ + is_pointer = False + null = 'zeroinitializer' + + def __repr__(self): + return "<%s %s>" % (type(self), str(self)) + + def _to_string(self): + raise NotImplementedError + + def as_pointer(self, addrspace=0): + return PointerType(self, addrspace) + + def __ne__(self, other): + return not (self == other) + + def _get_ll_global_value_type(self, target_data, context=None): + """ + Convert this type object to an LLVM type. + """ + from llvmlite.ir import Module, GlobalVariable + from llvmlite.binding import parse_assembly + + if context is None: + m = Module() + else: + m = Module(context=context) + foo = GlobalVariable(m, self, name="foo") + with parse_assembly(str(m)) as llmod: + return llmod.get_global_variable(foo.name).global_value_type + + def get_abi_size(self, target_data, context=None): + """ + Get the ABI size of this type according to data layout *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_size(llty) + + def get_element_offset(self, target_data, ndx, context=None): + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_element_offset(llty, ndx) + + def get_abi_alignment(self, target_data, context=None): + """ + Get the minimum ABI alignment of this type according to data layout + *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_alignment(llty) + + def format_constant(self, value): + """ + Format constant *value* of this type. This method may be overriden + by subclasses. + """ + return str(value) + + def wrap_constant_value(self, value): + """ + Wrap constant *value* if necessary. This method may be overriden + by subclasses (especially aggregate types). + """ + return value + + def __call__(self, value): + """ + Create a LLVM constant of this type with the given Python value. + """ + from llvmlite.ir import Constant + return Constant(self, value) + + +class MetaDataType(Type): + + def _to_string(self): + return "metadata" + + def as_pointer(self): + raise TypeError + + def __eq__(self, other): + return isinstance(other, MetaDataType) + + def __hash__(self): + return hash(MetaDataType) + + +class LabelType(Type): + """ + The label type is the type of e.g. basic blocks. + """ + + def _to_string(self): + return "label" + + +class PointerType(Type): + """ + The type of all pointer values. + By default (without specialisation) represents an opaque pointer. + """ + is_opaque = True + is_pointer = True + null = 'null' + + # Factory to create typed or opaque pointers based on `pointee'. + def __new__(cls, pointee=None, addrspace=0): + if cls is PointerType and pointee is not None: + return super().__new__(_TypedPointerType) + return super(PointerType, cls).__new__(cls) + + def __init__(self, addrspace=0): + self.addrspace = addrspace + + def _to_string(self): + if self.addrspace != 0: + return "ptr addrspace({0})".format(self.addrspace) + else: + return "ptr" + + def __hash__(self): + return hash(PointerType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + if not opaque_pointers_enabled: + return _TypedPointerType.from_llvm(typeref, ir_ctx) + return cls() + + +class _TypedPointerType(PointerType): + """ + The type of typed pointer values. To be removed eventually. + """ + + def __init__(self, pointee, addrspace=0): + super(_TypedPointerType, self).__init__(addrspace) + assert pointee is not None + assert not isinstance(pointee, VoidType) + self.pointee = pointee + self.is_opaque = False + + def _to_string(self): + if not opaque_pointers_enabled: + return "{0}*".format(self.pointee) if self.addrspace == 0 else \ + "{0} addrspace({1})*".format(self.pointee, self.addrspace) + return super(_TypedPointerType, self)._to_string() + + # This implements ``isOpaqueOrPointeeTypeEquals''. + def __eq__(self, other): + if isinstance(other, _TypedPointerType): + return (self.pointee, self.addrspace) == (other.pointee, + other.addrspace) + return isinstance(other, PointerType) + + def __hash__(self): + return hash(_TypedPointerType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.pointee + + @property + def intrinsic_name(self): + return 'p%d%s' % (self.addrspace, self.pointee.intrinsic_name) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + assert not opaque_pointers_enabled + # opaque pointer will change this + [pointee] = typeref.elements + # addrspace is not handled + return cls(pointee.as_ir(ir_ctx=ir_ctx)) + + +class VoidType(Type): + """ + The type for empty values (e.g. a function returning no value). + """ + + def _to_string(self): + return 'void' + + def __eq__(self, other): + return isinstance(other, VoidType) + + def __hash__(self): + return hash(VoidType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class FunctionType(Type): + """ + The type for functions. + """ + + def __init__(self, return_type, args, var_arg=False): + self.return_type = return_type + self.args = tuple(args) + self.var_arg = var_arg + + def _to_string(self): + if self.args: + strargs = ', '.join([str(a) for a in self.args]) + if self.var_arg: + return '{0} ({1}, ...)'.format(self.return_type, strargs) + else: + return '{0} ({1})'.format(self.return_type, strargs) + elif self.var_arg: + return '{0} (...)'.format(self.return_type) + else: + return '{0} ()'.format(self.return_type) + + def __eq__(self, other): + if isinstance(other, FunctionType): + return (self.return_type == other.return_type and + self.args == other.args and self.var_arg == other.var_arg) + else: + return False + + def __hash__(self): + return hash(FunctionType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + params = tuple(x.as_ir(ir_ctx=ir_ctx) + for x in typeref.get_function_parameters()) + ret = typeref.get_function_return().as_ir(ir_ctx=ir_ctx) + is_vararg = typeref.is_function_vararg + return cls(ret, params, is_vararg) + + +class IntType(Type): + """ + The type for integers. + """ + null = '0' + _instance_cache = {} + width: int + + def __new__(cls, bits): + # Cache all common integer types + if 0 <= bits <= 128: + try: + return cls._instance_cache[bits] + except KeyError: + inst = cls._instance_cache[bits] = cls.__new(bits) + return inst + return cls.__new(bits) + + @classmethod + def __new(cls, bits): + assert isinstance(bits, int) and bits >= 0 + self = super(IntType, cls).__new__(cls) + self.width = bits + return self + + def __getnewargs__(self): + return self.width, + + def __copy__(self): + return self + + def _to_string(self): + return 'i%u' % (self.width,) + + def __eq__(self, other): + if isinstance(other, IntType): + return self.width == other.width + else: + return False + + def __hash__(self): + return hash(IntType) + + def format_constant(self, val): + if isinstance(val, bool): + return str(val).lower() + else: + return str(val) + + def wrap_constant_value(self, val): + if val is None: + return 0 + return val + + @property + def intrinsic_name(self): + return str(self) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return IntType(typeref.type_width) + + +def _as_float(value): + """ + Truncate to single-precision float. + """ + return struct.unpack('f', struct.pack('f', value))[0] + + +def _as_half(value): + """ + Truncate to half-precision float. + """ + try: + return struct.unpack('e', struct.pack('e', value))[0] + except struct.error: + # 'e' only added in Python 3.6+ + return _as_float(value) + + +def _format_float_as_hex(value, packfmt, unpackfmt, numdigits): + raw = struct.pack(packfmt, float(value)) + intrep = struct.unpack(unpackfmt, raw)[0] + out = '{{0:#{0}x}}'.format(numdigits).format(intrep) + return out + + +def _format_double(value): + """ + Format *value* as a hexadecimal string of its IEEE double precision + representation. + """ + return _format_float_as_hex(value, 'd', 'Q', 16) + + +class _BaseFloatType(Type): + + def __new__(cls): + return cls._instance_cache + + def __eq__(self, other): + return isinstance(other, type(self)) + + def __hash__(self): + return hash(type(self)) + + @classmethod + def _create_instance(cls): + cls._instance_cache = super(_BaseFloatType, cls).__new__(cls) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class HalfType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f16' + + def __str__(self): + return 'half' + + def format_constant(self, value): + return _format_double(_as_half(value)) + + +class FloatType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f32' + + def __str__(self): + return 'float' + + def format_constant(self, value): + return _format_double(_as_float(value)) + + +class DoubleType(_BaseFloatType): + """ + The type for double-precision floats. + """ + null = '0.0' + intrinsic_name = 'f64' + + def __str__(self): + return 'double' + + def format_constant(self, value): + return _format_double(value) + + +for _cls in (HalfType, FloatType, DoubleType): + _cls._create_instance() + + +class _Repeat(object): + def __init__(self, value, size): + self.value = value + self.size = size + + def __len__(self): + return self.size + + def __getitem__(self, item): + if 0 <= item < self.size: + return self.value + else: + raise IndexError(item) + + +class VectorType(Type): + """ + The type for vectors of primitive data items (e.g. ""). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "<%d x %s>" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, VectorType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + # TODO: why does this not take self.element/self.count into account? + return hash(VectorType) + + def __copy__(self): + return self + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "<{0}>".format(itemstring) + + def wrap_constant_value(self, values): + from . import Value, Constant + if not isinstance(values, (list, tuple)): + if isinstance(values, Constant): + if values.type != self.element: + raise TypeError("expected {} for {}".format( + self.element, values.type)) + return (values, ) * self.count + return (Constant(self.element, values), ) * self.count + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class Aggregate(Type): + """ + Base class for aggregate types. + See http://llvm.org/docs/LangRef.html#t-aggregate + """ + + def wrap_constant_value(self, values): + from . import Value, Constant + + if not isinstance(values, (list, tuple)): + return values + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + +class ArrayType(Aggregate): + """ + The type for fixed-size homogenous arrays (e.g. "[f32 x 3]"). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "[%d x %s]" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, ArrayType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + return hash(ArrayType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.element + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "[{0}]".format(itemstring) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class BaseStructType(Aggregate): + """ + The base type for heterogenous struct types. + """ + _packed = False + + @property + def packed(self): + """ + A boolean attribute that indicates whether the structure uses + packed layout. + """ + return self._packed + + @packed.setter + def packed(self, val): + self._packed = bool(val) + + def __len__(self): + assert self.elements is not None + return len(self.elements) + + def __iter__(self): + assert self.elements is not None + return iter(self.elements) + + @property + def is_opaque(self): + return self.elements is None + + def structure_repr(self): + """ + Return the LLVM IR for the structure representation + """ + ret = '{%s}' % ', '.join([str(x) for x in self.elements]) + return self._wrap_packed(ret) + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + ret = "{{{0}}}".format(itemstring) + return self._wrap_packed(ret) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + + *i* needs to be a LLVM constant, so that the type can be determined + at compile-time. + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.elements[i.constant] + + def _wrap_packed(self, textrepr): + """ + Internal helper to wrap textual repr of struct type into packed struct + """ + if self.packed: + return '<{}>'.format(textrepr) + else: + return textrepr + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + if typeref.is_literal_struct: + elems = [el.as_ir(ir_ctx=ir_ctx) for el in typeref.elements] + return cls(elems, typeref.is_packed_struct) + else: + return ir_ctx.get_identified_type(typeref.name) + + +class LiteralStructType(BaseStructType): + """ + The type of "literal" structs, i.e. structs with a literally-defined + type (by contrast with IdentifiedStructType). + """ + + null = 'zeroinitializer' + + def __init__(self, elems, packed=False): + """ + *elems* is a sequence of types to be used as members. + *packed* controls the use of packed layout. + """ + self.elements = tuple(elems) + self.packed = packed + + def _to_string(self): + return self.structure_repr() + + def __eq__(self, other): + if isinstance(other, LiteralStructType): + return (self.elements == other.elements + and self.packed == other.packed) + + def __hash__(self): + return hash(LiteralStructType) + + +class IdentifiedStructType(BaseStructType): + """ + A type which is a named alias for another struct type, akin to a typedef. + While literal struct types can be structurally equal (see + LiteralStructType), identified struct types are compared by name. + + Do not use this directly. + """ + null = 'zeroinitializer' + + def __init__(self, context, name, packed=False): + """ + *context* is a llvmlite.ir.Context. + *name* is the identifier for the new struct type. + *packed* controls the use of packed layout. + """ + assert name + self.context = context + self.name = name + self.elements = None + self.packed = packed + + def _to_string(self): + return "%{name}".format(name=_wrapname(self.name)) + + def get_declaration(self): + """ + Returns the string for the declaration of the type + """ + if self.is_opaque: + out = "{strrep} = type opaque".format(strrep=str(self)) + else: + out = "{strrep} = type {struct}".format( + strrep=str(self), struct=self.structure_repr()) + return out + + def __eq__(self, other): + if isinstance(other, IdentifiedStructType): + return (self.name == other.name + and self.packed == other.packed) + + def __hash__(self): + return hash(IdentifiedStructType) + + def set_body(self, *elems): + if not self.is_opaque: + raise RuntimeError("{name} is already defined".format( + name=self.name)) + self.elements = tuple(elems) diff --git a/python_embeded/Lib/site-packages/llvmlite/ir/values.py b/python_embeded/Lib/site-packages/llvmlite/ir/values.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa3b34976aa1a31dd8d3e919df4d6b27819ae5e --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/ir/values.py @@ -0,0 +1,1217 @@ +""" +Classes that are LLVM values: Value, Constant... +Instructions are in the instructions module. +""" + +import functools +import string +import re +from types import MappingProxyType + +from llvmlite.ir import values, types, _utils +from llvmlite.ir._utils import (_StrCaching, _StringReferenceCaching, + _HasMetadata) + +_VALID_CHARS = (frozenset(map(ord, string.ascii_letters)) | + frozenset(map(ord, string.digits)) | + frozenset(map(ord, ' !#$%&\'()*+,-./:;<=>?@[]^_`{|}~'))) + +_SIMPLE_IDENTIFIER_RE = re.compile(r"[-a-zA-Z$._][-a-zA-Z$._0-9]*$") + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _escape_string(text, _map={}): + """ + Escape the given bytestring for safe use as a LLVM array constant. + Any unicode string input is first encoded with utf8 into bytes. + """ + if isinstance(text, str): + text = text.encode() + assert isinstance(text, (bytes, bytearray)) + + if not _map: + for ch in range(256): + if ch in _VALID_CHARS: + _map[ch] = chr(ch) + else: + _map[ch] = '\\%02x' % ch + + buf = [_map[ch] for ch in text] + return ''.join(buf) + + +def _binop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(lhs, rhs): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + + fmt = "{0} ({1} {2}, {3} {4})".format(opname, + lhs.type, lhs.get_reference(), + rhs.type, rhs.get_reference()) + return FormattedConstant(lhs.type, fmt) + + return wrapped + return wrap + + +def _castop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, typ): + fn(self, typ) + if typ == self.type: + return self + + op = "{0} ({1} {2} to {3})".format(opname, self.type, + self.get_reference(), typ) + return FormattedConstant(typ, op) + + return wrapped + return wrap + + +class _ConstOpMixin(object): + """ + A mixin defining constant operations, for use in constant-like classes. + """ + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, other): + """ + Left integer shift: + lhs << rhs + """ + + @_binop('lshr') + def lshr(self, other): + """ + Logical (unsigned) right integer shift: + lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, other): + """ + Arithmetic (signed) right integer shift: + lhs >> rhs + """ + + @_binop('add') + def add(self, other): + """ + Integer addition: + lhs + rhs + """ + + @_binop('fadd') + def fadd(self, other): + """ + Floating-point addition: + lhs + rhs + """ + + @_binop('sub') + def sub(self, other): + """ + Integer subtraction: + lhs - rhs + """ + + @_binop('fsub') + def fsub(self, other): + """ + Floating-point subtraction: + lhs - rhs + """ + + @_binop('mul') + def mul(self, other): + """ + Integer multiplication: + lhs * rhs + """ + + @_binop('fmul') + def fmul(self, other): + """ + Floating-point multiplication: + lhs * rhs + """ + + @_binop('udiv') + def udiv(self, other): + """ + Unsigned integer division: + lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, other): + """ + Signed integer division: + lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, other): + """ + Floating-point division: + lhs / rhs + """ + + @_binop('urem') + def urem(self, other): + """ + Unsigned integer remainder: + lhs % rhs + """ + + @_binop('srem') + def srem(self, other): + """ + Signed integer remainder: + lhs % rhs + """ + + @_binop('frem') + def frem(self, other): + """ + Floating-point remainder: + lhs % rhs + """ + + @_binop('or') + def or_(self, other): + """ + Bitwise integer OR: + lhs | rhs + """ + + @_binop('and') + def and_(self, other): + """ + Bitwise integer AND: + lhs & rhs + """ + + @_binop('xor') + def xor(self, other): + """ + Bitwise integer XOR: + lhs ^ rhs + """ + + def _cmp(self, prefix, sign, cmpop, other): + ins = prefix + 'cmp' + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for %s" % (cmpop, ins)) + + if not (prefix == 'i' and cmpop in ('==', '!=')): + op = sign + op + + if self.type != other.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (self.type, other.type)) + + fmt = "{0} {1} ({2} {3}, {4} {5})".format( + ins, op, + self.type, self.get_reference(), + other.type, other.get_reference()) + + return FormattedConstant(types.IntType(1), fmt) + + def icmp_signed(self, cmpop, other): + """ + Signed integer comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 's', cmpop, other) + + def icmp_unsigned(self, cmpop, other): + """ + Unsigned integer (or pointer) comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 'u', cmpop, other) + + def fcmp_ordered(self, cmpop, other): + """ + Floating-point ordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'o', cmpop, other) + + def fcmp_unordered(self, cmpop, other): + """ + Floating-point unordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'u', cmpop, other) + + # + # Unary APIs + # + + def not_(self): + """ + Bitwise integer complement: + ~value + """ + if isinstance(self.type, types.VectorType): + rhs = values.Constant(self.type, (-1,) * self.type.count) + else: + rhs = values.Constant(self.type, -1) + + return self.xor(rhs) + + def neg(self): + """ + Integer negative: + -value + """ + zero = values.Constant(self.type, 0) + return zero.sub(self) + + def fneg(self): + """ + Floating-point negative: + -value + """ + fmt = "fneg ({0} {1})".format(self.type, self.get_reference()) + return FormattedConstant(self.type, fmt) + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, typ): + """ + Truncating integer downcast to a smaller type. + """ + + @_castop('zext') + def zext(self, typ): + """ + Zero-extending integer upcast to a larger type + """ + + @_castop('sext') + def sext(self, typ): + """ + Sign-extending integer upcast to a larger type. + """ + + @_castop('fptrunc') + def fptrunc(self, typ): + """ + Floating-point downcast to a less precise type. + """ + + @_castop('fpext') + def fpext(self, typ): + """ + Floating-point upcast to a more precise type. + """ + + @_castop('bitcast') + def bitcast(self, typ): + """ + Pointer cast to a different pointer type. + """ + + @_castop('fptoui') + def fptoui(self, typ): + """ + Convert floating-point to unsigned integer. + """ + + @_castop('uitofp') + def uitofp(self, typ): + """ + Convert unsigned integer to floating-point. + """ + + @_castop('fptosi') + def fptosi(self, typ): + """ + Convert floating-point to signed integer. + """ + + @_castop('sitofp') + def sitofp(self, typ): + """ + Convert signed integer to floating-point. + """ + + @_castop('ptrtoint') + def ptrtoint(self, typ): + """ + Cast pointer to integer. + """ + if not isinstance(self.type, types.PointerType): + msg = "can only call ptrtoint() on pointer type, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.IntType): + raise TypeError("can only ptrtoint() to integer type, not '%s'" + % (typ,)) + + @_castop('inttoptr') + def inttoptr(self, typ): + """ + Cast integer to pointer. + """ + if not isinstance(self.type, types.IntType): + msg = "can only call inttoptr() on integer constants, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.PointerType): + raise TypeError("can only inttoptr() to pointer type, not '%s'" + % (typ,)) + + def gep(self, indices): + """ + Call getelementptr on this pointer constant. + """ + if not isinstance(self.type, types.PointerType): + raise TypeError("can only call gep() on pointer constants, not '%s'" + % (self.type,)) + + outtype = self.type + for i in indices: + outtype = outtype.gep(i) + + strindices = ["{0} {1}".format(idx.type, idx.get_reference()) + for idx in indices] + + op = "getelementptr ({0}, {1} {2}, {3})".format( + self.type.pointee, self.type, + self.get_reference(), ', '.join(strindices)) + return FormattedConstant(outtype.as_pointer(self.addrspace), op) + + +class Value(object): + """ + The base class for all values. + """ + + def __repr__(self): + return "" % (self.__class__.__name__, self.type,) + + +class _Undefined(object): + """ + 'undef': a value for undefined values. + """ + def __new__(cls): + try: + return Undefined + except NameError: + return object.__new__(_Undefined) + + +Undefined = _Undefined() + + +class Constant(_StrCaching, _StringReferenceCaching, _ConstOpMixin, Value): + """ + A constant LLVM value. + """ + + def __init__(self, typ, constant): + assert isinstance(typ, types.Type) + assert not isinstance(typ, types.VoidType) + self.type = typ + constant = typ.wrap_constant_value(constant) + self.constant = constant + + def _to_string(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def _get_reference(self): + if self.constant is None: + val = self.type.null + + elif self.constant is Undefined: + val = "undef" + + elif isinstance(self.constant, bytearray): + val = 'c"{0}"'.format(_escape_string(self.constant)) + + else: + val = self.type.format_constant(self.constant) + + return val + + @classmethod + def literal_array(cls, elems): + """ + Construct a literal array constant made of the given members. + """ + tys = [el.type for el in elems] + if len(tys) == 0: + raise ValueError("need at least one element") + ty = tys[0] + for other in tys: + if ty != other: + raise TypeError("all elements must have the same type") + return cls(types.ArrayType(ty, len(elems)), elems) + + @classmethod + def literal_struct(cls, elems, packed=False): + """ + Construct a literal structure constant made of the given members. + """ + tys = [el.type for el in elems] + return cls(types.LiteralStructType(tys, packed), elems) + + @property + def addrspace(self): + if not isinstance(self.type, types.PointerType): + raise TypeError("Only pointer constant have address spaces") + return self.type.addrspace + + def __eq__(self, other): + if isinstance(other, Constant): + return str(self) == str(other) + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(str(self)) + + def __repr__(self): + return "" % (self.type, self.constant) + + +class FormattedConstant(Constant): + """ + A constant with an already formatted IR representation. + """ + + def __init__(self, typ, constant): + assert isinstance(constant, str) + Constant.__init__(self, typ, constant) + + def _to_string(self): + return self.constant + + def _get_reference(self): + return self.constant + + +class NamedValue(_StrCaching, _StringReferenceCaching, Value): + """ + The base class for named values. + """ + name_prefix = '%' + deduplicate_name = True + + def __init__(self, parent, type, name): + assert parent is not None + assert isinstance(type, types.Type) + self.parent = parent + self.type = type + self._set_name(name) + + def _to_string(self): + buf = [] + if not isinstance(self.type, types.VoidType): + buf.append("{0} = ".format(self.get_reference())) + self.descr(buf) + return "".join(buf).rstrip() + + def descr(self, buf): + raise NotImplementedError + + def _get_name(self): + return self._name + + def _set_name(self, name): + name = self.parent.scope.register(name, + deduplicate=self.deduplicate_name) + self._name = name + + name = property(_get_name, _set_name) + + def _get_reference(self): + name = self.name + # Quote and escape value name + if '\\' in name or '"' in name: + name = name.replace('\\', '\\5c').replace('"', '\\22') + return '{0}"{1}"'.format(self.name_prefix, name) + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type) + + @property + def function_type(self): + ty = self.type + if isinstance(ty, types.PointerType): + ty = self.type.pointee + if isinstance(ty, types.FunctionType): + return ty + else: + raise TypeError("Not a function: {0}".format(self.type)) + + +class MetaDataString(NamedValue): + """ + A metadata string, i.e. a constant string used as a value in a metadata + node. + """ + + def __init__(self, parent, string): + super(MetaDataString, self).__init__(parent, + types.MetaDataType(), + name="") + self.string = string + + def descr(self, buf): + buf += (self.get_reference(), "\n") + + def _get_reference(self): + return '!"{0}"'.format(_escape_string(self.string)) + + _to_string = _get_reference + + def __eq__(self, other): + if isinstance(other, MetaDataString): + return self.string == other.string + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.string) + + +class MetaDataArgument(_StrCaching, _StringReferenceCaching, Value): + """ + An argument value to a function taking metadata arguments. + This can wrap any other kind of LLVM value. + + Do not instantiate directly, Builder.call() will create these + automatically. + """ + + def __init__(self, value): + assert isinstance(value, Value) + assert not isinstance(value.type, types.MetaDataType) + self.type = types.MetaDataType() + self.wrapped_value = value + + def _get_reference(self): + # e.g. "i32* %2" + return "{0} {1}".format(self.wrapped_value.type, + self.wrapped_value.get_reference()) + + _to_string = _get_reference + + +class NamedMetaData(object): + """ + A named metadata node. + + Do not instantiate directly, use Module.add_named_metadata() instead. + """ + + def __init__(self, parent): + self.parent = parent + self.operands = [] + + def add(self, md): + self.operands.append(md) + + +class MDValue(NamedValue): + """ + A metadata node's value, consisting of a sequence of elements ("operands"). + + Do not instantiate directly, use Module.add_metadata() instead. + """ + name_prefix = '!' + + def __init__(self, parent, values, name): + super(MDValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.operands = tuple(values) + parent.metadata.append(self) + + def descr(self, buf): + operands = [] + for op in self.operands: + if isinstance(op.type, types.MetaDataType): + if isinstance(op, Constant) and op.constant is None: + operands.append("null") + else: + operands.append(op.get_reference()) + else: + operands.append("{0} {1}".format(op.type, op.get_reference())) + operands = ', '.join(operands) + buf += ("!{{ {0} }}".format(operands), "\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, MDValue): + return self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.operands) + + +class DIToken: + """ + A debug information enumeration value that should appear bare in + the emitted metadata. + + Use this to wrap known constants, e.g. the DW_* enumerations. + """ + + def __init__(self, value): + self.value = value + + +class DIValue(NamedValue): + """ + A debug information descriptor, containing key-value pairs. + + Do not instantiate directly, use Module.add_debug_info() instead. + """ + name_prefix = '!' + + def __init__(self, parent, is_distinct, kind, operands, name): + super(DIValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.is_distinct = is_distinct + self.kind = kind + self.operands = tuple(operands) + parent.metadata.append(self) + + def descr(self, buf): + if self.is_distinct: + buf += ("distinct ",) + operands = [] + for key, value in self.operands: + if value is None: + strvalue = "null" + elif value is True: + strvalue = "true" + elif value is False: + strvalue = "false" + elif isinstance(value, DIToken): + strvalue = value.value + elif isinstance(value, str): + strvalue = '"{}"'.format(_escape_string(value)) + elif isinstance(value, int): + strvalue = str(value) + elif isinstance(value, NamedValue): + strvalue = value.get_reference() + else: + raise TypeError("invalid operand type for debug info: %r" + % (value,)) + operands.append("{0}: {1}".format(key, strvalue)) + operands = ', '.join(operands) + buf += ("!", self.kind, "(", operands, ")\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, DIValue): + return self.is_distinct == other.is_distinct and \ + self.kind == other.kind and \ + self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash((self.is_distinct, self.kind, self.operands)) + + +class GlobalValue(NamedValue, _ConstOpMixin, _HasMetadata): + """ + A global value. + """ + name_prefix = '@' + deduplicate_name = False + + def __init__(self, *args, **kwargs): + super(GlobalValue, self).__init__(*args, **kwargs) + self.linkage = '' + self.storage_class = '' + self.section = '' + self.metadata = {} + + +class GlobalVariable(GlobalValue): + """ + A global variable. + """ + + def __init__(self, module, typ, name, addrspace=0): + assert isinstance(typ, types.Type) + super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace), + name=name) + self.value_type = typ + self.initializer = None + self.unnamed_addr = False + self.global_constant = False + self.addrspace = addrspace + self.align = None + self.parent.add_global(self) + + def descr(self, buf): + if self.global_constant: + kind = 'constant' + else: + kind = 'global' + + if not self.linkage: + # Default to external linkage + linkage = 'external' if self.initializer is None else '' + else: + linkage = self.linkage + + if linkage: + buf.append(linkage + " ") + if self.storage_class: + buf.append(self.storage_class + " ") + if self.unnamed_addr: + buf.append("unnamed_addr ") + if self.addrspace != 0: + buf.append('addrspace({0:d}) '.format(self.addrspace)) + + buf.append("{kind} {type}" .format(kind=kind, type=self.value_type)) + + if self.initializer is not None: + if self.initializer.type != self.value_type: + raise TypeError("got initializer of type %s " + "for global value type %s" + % (self.initializer.type, self.value_type)) + buf.append(" " + self.initializer.get_reference()) + elif linkage not in ('external', 'extern_weak'): + # emit 'undef' for non-external linkage GV + buf.append(" " + self.value_type(Undefined).get_reference()) + + if self.section: + buf.append(", section \"%s\"" % (self.section,)) + + if self.align is not None: + buf.append(", align %d" % (self.align,)) + + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + buf.append("\n") + + +class AttributeSet(set): + """A set of string attribute. + Only accept items listed in *_known*. + + Properties: + * Iterate in sorted order + """ + _known = () + + def __init__(self, args=()): + super().__init__() + if isinstance(args, str): + args = [args] + for name in args: + self.add(name) + + def _expand(self, name, typ): + return name + + def add(self, name): + if name not in self._known: + raise ValueError('unknown attr {!r} for {}'.format(name, self)) + return super(AttributeSet, self).add(name) + + def _to_list(self, typ): + return [self._expand(i, typ) for i in sorted(self)] + + +class FunctionAttributes(AttributeSet): + _known = frozenset([ + 'argmemonly', 'alwaysinline', 'builtin', 'cold', 'convergent', + 'inaccessiblememonly', 'inaccessiblemem_or_argmemonly', 'inlinehint', + 'jumptable', 'minsize', 'naked', 'nobuiltin', 'noduplicate', + 'noimplicitfloat', 'noinline', 'nonlazybind', 'norecurse', + 'noredzone', 'noreturn', 'nounwind', 'optnone', 'optsize', + 'readnone', 'readonly', 'returns_twice', 'sanitize_address', + 'sanitize_memory', 'sanitize_thread', 'ssp', + 'sspreg', 'sspstrong', 'uwtable']) + + def __init__(self, args=()): + self._alignstack = 0 + self._personality = None + super(FunctionAttributes, self).__init__(args) + + def add(self, name): + if ((name == 'alwaysinline' and 'noinline' in self) or + (name == 'noinline' and 'alwaysinline' in self)): + raise ValueError("Can't have alwaysinline and noinline") + + super().add(name) + + @property + def alignstack(self): + return self._alignstack + + @alignstack.setter + def alignstack(self, val): + assert val >= 0 + self._alignstack = val + + @property + def personality(self): + return self._personality + + @personality.setter + def personality(self, val): + assert val is None or isinstance(val, GlobalValue) + self._personality = val + + def _to_list(self, ret_type): + attrs = super()._to_list(ret_type) + if self.alignstack: + attrs.append('alignstack({0:d})'.format(self.alignstack)) + if self.personality: + attrs.append('personality {persty} {persfn}'.format( + persty=self.personality.type, + persfn=self.personality.get_reference())) + return attrs + + +class Function(GlobalValue): + """Represent a LLVM Function but does uses a Module as parent. + Global Values are stored as a set of dependencies (attribute `depends`). + """ + + def __init__(self, module, ftype, name): + assert isinstance(ftype, types.Type) + super(Function, self).__init__(module, ftype.as_pointer(), name=name) + self.ftype = ftype + self.scope = _utils.NameScope() + self.blocks = [] + self.attributes = FunctionAttributes() + self.args = tuple([Argument(self, t) + for t in ftype.args]) + self.return_value = ReturnValue(self, ftype.return_type) + self.parent.add_global(self) + self.calling_convention = '' + + @property + def module(self): + return self.parent + + @property + def entry_basic_block(self): + return self.blocks[0] + + @property + def basic_blocks(self): + return self.blocks + + def append_basic_block(self, name=''): + blk = Block(parent=self, name=name) + self.blocks.append(blk) + return blk + + def insert_basic_block(self, before, name=''): + """Insert block before + """ + blk = Block(parent=self, name=name) + self.blocks.insert(before, blk) + return blk + + def descr_prototype(self, buf): + """ + Describe the prototype ("head") of the function. + """ + state = "define" if self.blocks else "declare" + ret = self.return_value + args = ", ".join(str(a) for a in self.args) + name = self.get_reference() + attrs = ' ' + ' '.join(self.attributes._to_list( + self.ftype.return_type)) if self.attributes else '' + if any(self.args): + vararg = ', ...' if self.ftype.var_arg else '' + else: + vararg = '...' if self.ftype.var_arg else '' + linkage = self.linkage + cconv = self.calling_convention + prefix = " ".join(str(x) for x in [state, linkage, cconv, ret] if x) + metadata = self._stringify_metadata() + metadata = ' {}'.format(metadata) if metadata else '' + section = ' section "{}"'.format(self.section) if self.section else '' + pt_str = "{prefix} {name}({args}{vararg}){attrs}{section}{metadata}\n" + prototype = pt_str.format(prefix=prefix, name=name, args=args, + vararg=vararg, attrs=attrs, section=section, + metadata=metadata) + buf.append(prototype) + + def descr_body(self, buf): + """ + Describe of the body of the function. + """ + for blk in self.blocks: + blk.descr(buf) + + def descr(self, buf): + self.descr_prototype(buf) + if self.blocks: + buf.append("{\n") + self.descr_body(buf) + buf.append("}\n") + + def __str__(self): + buf = [] + self.descr(buf) + return "".join(buf) + + @property + def is_declaration(self): + return len(self.blocks) == 0 + + +class ArgumentAttributes(AttributeSet): + # List from + # https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes + _known = MappingProxyType({ + # True (emit type), + # False (emit name only) + 'byref': True, + 'byval': True, + 'elementtype': True, + 'immarg': False, + 'inalloca': True, + 'inreg': False, + 'nest': False, + 'noalias': False, + 'nocapture': False, + 'nofree': False, + 'nonnull': False, + 'noundef': False, + 'preallocated': True, + 'returned': False, + 'signext': False, + 'sret': True, + 'swiftasync': False, + 'swifterror': False, + 'swiftself': False, + 'zeroext': False, + }) + + def __init__(self, args=()): + self._align = 0 + self._dereferenceable = 0 + self._dereferenceable_or_null = 0 + super(ArgumentAttributes, self).__init__(args) + + def _expand(self, name, typ): + requires_type = self._known.get(name) + if requires_type: + return f"{name}({typ.pointee})" + else: + return name + + @property + def align(self): + return self._align + + @align.setter + def align(self, val): + assert isinstance(val, int) and val >= 0 + self._align = val + + @property + def dereferenceable(self): + return self._dereferenceable + + @dereferenceable.setter + def dereferenceable(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable = val + + @property + def dereferenceable_or_null(self): + return self._dereferenceable_or_null + + @dereferenceable_or_null.setter + def dereferenceable_or_null(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable_or_null = val + + def _to_list(self, typ): + attrs = super()._to_list(typ) + if self.align: + attrs.append('align {0:d}'.format(self.align)) + if self.dereferenceable: + attrs.append('dereferenceable({0:d})'.format(self.dereferenceable)) + if self.dereferenceable_or_null: + dref = 'dereferenceable_or_null({0:d})' + attrs.append(dref.format(self.dereferenceable_or_null)) + return attrs + + +class _BaseArgument(NamedValue): + def __init__(self, parent, typ, name=''): + assert isinstance(typ, types.Type) + super(_BaseArgument, self).__init__(parent, typ, name=name) + self.parent = parent + self.attributes = ArgumentAttributes() + + def __repr__(self): + return "" % (self.__class__.__name__, self.name, + self.type) + + def add_attribute(self, attr): + self.attributes.add(attr) + + +class Argument(_BaseArgument): + """ + The specification of a function argument. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1} {2}".format(self.type, ' '.join(attrs), + self.get_reference()) + else: + return "{0} {1}".format(self.type, self.get_reference()) + + +class ReturnValue(_BaseArgument): + """ + The specification of a function's return value. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1}".format(' '.join(attrs), self.type) + else: + return str(self.type) + + +class Block(NamedValue): + """ + A LLVM IR basic block. A basic block is a sequence of + instructions whose execution always goes from start to end. That + is, a control flow instruction (branch) can only appear as the + last instruction, and incoming branches can only jump to the first + instruction. + """ + + def __init__(self, parent, name=''): + super(Block, self).__init__(parent, types.LabelType(), name=name) + self.scope = parent.scope + self.instructions = [] + self.terminator = None + + @property + def is_terminated(self): + return self.terminator is not None + + @property + def function(self): + return self.parent + + @property + def module(self): + return self.parent.module + + def descr(self, buf): + buf.append("{0}:\n".format(self._format_name())) + buf += [" {0}\n".format(instr) for instr in self.instructions] + + def replace(self, old, new): + """Replace an instruction""" + if old.type != new.type: + raise TypeError("new instruction has a different type") + pos = self.instructions.index(old) + self.instructions.remove(old) + self.instructions.insert(pos, new) + + for bb in self.parent.basic_blocks: + for instr in bb.instructions: + instr.replace_usage(old, new) + + def _format_name(self): + # Per the LLVM Language Ref on identifiers, names matching the following + # regex do not need to be quoted: [%@][-a-zA-Z$._][-a-zA-Z$._0-9]* + # Otherwise, the identifier must be quoted and escaped. + name = self.name + if not _SIMPLE_IDENTIFIER_RE.match(name): + name = name.replace('\\', '\\5c').replace('"', '\\22') + name = '"{0}"'.format(name) + return name + + +class BlockAddress(Value): + """ + The address of a basic block. + """ + + def __init__(self, function, basic_block): + assert isinstance(function, Function) + assert isinstance(basic_block, Block) + self.type = types.IntType(8).as_pointer() + self.function = function + self.basic_block = basic_block + + def __str__(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def get_reference(self): + return "blockaddress({0}, {1})".format( + self.function.get_reference(), + self.basic_block.get_reference()) diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/__init__.py b/python_embeded/Lib/site-packages/llvmlite/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c681542e8dcde07432971c5d52540458b8defd1d --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/__init__.py @@ -0,0 +1,57 @@ +import sys + +import unittest +from unittest import TestCase + +import faulthandler + + +try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() +except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) + + +# Try to inject Numba's unittest customizations. +from llvmlite.tests import customize + + +def discover_tests(startdir): + """Discover test under a directory + """ + # Avoid importing unittest + loader = unittest.TestLoader() + suite = loader.discover(startdir) + return suite + + +def run_tests(suite=None, xmloutput=None, verbosity=1): + """ + args + ---- + - suite [TestSuite] + A suite of all tests to run + - xmloutput [str or None] + Path of XML output directory (optional) + - verbosity [int] + Verbosity level of tests output + + Returns the TestResult object after running the test *suite*. + """ + if suite is None: + suite = discover_tests("llvmlite.tests") + if xmloutput is not None: + import xmlrunner + runner = xmlrunner.XMLTestRunner(output=xmloutput) + else: + runner = None + prog = unittest.main(suite=suite, testRunner=runner, exit=False, + verbosity=verbosity) + return prog.result + + +def main(): + res = run_tests() + sys.exit(0 if res.wasSuccessful() else 1) diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/__main__.py b/python_embeded/Lib/site-packages/llvmlite/tests/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea3f4f1a50ed0b5c5d7477c730936b9c645bb25 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/__main__.py @@ -0,0 +1,3 @@ +from llvmlite.tests import main + +main() diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/customize.py b/python_embeded/Lib/site-packages/llvmlite/tests/customize.py new file mode 100644 index 0000000000000000000000000000000000000000..edcd0d7360103038b84e815fad5911dc71386dd0 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/customize.py @@ -0,0 +1,407 @@ +# XXX Ripped off from numba.tests; we should factor it out somewhere? + +import collections +import contextlib +import cProfile +from io import StringIO +import gc +import os +import multiprocessing +import sys +import time +import unittest +import warnings +from unittest import result, runner, signals + + +# "unittest.main" is really the TestProgram class! +# (defined in a module named itself "unittest.main"...) + +class NumbaTestProgram(unittest.main): + """ + A TestProgram subclass adding the following options: + * a -R option to enable reference leak detection + * a --profile option to enable profiling of the test run + + Currently the options are only added in 3.4+. + """ + + refleak = False + profile = False + multiprocess = False + + def __init__(self, *args, **kwargs): + self.discovered_suite = kwargs.pop('suite', None) + # HACK to force unittest not to change warning display options + # (so that NumbaWarnings don't appear all over the place) + sys.warnoptions.append(':x') + super(NumbaTestProgram, self).__init__(*args, **kwargs) + + def createTests(self): + if self.discovered_suite is not None: + self.test = self.discovered_suite + else: + super(NumbaTestProgram, self).createTests() + + def _getParentArgParser(self): + # NOTE: this hook only exists on Python 3.4+. The options won't be + # added in earlier versions (which use optparse - 3.3 - or getopt() + # - 2.x). + parser = super(NumbaTestProgram, self)._getParentArgParser() + if self.testRunner is None: + parser.add_argument('-R', '--refleak', dest='refleak', + action='store_true', + help='Detect reference / memory leaks') + parser.add_argument('-m', '--multiprocess', dest='multiprocess', + action='store_true', + help='Parallelize tests') + parser.add_argument('--profile', dest='profile', + action='store_true', + help='Profile the test run') + return parser + + def parseArgs(self, argv): + if sys.version_info < (3, 4): + # We want these options to work on all versions, emulate them. + if '-R' in argv: + argv.remove('-R') + self.refleak = True + if '-m' in argv: + argv.remove('-m') + self.multiprocess = True + super(NumbaTestProgram, self).parseArgs(argv) + if self.verbosity <= 0: + # We aren't interested in informational messages / warnings when + # running with '-q'. + self.buffer = True + + def runTests(self): + if self.refleak: + self.testRunner = RefleakTestRunner + + if not hasattr(sys, "gettotalrefcount"): + warnings.warn("detecting reference leaks requires a debug " + "build of Python, only memory leaks will be " + "detected") + + elif self.testRunner is None: + self.testRunner = unittest.TextTestRunner + + if self.multiprocess: + self.testRunner = ParallelTestRunner(self.testRunner, + verbosity=self.verbosity, + failfast=self.failfast, + buffer=self.buffer) + + def run_tests_real(): + super(NumbaTestProgram, self).runTests() + + if self.profile: + filename = os.path.splitext( + os.path.basename(sys.modules['__main__'].__file__) + )[0] + '.prof' + p = cProfile.Profile(timer=time.perf_counter) # 3.3+ + p.enable() + try: + p.runcall(run_tests_real) + finally: + p.disable() + print("Writing test profile data into %r" % (filename,)) + p.dump_stats(filename) + else: + run_tests_real() + + +# Monkey-patch unittest so that individual test modules get our custom +# options for free. +unittest.main = NumbaTestProgram + + +# The reference leak detection code is liberally taken and adapted from +# Python's own Lib/test/regrtest.py. + +def _refleak_cleanup(): + # Collect cyclic trash and read memory statistics immediately after. + try: + func1 = sys.getallocatedblocks + except AttributeError: + def func1(): + return 42 + try: + func2 = sys.gettotalrefcount + except AttributeError: + def func2(): + return 42 + + # Flush standard output, so that buffered data is sent to the OS and + # associated Python objects are reclaimed. + for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__): + if stream is not None: + stream.flush() + + sys._clear_type_cache() + # This also clears the various internal CPython freelists. + gc.collect() + return func1(), func2() + + +class ReferenceLeakError(RuntimeError): + pass + + +class IntPool(collections.defaultdict): + + def __missing__(self, key): + return key + + +class RefleakTestResult(runner.TextTestResult): + + warmup = 3 + repetitions = 6 + + def _huntLeaks(self, test): + self.stream.flush() + + repcount = self.repetitions + nwarmup = self.warmup + rc_deltas = [0] * (repcount - nwarmup) + alloc_deltas = [0] * (repcount - nwarmup) + # Preallocate ints likely to be stored in rc_deltas and alloc_deltas, + # to make sys.getallocatedblocks() less flaky. + _int_pool = IntPool() + for i in range(-200, 200): + _int_pool[i] + + alloc_before = rc_before = 0 + for i in range(repcount): + # Use a pristine, silent result object to avoid recursion + res = result.TestResult() + test.run(res) + # Poorly-written tests may fail when run several times. + # In this case, abort the refleak run and report the failure. + if not res.wasSuccessful(): + self.failures.extend(res.failures) + self.errors.extend(res.errors) + raise AssertionError + del res + alloc_after, rc_after = _refleak_cleanup() + if i >= nwarmup: + rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before] + alloc_deltas[i - + nwarmup] = _int_pool[alloc_after - + alloc_before] + alloc_before, rc_before = alloc_after, rc_after + return rc_deltas, alloc_deltas + + def addSuccess(self, test): + try: + rc_deltas, alloc_deltas = self._huntLeaks(test) + except AssertionError: + # Test failed when repeated + assert not self.wasSuccessful() + return + + # These checkers return False on success, True on failure + def check_rc_deltas(deltas): + return any(deltas) + + def check_alloc_deltas(deltas): + # At least 1/3rd of 0s + if 3 * deltas.count(0) < len(deltas): + return True + # Nothing else than 1s, 0s and -1s + if not set(deltas) <= set((1, 0, -1)): + return True + return False + + failed = False + + for deltas, item_name, checker in [ + (rc_deltas, 'references', check_rc_deltas), + (alloc_deltas, 'memory blocks', check_alloc_deltas)]: + if checker(deltas): + msg = '%s leaked %s %s, sum=%s' % ( + test, deltas, item_name, sum(deltas)) + failed = True + try: + raise ReferenceLeakError(msg) + except Exception: + exc_info = sys.exc_info() + if self.showAll: + self.stream.write("%s = %r " % (item_name, deltas)) + self.addFailure(test, exc_info) + + if not failed: + super(RefleakTestResult, self).addSuccess(test) + + +class RefleakTestRunner(runner.TextTestRunner): + resultclass = RefleakTestResult + + +def _flatten_suite(test): + """Expand suite into list of tests + """ + if isinstance(test, unittest.TestSuite): + tests = [] + for x in test: + tests.extend(_flatten_suite(x)) + return tests + else: + return [test] + + +class ParallelTestResult(runner.TextTestResult): + """ + A TestResult able to inject results from other results. + """ + + def add_results(self, result): + """ + Add the results from the other *result* to this result. + """ + self.stream.write(result.stream.getvalue()) + self.stream.flush() + self.testsRun += result.testsRun + self.failures.extend(result.failures) + self.errors.extend(result.errors) + self.skipped.extend(result.skipped) + self.expectedFailures.extend(result.expectedFailures) + self.unexpectedSuccesses.extend(result.unexpectedSuccesses) + + +class _MinimalResult(object): + """ + A minimal, picklable TestResult-alike object. + """ + + __slots__ = ( + 'failures', 'errors', 'skipped', 'expectedFailures', + 'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun') + + def fixup_case(self, case): + """ + Remove any unpicklable attributes from TestCase instance *case*. + """ + # Python 3.3 doesn't reset this one. + case._outcomeForDoCleanups = None + + def __init__(self, original_result): + for attr in self.__slots__: + setattr(self, attr, getattr(original_result, attr)) + for case, _ in self.expectedFailures: + self.fixup_case(case) + for case, _ in self.errors: + self.fixup_case(case) + for case, _ in self.failures: + self.fixup_case(case) + + +class _FakeStringIO(object): + """ + A trivial picklable StringIO-alike for Python 2. + """ + + def __init__(self, value): + self._value = value + + def getvalue(self): + return self._value + + +class _MinimalRunner(object): + """ + A minimal picklable object able to instantiate a runner in a + child process and run a test case with it. + """ + + def __init__(self, runner_cls, runner_args): + self.runner_cls = runner_cls + self.runner_args = runner_args + + # Python 2 doesn't know how to pickle instance methods, so we use __call__ + # instead. + + def __call__(self, test): + # Executed in child process + kwargs = self.runner_args + # Force recording of output in a buffer (it will be printed out + # by the parent). + kwargs['stream'] = StringIO() + runner = self.runner_cls(**kwargs) + result = runner._makeResult() + # Avoid child tracebacks when Ctrl-C is pressed. + signals.installHandler() + signals.registerResult(result) + result.failfast = runner.failfast + result.buffer = runner.buffer + with self.cleanup_object(test): + test(result) + # HACK as cStringIO.StringIO isn't picklable in 2.x + result.stream = _FakeStringIO(result.stream.getvalue()) + return _MinimalResult(result) + + @contextlib.contextmanager + def cleanup_object(self, test): + """ + A context manager which cleans up unwanted attributes on a test case + (or any other object). + """ + vanilla_attrs = set(test.__dict__) + try: + yield test + finally: + spurious_attrs = set(test.__dict__) - vanilla_attrs + for name in spurious_attrs: + del test.__dict__[name] + + +class ParallelTestRunner(runner.TextTestRunner): + """ + A test runner which delegates the actual running to a pool of child + processes. + """ + + resultclass = ParallelTestResult + + def __init__(self, runner_cls, **kwargs): + runner.TextTestRunner.__init__(self, **kwargs) + self.runner_cls = runner_cls + self.runner_args = kwargs + + def _run_inner(self, result): + # We hijack TextTestRunner.run()'s inner logic by passing this + # method as if it were a test case. + child_runner = _MinimalRunner(self.runner_cls, self.runner_args) + pool = multiprocessing.Pool() + imap = pool.imap_unordered + try: + for child_result in imap(child_runner, self._test_list): + result.add_results(child_result) + if child_result.shouldStop: + break + return result + finally: + # Kill the still active workers + pool.terminate() + pool.join() + + def run(self, test): + self._test_list = _flatten_suite(test) + # This will call self._run_inner() on the created result object, + # and print out the detailed test results at the end. + return super(ParallelTestRunner, self).run(self._run_inner) + + +try: + import faulthandler +except ImportError: + pass +else: + try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() + except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/refprune_proto.py b/python_embeded/Lib/site-packages/llvmlite/tests/refprune_proto.py new file mode 100644 index 0000000000000000000000000000000000000000..6df2355bdc349ed1ba69d209763f0f503d32cf24 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/refprune_proto.py @@ -0,0 +1,329 @@ +""" +Contains tests and a prototype implementation for the fanout algorithm in +the LLVM refprune pass. +""" + +try: + from graphviz import Digraph +except ImportError: + pass +from collections import defaultdict + +# The entry block. It's always the same. +ENTRY = "A" + + +# The following caseNN() functions returns a 3-tuple of +# (nodes, edges, expected). +# `nodes` maps BB nodes to incref/decref inside the block. +# `edges` maps BB nodes to their successor BB. +# `expected` maps BB-node with incref to a set of BB-nodes with the decrefs, or +# the value can be None, indicating invalid prune. + +def case1(): + edges = { + "A": ["B"], + "B": ["C", "D"], + "C": [], + "D": ["E", "F"], + "E": ["G"], + "F": [], + "G": ["H", "I"], + "I": ["G", "F"], + "H": ["J", "K"], + "J": ["L", "M"], + "K": [], + "L": ["Z"], + "M": ["Z", "O", "P"], + "O": ["Z"], + "P": ["Z"], + "Z": [], + } + nodes = defaultdict(list) + nodes["D"] = ["incref"] + nodes["H"] = ["decref"] + nodes["F"] = ["decref", "decref"] + expected = {"D": {"H", "F"}} + return nodes, edges, expected + + +def case2(): + edges = { + "A": ["B", "C"], + "B": ["C"], + "C": [], + } + nodes = defaultdict(list) + nodes["A"] = ["incref"] + nodes["B"] = ["decref"] + nodes["C"] = ["decref"] + expected = {"A": None} + return nodes, edges, expected + + +def case3(): + nodes, edges, _ = case1() + # adds an invalid edge + edges["H"].append("F") + expected = {"D": None} + return nodes, edges, expected + + +def case4(): + nodes, edges, _ = case1() + # adds an invalid edge + edges["H"].append("E") + expected = {"D": None} + return nodes, edges, expected + + +def case5(): + nodes, edges, _ = case1() + # adds backedge to go before incref + edges["B"].append("I") + expected = {"D": None} + return nodes, edges, expected + + +def case6(): + nodes, edges, _ = case1() + # adds backedge to go before incref + edges["I"].append("B") + expected = {"D": None} + return nodes, edges, expected + + +def case7(): + nodes, edges, _ = case1() + # adds forward jump outside + edges["I"].append("M") + expected = {"D": None} + return nodes, edges, expected + + +def case8(): + edges = { + "A": ["B", "C"], + "B": ["C"], + "C": [], + } + nodes = defaultdict(list) + nodes["A"] = ["incref"] + nodes["C"] = ["decref"] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case9(): + nodes, edges, _ = case8() + # adds back edge + edges["C"].append("B") + expected = {"A": None} + return nodes, edges, expected + + +def case10(): + nodes, edges, _ = case8() + # adds back edge to A + edges["C"].append("A") + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case11(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = [] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case12(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = ["A"] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case13(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = ["B"] + expected = {"A": None} + return nodes, edges, expected + + +def make_predecessor_map(edges): + d = defaultdict(set) + for src, outgoings in edges.items(): + for dst in outgoings: + d[dst].add(src) + return d + + +class FanoutAlgorithm: + def __init__(self, nodes, edges, verbose=False): + self.nodes = nodes + self.edges = edges + self.rev_edges = make_predecessor_map(edges) + self.print = print if verbose else self._null_print + + def run(self): + return self.find_fanout_in_function() + + def _null_print(self, *args, **kwargs): + pass + + def find_fanout_in_function(self): + got = {} + for cur_node in self.edges: + for incref in (x for x in self.nodes[cur_node] if x == "incref"): + decref_blocks = self.find_fanout(cur_node) + self.print(">>", cur_node, "===", decref_blocks) + got[cur_node] = decref_blocks + return got + + def find_fanout(self, head_node): + decref_blocks = self.find_decref_candidates(head_node) + self.print("candidates", decref_blocks) + if not decref_blocks: + return None + if not self.verify_non_overlapping( + head_node, decref_blocks, entry=ENTRY + ): + return None + return set(decref_blocks) + + def verify_non_overlapping(self, head_node, decref_blocks, entry): + self.print("verify_non_overlapping".center(80, "-")) + # reverse walk for each decref_blocks + # they should end at head_node + todo = list(decref_blocks) + while todo: + cur_node = todo.pop() + visited = set() + + workstack = [cur_node] + del cur_node + while workstack: + cur_node = workstack.pop() + self.print("cur_node", cur_node, "|", workstack) + if cur_node in visited: + continue # skip + if cur_node == entry: + # Entry node + self.print( + "!! failed because we arrived at entry", cur_node + ) + return False + visited.add(cur_node) + # check all predecessors + self.print( + f" {cur_node} preds {self.get_predecessors(cur_node)}" + ) + for pred in self.get_predecessors(cur_node): + if pred in decref_blocks: + # reject because there's a predecessor in decref_blocks + self.print( + "!! reject because predecessor in decref_blocks" + ) + return False + if pred != head_node: + + workstack.append(pred) + + return True + + def get_successors(self, node): + return tuple(self.edges[node]) + + def get_predecessors(self, node): + return tuple(self.rev_edges[node]) + + def has_decref(self, node): + return "decref" in self.nodes[node] + + def walk_child_for_decref( + self, cur_node, path_stack, decref_blocks, depth=10 + ): + indent = " " * len(path_stack) + self.print(indent, "walk", path_stack, cur_node) + if depth <= 0: + return False # missing + if cur_node in path_stack: + if cur_node == path_stack[0]: + return False # reject interior node backedge + return True # skip + if self.has_decref(cur_node): + decref_blocks.add(cur_node) + self.print(indent, "found decref") + return True + + depth -= 1 + path_stack += (cur_node,) + found = False + for child in self.get_successors(cur_node): + if not self.walk_child_for_decref( + child, path_stack, decref_blocks + ): + found = False + break + else: + found = True + + self.print(indent, f"ret {found}") + return found + + def find_decref_candidates(self, cur_node): + # Forward pass + self.print("find_decref_candidates".center(80, "-")) + path_stack = (cur_node,) + found = False + decref_blocks = set() + for child in self.get_successors(cur_node): + if not self.walk_child_for_decref( + child, path_stack, decref_blocks + ): + found = False + break + else: + found = True + if not found: + return set() + else: + return decref_blocks + + +def check_once(): + nodes, edges, expected = case13() + + # Render graph + G = Digraph() + for node in edges: + G.node(node, shape="rect", label=f"{node}\n" + r"\l".join(nodes[node])) + for node, children in edges.items(): + for child in children: + G.edge(node, child) + + G.view() + + algo = FanoutAlgorithm(nodes, edges, verbose=True) + got = algo.run() + assert expected == got + + +def check_all(): + for k, fn in list(globals().items()): + if k.startswith("case"): + print(f"{fn}".center(80, "-")) + nodes, edges, expected = fn() + algo = FanoutAlgorithm(nodes, edges) + got = algo.run() + assert expected == got + print("ALL PASSED") + + +if __name__ == "__main__": + # check_once() + check_all() diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/test_binding.py b/python_embeded/Lib/site-packages/llvmlite/tests/test_binding.py new file mode 100644 index 0000000000000000000000000000000000000000..87ae72dc95d950de0e1be46698b2c6fc982ed0a9 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/test_binding.py @@ -0,0 +1,3208 @@ +import ctypes +import threading +from ctypes import CFUNCTYPE, c_int, c_int32 +from ctypes.util import find_library +import gc +import locale +import os +import platform +import re +import subprocess +import sys +import unittest +from contextlib import contextmanager +from tempfile import mkstemp + +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite.binding import ffi +from llvmlite.tests import TestCase + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled + +# arvm7l needs extra ABI symbols to link successfully +if platform.machine() == 'armv7l': + llvm.load_library_permanently('libgcc_s.so.1') + + +def no_de_locale(): + cur = locale.setlocale(locale.LC_ALL) + try: + locale.setlocale(locale.LC_ALL, 'de_DE') + except locale.Error: + return True + else: + return False + finally: + locale.setlocale(locale.LC_ALL, cur) + + +asm_sum = r""" + ; ModuleID = '' + source_filename = "asm_sum.c" + target triple = "{triple}" + %struct.glob_type = type {{ i64, [2 x i64]}} + %struct.glob_type_vec = type {{ i64, <2 x i64>}} + + @glob = global i32 0 + @glob_b = global i8 0 + @glob_f = global float 1.5 + @glob_struct = global %struct.glob_type {{i64 0, [2 x i64] [i64 0, i64 0]}} + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + %.4 = add i32 0, %.3 + ret i32 %.4 + }} + """ + +asm_sum2 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_sum3 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i64 @sum(i64 %.1, i64 %.2) {{ + %.3 = add i64 %.1, %.2 + %.4 = add i64 5, %.3 + %.5 = add i64 -5, %.4 + ret i64 %.5 + }} + """ + +asm_sum4 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 0 + }} + """ + +asm_mul = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + define i32 @mul(i32 %.1, i32 %.2) {{ + %.3 = mul i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_square_sum = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + declare i32 @sum(i32, i32) + define i32 @square_sum(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = mul i32 %.3, %.3 + ret i32 %.4 + }} + """ + +asm_getversion = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i8* @Py_GetVersion() + + define void @getversion(i32 %.1, i32 %.2) {{ + %1 = call i8* @Py_GetVersion() + ret void + }} + """ + +if platform.python_implementation() == 'PyPy': + asm_getversion = asm_getversion.replace('Py_GetVersion', 'PyPy_GetVersion') + +# `fadd` used on integer inputs +asm_parse_error = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = fadd i32 %.1, %.2 + ret i32 %.3 + }} + """ + +# "%.bug" definition references itself +asm_verification_fail = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @sum() {{ + %.bug = add i32 1, %.bug + ret void + }} + """ + +asm_sum_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + """ + +asm_vararg_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @vararg(i32 %.1, ...) + """ + +asm_double_inaccurate = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd fp128 0xLF3CB1CCF26FBC178452FB4EC7F91DEAD, 0xL00000000000000000000000000000001 + ret void + }} + """ # noqa E501 + +asm_double_locale = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd double 0.0, 3.14 + ret void + }} + """ + + +asm_inlineasm = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + call void asm sideeffect "nop", ""() + ret void + }} + """ + +asm_inlineasm2 = """ + ; ModuleID = '' + target triple = "{triple}" + + define void @inlineme() {{ + ret void + }} + + define i32 @caller(i32 %.1, i32 %.2) {{ + entry: + %stack = alloca i32 + store i32 %.1, i32* %stack + br label %main + main: + %loaded = load i32, i32* %stack + %.3 = add i32 %loaded, %.2 + %.4 = add i32 0, %.3 + call void @inlineme() + ret i32 %.4 + }} +""" + +asm_inlineasm3 = """ +; ModuleID = 'test.c' +source_filename = "test.c" +target triple = "{triple}" + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @inlineme() noinline !dbg !15 {{ + ret void, !dbg !18 +}} + +; Function Attrs: noinline nounwind optnone ssp uwtable +define i32 @foo(i32 %0, i32 %1) !dbg !19 {{ + %3 = alloca i32, align 4 + %4 = alloca i32, align 4 + store i32 %0, i32* %3, align 4 + call void @llvm.dbg.declare(metadata i32* %3, metadata !23, metadata !DIExpression()), !dbg !24 + store i32 %1, i32* %4, align 4 + call void @llvm.dbg.declare(metadata i32* %4, metadata !25, metadata !DIExpression()), !dbg !26 + call void @inlineme(), !dbg !27 + %5 = load i32, i32* %3, align 4, !dbg !28 + %6 = load i32, i32* %4, align 4, !dbg !29 + %7 = add nsw i32 %5, %6, !dbg !30 + ret i32 %7, !dbg !31 +}} + +; Function Attrs: nofree nosync nounwind readnone speculatable willreturn +declare void @llvm.dbg.declare(metadata, metadata, metadata) #1 + +attributes #1 = {{ nofree nosync nounwind readnone speculatable willreturn }} + +!llvm.module.flags = !{{!1, !2, !3, !4, !5, !6, !7, !8, !9, !10}} +!llvm.dbg.cu = !{{!11}} +!llvm.ident = !{{!14}} + +!0 = !{{i32 2, !"SDK Version", [2 x i32] [i32 12, i32 3]}} +!1 = !{{i32 7, !"Dwarf Version", i32 4}} +!2 = !{{i32 2, !"Debug Info Version", i32 3}} +!3 = !{{i32 1, !"wchar_size", i32 4}} +!4 = !{{i32 1, !"branch-target-enforcement", i32 0}} +!5 = !{{i32 1, !"sign-return-address", i32 0}} +!6 = !{{i32 1, !"sign-return-address-all", i32 0}} +!7 = !{{i32 1, !"sign-return-address-with-bkey", i32 0}} +!8 = !{{i32 7, !"PIC Level", i32 2}} +!9 = !{{i32 7, !"uwtable", i32 1}} +!10 = !{{i32 7, !"frame-pointer", i32 1}} +!11 = distinct !DICompileUnit(language: DW_LANG_C99, file: !12, producer: "Apple clang version 13.1.6 (clang-1316.0.21.2.3)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !13, splitDebugInlining: false, nameTableKind: None, sysroot: "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk", sdk: "MacOSX.sdk") +!12 = !DIFile(filename: "test.c", directory: "/") +!13 = !{{}} +!14 = !{{!"Apple clang version 13.1.6 (clang-1316.0.21.2.3)"}} +!15 = distinct !DISubprogram(name: "inlineme", scope: !12, file: !12, line: 1, type: !16, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!16 = !DISubroutineType(types: !17) +!17 = !{{null}} +!18 = !DILocation(line: 1, column: 22, scope: !15) +!19 = distinct !DISubprogram(name: "foo", scope: !12, file: !12, line: 3, type: !20, scopeLine: 3, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!20 = !DISubroutineType(types: !21) +!21 = !{{!22, !22, !22}} +!22 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) +!23 = !DILocalVariable(name: "a", arg: 1, scope: !19, file: !12, line: 3, type: !22) +!24 = !DILocation(line: 3, column: 13, scope: !19) +!25 = !DILocalVariable(name: "b", arg: 2, scope: !19, file: !12, line: 3, type: !22) +!26 = !DILocation(line: 3, column: 20, scope: !19) +!27 = !DILocation(line: 4, column: 5, scope: !19) +!28 = !DILocation(line: 5, column: 12, scope: !19) +!29 = !DILocation(line: 5, column: 16, scope: !19) +!30 = !DILocation(line: 5, column: 14, scope: !19) +!31 = !DILocation(line: 5, column: 5, scope: !19) +""" # noqa E501 + +licm_asm = r""" +; ModuleID = "" +target triple = "{triple}" + +define double @licm(i32 %0) {{ + %2 = alloca i32, align 4 + %3 = alloca double, align 8 + %4 = alloca i32, align 4 + %5 = alloca double, align 8 + store i32 %0, i32* %2, align 4 + store double 0.000000e+00, double* %3, align 8 + store i32 0, i32* %4, align 4 + br label %6 + +6: ; preds = %14, %1 + %7 = load i32, i32* %4, align 4 + %8 = load i32, i32* %2, align 4 + %9 = icmp slt i32 %7, %8 + br i1 %9, label %10, label %17 + +10: ; preds = %6 + store double 7.000000e+00, double* %5, align 8 + %11 = load double, double* %5, align 8 + %12 = load double, double* %3, align 8 + %13 = fadd double %12, %11 + store double %13, double* %3, align 8 + br label %14 + +14: ; preds = %10 + %15 = load i32, i32* %4, align 4 + %16 = add nsw i32 %15, 1 + store i32 %16, i32* %4, align 4 + br label %6 + +17: ; preds = %6 + %18 = load double, double* %3, align 8 + ret double %18 +}} +""" # noqa E501 + +asm_global_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = global i32 undef + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + +asm_ext_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = external global i32 + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + + +asm_nonalphanum_blocklabel = """; ModuleID = "" +target triple = "unknown-unknown-unknown" +target datalayout = "" + +define i32 @"foo"() +{ +"<>!*''#": + ret i32 12345 +} +""" # noqa W291 # trailing space needed for match later + + +asm_null_constant = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo(i64* %.1) {{ + ret void + }} + + define void @bar() {{ + call void @foo(i64* null) + ret void + }} +""" + + +riscv_asm_ilp32 = [ + 'addi\tsp, sp, -16', + 'sw\ta1, 8(sp)', + 'sw\ta2, 12(sp)', + 'fld\tft0, 8(sp)', + 'fmv.w.x\tft1, a0', + 'fcvt.d.s\tft1, ft1', + 'fadd.d\tft0, ft1, ft0', + 'fsd\tft0, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32f = [ + 'addi\tsp, sp, -16', + 'sw\ta0, 8(sp)', + 'sw\ta1, 12(sp)', + 'fld\tft0, 8(sp)', + 'fcvt.d.s\tft1, fa0', + 'fadd.d\tft0, ft1, ft0', + 'fsd\tft0, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32d = [ + 'fcvt.d.s\tft0, fa0', + 'fadd.d\tfa0, ft0, fa1', + 'ret' +] + + +asm_attributes = r""" +declare void @a_readonly_func(i8 *) readonly + +declare i8* @a_arg0_return_func(i8* returned, i32*) +""" + +asm_alloca_optnone = r""" +define double @foo(i32 %i, double %j) optnone noinline { + %I = alloca i32 ; [#uses=4] + %J = alloca double ; [#uses=2] + store i32 %i, i32* %I + store double %j, double* %J + %t1 = load i32, i32* %I ; [#uses=1] + %t2 = add i32 %t1, 1 ; [#uses=1] + store i32 %t2, i32* %I + %t3 = load i32, i32* %I ; [#uses=1] + %t4 = sitofp i32 %t3 to double ; [#uses=1] + %t5 = load double, double* %J ; [#uses=1] + %t6 = fmul double %t4, %t5 ; [#uses=1] + ret double %t6 +} +""" + +asm_declaration = r""" +declare void @test_declare(i32* ) +""" + +# This produces the following output from objdump: +# +# $ objdump -D 632.elf +# +# 632.elf: file format elf64-x86-64 +# +# +# Disassembly of section .text: +# +# 0000000000000000 <__arybo>: +# 0: 48 c1 e2 20 shl $0x20,%rdx +# 4: 48 09 c2 or %rax,%rdx +# 7: 48 89 d0 mov %rdx,%rax +# a: 48 c1 c0 3d rol $0x3d,%rax +# e: 48 31 d0 xor %rdx,%rax +# 11: 48 b9 01 20 00 04 80 movabs $0x7010008004002001,%rcx +# 18: 00 10 70 +# 1b: 48 0f af c8 imul %rax,%rcx + +issue_632_elf = \ + "7f454c4602010100000000000000000001003e00010000000000000000000000000000" \ + "0000000000e0000000000000000000000040000000000040000500010048c1e2204809" \ + "c24889d048c1c03d4831d048b90120000480001070480fafc800000000000000000000" \ + "0000000000000000000000000000002f0000000400f1ff000000000000000000000000" \ + "00000000070000001200020000000000000000001f00000000000000002e7465787400" \ + "5f5f617279626f002e6e6f74652e474e552d737461636b002e737472746162002e7379" \ + "6d746162003c737472696e673e00000000000000000000000000000000000000000000" \ + "0000000000000000000000000000000000000000000000000000000000000000000000" \ + "00000000000000001f0000000300000000000000000000000000000000000000a80000" \ + "0000000000380000000000000000000000000000000100000000000000000000000000" \ + "000001000000010000000600000000000000000000000000000040000000000000001f" \ + "000000000000000000000000000000100000000000000000000000000000000f000000" \ + "01000000000000000000000000000000000000005f0000000000000000000000000000" \ + "0000000000000000000100000000000000000000000000000027000000020000000000" \ + "0000000000000000000000000000600000000000000048000000000000000100000002" \ + "00000008000000000000001800000000000000" + + +issue_632_text = \ + "48c1e2204809c24889d048c1c03d4831d048b90120000480001070480fafc8" + + +asm_tli_exp2 = r""" +; ModuleID = '' +source_filename = "" +target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-pc-windows-msvc" + +declare float @llvm.exp2.f32(float %casted) + +define float @foo(i16 %arg) { +entry: + %casted = sitofp i16 %arg to float + %ret = call float @llvm.exp2.f32(float %casted) + ret float %ret +} +""" # noqa E501 + +asm_phi_blocks = r""" +; ModuleID = '' +target triple = "{triple}" + +define void @foo(i32 %N) {{ + ; unnamed block for testing + %cmp4 = icmp sgt i32 %N, 0 + br i1 %cmp4, label %for.body, label %for.cond.cleanup + +for.cond.cleanup: + ret void + +for.body: + %i.05 = phi i32 [ %inc, %for.body ], [ 0, %0 ] + %inc = add nuw nsw i32 %i.05, 1 + %exitcond.not = icmp eq i32 %inc, %N + br i1 %exitcond.not, label %for.cond.cleanup, label %for.body +}} +""" + +asm_cpp_class = r""" +; Source C++ +;----------------------------------------- +; class MyClass; +; +; class MyClassDefined{ +; MyClass *member; +; MyClass *m2; +; MyClass *m3; +; }; +; +; void foo(MyClass *c, MyClassDefined){ } +;----------------------------------------- +; LLVM-IR by: clang -arch arm64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" +target triple = "arm64-apple-macosx13.3.0" + +%class.MyClass = type opaque +%class.MyClassDefined = type { %class.MyClass*, %class.MyClass*, %class.MyClass* } + +; Function Attrs: noinline nounwind optnone ssp uwtable(sync) +define void @_Z3fooP7MyClass14MyClassDefined(%class.MyClass* noundef %0, %class.MyClassDefined* noundef %1) { + %3 = alloca %class.MyClass*, align 8 + store %class.MyClass* %0, %class.MyClass** %3, align 8 + ret void +} + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!llvm.ident = !{!9} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 8, !"branch-target-enforcement", i32 0} +!3 = !{i32 8, !"sign-return-address", i32 0} +!4 = !{i32 8, !"sign-return-address-all", i32 0} +!5 = !{i32 8, !"sign-return-address-with-bkey", i32 0} +!6 = !{i32 7, !"PIC Level", i32 2} +!7 = !{i32 7, !"uwtable", i32 1} +!8 = !{i32 7, !"frame-pointer", i32 1} +!9 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + +asm_cpp_vector = r"""; Source C++ +;----------------------------------------- + +; struct Vector2D{ +; float x, y; +; }; +; +; void foo(Vector2D vec, Vector2D *out) { +; *out = vec; +; } +;----------------------------------------- +; LLVM-IR by: clang -arch x86_64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-apple-macosx13.3.0" + +%struct.Vector2D = type { float, float } + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @_Z3foo8Vector2DPS_(<2 x float> %0, %struct.Vector2D* noundef %1) #0 { + %3 = alloca %struct.Vector2D, align 4 + %4 = alloca %struct.Vector2D*, align 8 + %5 = bitcast %struct.Vector2D* %3 to <2 x float>* + store <2 x float> %0, <2 x float>* %5, align 4 + store %struct.Vector2D* %1, %struct.Vector2D** %4, align 8 + %6 = load %struct.Vector2D*, %struct.Vector2D** %4, align 8 + %7 = bitcast %struct.Vector2D* %6 to i8* + %8 = bitcast %struct.Vector2D* %3 to i8* + call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %7, i8* align 4 %8, i64 8, i1 false) + ret void +} + +; Function Attrs: argmemonly nofree nounwind willreturn +declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg) #1 + +attributes #0 = { noinline nounwind optnone ssp uwtable "darwin-stkchk-strong-link" "frame-pointer"="all" "min-legal-vector-width"="64" "no-trapping-math"="true" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "tune-cpu"="generic" } +attributes #1 = { argmemonly nofree nounwind willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4} +!llvm.ident = !{!5} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"PIC Level", i32 2} +!3 = !{i32 7, !"uwtable", i32 2} +!4 = !{i32 7, !"frame-pointer", i32 2} +!5 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + + +class BaseTest(TestCase): + + def setUp(self): + llvm.initialize() + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + gc.collect() + self.old_garbage = gc.garbage[:] + gc.garbage[:] = [] + + def tearDown(self): + # Test that no uncollectable objects were created + # (llvmlite objects have a __del__ so a reference cycle could + # create some). + gc.collect() + self.assertEqual(gc.garbage, []) + # This will probably put any existing garbage in gc.garbage again + del self.old_garbage + + def module(self, asm=asm_sum, context=None): + asm = asm.format(triple=llvm.get_default_triple()) + mod = llvm.parse_assembly(asm, context) + return mod + + def glob(self, name='glob', mod=None): + if mod is None: + mod = self.module() + return mod.get_global_variable(name) + + def target_machine(self, *, jit): + target = llvm.Target.from_default_triple() + return target.create_target_machine(jit=jit) + + +class TestDependencies(BaseTest): + """ + Test DLL dependencies are within a certain expected set. + """ + + @unittest.skipUnless(sys.platform.startswith('linux'), + "Linux-specific test") + @unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'), + "Distribution-specific test") + def test_linux(self): + lib_path = ffi.lib._name + env = os.environ.copy() + env['LANG'] = 'C' + p = subprocess.Popen(["objdump", "-p", lib_path], + stdout=subprocess.PIPE, env=env) + out, _ = p.communicate() + self.assertEqual(0, p.returncode) + # Parse library dependencies + lib_pat = re.compile(r'^([+-_a-zA-Z0-9]+)\.so(?:\.\d+){0,3}$') + deps = set() + for line in out.decode().splitlines(): + parts = line.split() + if parts and parts[0] == 'NEEDED': + dep = parts[1] + m = lib_pat.match(dep) + if len(parts) != 2 or not m: + self.fail("invalid NEEDED line: %r" % (line,)) + deps.add(m.group(1)) + # Sanity check that our dependencies were parsed ok + if 'libc' not in deps or 'libpthread' not in deps: + self.fail("failed parsing dependencies? got %r" % (deps,)) + # Ensure all dependencies are expected + allowed = set(['librt', 'libdl', 'libpthread', 'libz', 'libm', + 'libgcc_s', 'libc', 'ld-linux', 'ld64']) + if platform.python_implementation() == 'PyPy': + allowed.add('libtinfo') + + for dep in deps: + if not dep.startswith('ld-linux-') and dep not in allowed: + self.fail("unexpected dependency %r in %r" % (dep, deps)) + + +class TestRISCVABI(BaseTest): + """ + Test calling convention of floating point arguments of RISC-V + using different ABI. + """ + triple = "riscv32-unknown-linux" + + def setUp(self): + super().setUp() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + + def check_riscv_target(self): + try: + llvm.Target.from_triple(self.triple) + except RuntimeError as e: + if "No available targets are compatible with triple" in str(e): + self.skipTest("RISCV target unsupported by linked LLVM.") + else: + raise e + + def riscv_target_machine(self, **kwarg): + lltarget = llvm.Target.from_triple(self.triple) + return lltarget.create_target_machine(**kwarg) + + def fpadd_ll_module(self): + f64 = ir.DoubleType() + f32 = ir.FloatType() + fnty = ir.FunctionType(f64, (f32, f64)) + module = ir.Module() + func = ir.Function(module, fnty, name="fpadd") + block = func.append_basic_block() + builder = ir.IRBuilder(block) + a, b = func.args + arg0 = builder.fpext(a, f64) + result = builder.fadd(arg0, b) + builder.ret(result) + + llmod = llvm.parse_assembly(str(module)) + llmod.verify() + return llmod + + def break_up_asm(self, asm): + asm_list = [] + for line in asm.splitlines(): + s_line = line.strip() + if not (s_line.startswith(".") or s_line.startswith("fpadd") + or s_line == ""): + asm_list.append(s_line) + return asm_list + + def test_rv32d_ilp32(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32) + + def test_rv32d_ilp32f(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32f") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32f) + + def test_rv32d_ilp32d(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32d") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32d) + + +class TestMisc(BaseTest): + """ + Test miscellaneous functions in llvm.binding. + """ + + def test_parse_assembly(self): + self.module(asm_sum) + + def test_parse_assembly_error(self): + with self.assertRaises(RuntimeError) as cm: + self.module(asm_parse_error) + s = str(cm.exception) + self.assertIn("parsing error", s) + self.assertIn("invalid operand type", s) + + def test_nonalphanum_block_name(self): + mod = ir.Module() + ft = ir.FunctionType(ir.IntType(32), []) + fn = ir.Function(mod, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block(name="<>!*''#")) + bd.ret(ir.Constant(ir.IntType(32), 12345)) + asm = str(mod) + self.assertEqual(asm, asm_nonalphanum_blocklabel) + + def test_global_context(self): + gcontext1 = llvm.context.get_global_context() + gcontext2 = llvm.context.get_global_context() + assert gcontext1 == gcontext2 + + def test_dylib_symbols(self): + llvm.add_symbol("__xyzzy", 1234) + llvm.add_symbol("__xyzzy", 5678) + addr = llvm.address_of_symbol("__xyzzy") + self.assertEqual(addr, 5678) + addr = llvm.address_of_symbol("__foobar") + self.assertIs(addr, None) + + def test_get_default_triple(self): + triple = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + def test_get_process_triple(self): + # Sometimes we get synonyms for PPC + def normalize_ppc(arch): + if arch == 'powerpc64le': + return 'ppc64le' + else: + return arch + + triple = llvm.get_process_triple() + default = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + default_arch = normalize_ppc(default.split('-')[0]) + triple_arch = normalize_ppc(triple.split('-')[0]) + # Arch must be equal + self.assertEqual(default_arch, triple_arch) + + def test_get_host_cpu_features(self): + features = llvm.get_host_cpu_features() + # Check the content of `features` + self.assertIsInstance(features, dict) + self.assertIsInstance(features, llvm.FeatureMap) + for k, v in features.items(): + self.assertIsInstance(k, str) + self.assertTrue(k) # single feature string cannot be empty + self.assertIsInstance(v, bool) + self.assertIsInstance(features.flatten(), str) + + re_term = r"[+\-][a-zA-Z0-9\._-]+" + regex = r"^({0}|{0}(,{0})*)?$".format(re_term) + # quick check for our regex + self.assertIsNotNone(re.match(regex, "")) + self.assertIsNotNone(re.match(regex, "+aa")) + self.assertIsNotNone(re.match(regex, "+a,-bb")) + # check CpuFeature.flatten() + if len(features) == 0: + self.assertEqual(features.flatten(), "") + else: + self.assertIsNotNone(re.match(regex, features.flatten())) + + def test_get_host_cpu_name(self): + cpu = llvm.get_host_cpu_name() + self.assertIsInstance(cpu, str) + self.assertTrue(cpu) + + def test_initfini(self): + code = """if 1: + from llvmlite import binding as llvm + + llvm.initialize() + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + llvm.shutdown() + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_set_option(self): + # We cannot set an option multiple times (LLVM would exit() the + # process), so run the code in a subprocess. + code = """if 1: + from llvmlite import binding as llvm + + llvm.set_option("progname", "-debug-pass=Disabled") + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_version(self): + major, minor, patch = llvm.llvm_version_info + # one of these can be valid + valid = (15, 16) + self.assertIn(major, valid) + self.assertIn(patch, range(8)) + + def test_check_jit_execution(self): + llvm.check_jit_execution() + + @unittest.skipIf(no_de_locale(), "Locale not available") + def test_print_double_locale(self): + m = self.module(asm_double_locale) + expect = str(m) + # Change the locale so that comma is used as decimal-point + # to trigger the LLVM bug (llvmlite issue #80) + locale.setlocale(locale.LC_ALL, 'de_DE') + # The LLVM bug is trigged by print the module with double constant + got = str(m) + # Changing the locale should not affect the LLVM IR + self.assertEqual(expect, got) + + def test_no_accidental_warnings(self): + code = "from llvmlite import binding" + flags = "-Werror" + cmdargs = [sys.executable, flags, "-c", code] + subprocess.check_call(cmdargs) + + +class TestModuleRef(BaseTest): + + def test_str(self): + mod = self.module() + s = str(mod).strip() + self.assertTrue(s.startswith('; ModuleID ='), s) + + def test_close(self): + mod = self.module() + str(mod) + mod.close() + with self.assertRaises(ctypes.ArgumentError): + str(mod) + mod.close() + + def test_with(self): + mod = self.module() + str(mod) + with mod: + str(mod) + with self.assertRaises(ctypes.ArgumentError): + str(mod) + with self.assertRaises(RuntimeError): + with mod: + pass + + def test_name(self): + mod = self.module() + mod.name = "foo" + self.assertEqual(mod.name, "foo") + mod.name = "bar" + self.assertEqual(mod.name, "bar") + + def test_source_file(self): + mod = self.module() + self.assertEqual(mod.source_file, "asm_sum.c") + + def test_data_layout(self): + mod = self.module() + s = mod.data_layout + self.assertIsInstance(s, str) + mod.data_layout = s + self.assertEqual(s, mod.data_layout) + + def test_triple(self): + mod = self.module() + s = mod.triple + self.assertEqual(s, llvm.get_default_triple()) + mod.triple = '' + self.assertEqual(mod.triple, '') + + def test_verify(self): + # Verify successful + mod = self.module() + self.assertIs(mod.verify(), None) + # Verify failed + mod = self.module(asm_verification_fail) + with self.assertRaises(RuntimeError) as cm: + mod.verify() + s = str(cm.exception) + self.assertIn("%.bug = add i32 1, %.bug", s) + + def test_get_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertIsInstance(fn, llvm.ValueRef) + self.assertEqual(fn.name, "sum") + + with self.assertRaises(NameError): + mod.get_function("foo") + + # Check that fn keeps the module instance alive + del mod + str(fn.module) + + def test_get_struct_type(self): + mod = self.module() + st_ty = mod.get_struct_type("struct.glob_type") + self.assertEqual(st_ty.name, "struct.glob_type") + # also match struct names of form "%struct.glob_type.{some_index}" + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(st_ty))) + + with self.assertRaises(NameError): + mod.get_struct_type("struct.doesnt_exist") + + def test_get_global_variable(self): + mod = self.module() + gv = mod.get_global_variable("glob") + self.assertIsInstance(gv, llvm.ValueRef) + self.assertEqual(gv.name, "glob") + + with self.assertRaises(NameError): + mod.get_global_variable("bar") + + # Check that gv keeps the module instance alive + del mod + str(gv.module) + + def test_global_variables(self): + mod = self.module() + it = mod.global_variables + del mod + globs = sorted(it, key=lambda value: value.name) + self.assertEqual(len(globs), 4) + self.assertEqual([g.name for g in globs], + ["glob", "glob_b", "glob_f", "glob_struct"]) + + def test_functions(self): + mod = self.module() + it = mod.functions + del mod + funcs = list(it) + self.assertEqual(len(funcs), 1) + self.assertEqual(funcs[0].name, "sum") + + def test_structs(self): + mod = self.module() + it = mod.struct_types + del mod + structs = list(it) + self.assertEqual(len(structs), 1) + self.assertIsNotNone(re.match(r'struct\.glob_type(\.[\d]+)?', + structs[0].name)) + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(structs[0]))) + + def test_link_in(self): + dest = self.module() + src = self.module(asm_mul) + dest.link_in(src) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.get_function("mul") + dest.close() + with self.assertRaises(ctypes.ArgumentError): + src.get_function("mul") + + def test_link_in_preserve(self): + dest = self.module() + src2 = self.module(asm_mul) + dest.link_in(src2, preserve=True) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.close() + self.assertEqual(sorted(f.name for f in src2.functions), ["mul"]) + src2.get_function("mul") + + def test_link_in_error(self): + # Raise an error by trying to link two modules with the same global + # definition "sum". + dest = self.module() + src = self.module(asm_sum2) + with self.assertRaises(RuntimeError) as cm: + dest.link_in(src) + self.assertIn("symbol multiply defined", str(cm.exception)) + + def test_as_bitcode(self): + mod = self.module() + bc = mod.as_bitcode() + # Refer to http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00064 # noqa E501 + # and http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00092 # noqa E501 + bitcode_wrapper_magic = b'\xde\xc0\x17\x0b' + bitcode_magic = b'BC' + self.assertTrue(bc.startswith(bitcode_magic) or + bc.startswith(bitcode_wrapper_magic)) + + def test_parse_bitcode_error(self): + with self.assertRaises(RuntimeError) as cm: + llvm.parse_bitcode(b"") + self.assertIn("LLVM bitcode parsing error", str(cm.exception)) + self.assertIn( + "file too small to contain bitcode header", str(cm.exception), + ) + + def test_bitcode_roundtrip(self): + # create a new context to avoid struct renaming + context1 = llvm.create_context() + bc = self.module(context=context1).as_bitcode() + context2 = llvm.create_context() + mod = llvm.parse_bitcode(bc, context2) + self.assertEqual(mod.as_bitcode(), bc) + + mod.get_function("sum") + mod.get_global_variable("glob") + + def test_cloning(self): + m = self.module() + cloned = m.clone() + self.assertIsNot(cloned, m) + self.assertEqual(cloned.as_bitcode(), m.as_bitcode()) + + +class JITTestMixin(object): + """ + Mixin for ExecutionEngine tests. + """ + + def get_sum(self, ee, func_name="sum"): + ee.finalize_object() + cfptr = ee.get_function_address(func_name) + self.assertTrue(cfptr) + return CFUNCTYPE(c_int, c_int, c_int)(cfptr) + + def test_run_code(self): + mod = self.module() + with self.jit(mod) as ee: + cfunc = self.get_sum(ee) + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + ee = self.jit(self.module()) + ee.close() + ee.close() + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_with(self): + ee = self.jit(self.module()) + with ee: + pass + with self.assertRaises(RuntimeError): + with ee: + pass + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_module_lifetime(self): + mod = self.module() + ee = self.jit(mod) + ee.close() + mod.close() + + def test_module_lifetime2(self): + mod = self.module() + ee = self.jit(mod) + mod.close() + ee.close() + + def test_add_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + with self.assertRaises(KeyError): + ee.add_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertTrue(mod.closed) + + def test_add_module_lifetime(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + mod.close() + ee.close() + + def test_add_module_lifetime2(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.close() + mod.close() + + def test_remove_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.remove_module(mod) + with self.assertRaises(KeyError): + ee.remove_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertFalse(mod.closed) + + def test_target_data(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + # A singleton is returned + self.assertIs(ee.target_data, td) + str(td) + del mod, ee + str(td) + + def test_target_data_abi_enquiries(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + gv_i32 = mod.get_global_variable("glob") + gv_i8 = mod.get_global_variable("glob_b") + gv_struct = mod.get_global_variable("glob_struct") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + for g in (gv_i32, gv_i8, gv_struct): + self.assertEqual(td.get_abi_size(g.type), pointer_size) + + self.assertEqual(td.get_abi_size(gv_i32.global_value_type), 4) + self.assertEqual(td.get_abi_alignment(gv_i32.global_value_type), 4) + + self.assertEqual(td.get_abi_size(gv_i8.global_value_type), 1) + self.assertIn(td.get_abi_alignment(gv_i8.global_value_type), (1, 2, 4)) + + self.assertEqual(td.get_abi_size(gv_struct.global_value_type), 24) + self.assertIn(td.get_abi_alignment(gv_struct.global_value_type), (4, 8)) + + def test_object_cache_notify(self): + notifies = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify) + + self.assertEqual(len(notifies), 0) + cfunc = self.get_sum(ee) + cfunc(2, -5) + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod) + self.assertIsInstance(notifies[0][1], bytes) + + notifies[:] = [] + mod2 = self.module(asm_mul) + ee.add_module(mod2) + cfunc = self.get_sum(ee, "mul") + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod2) + self.assertIsInstance(notifies[0][1], bytes) + + def test_object_cache_getbuffer(self): + notifies = [] + getbuffers = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + def getbuffer(mod): + getbuffers.append(mod) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer) + + # First return None from getbuffer(): the object is compiled normally + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(len(notifies), 1) + self.assertEqual(len(getbuffers), 1) + self.assertIs(getbuffers[0], mod) + sum_buffer = notifies[0][1] + + # Recreate a new EE, and use getbuffer() to return the previously + # compiled object. + + def getbuffer_successful(mod): + getbuffers.append(mod) + return sum_buffer + + notifies[:] = [] + getbuffers[:] = [] + # Use another source module to make sure it is ignored + mod = self.module(asm_mul) + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer_successful) + + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(cfunc(2, -5), -3) + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 1) + + +class JITWithTMTestMixin(JITTestMixin): + + def test_emit_assembly(self): + """Test TargetMachineRef.emit_assembly()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + raw_asm = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + target_machine.set_asm_verbosity(True) + raw_asm_verbose = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + self.assertNotEqual(raw_asm, raw_asm_verbose) + + def test_emit_object(self): + """Test TargetMachineRef.emit_object()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + code_object = target_machine.emit_object(mod) + self.assertIsInstance(code_object, bytes) + if sys.platform.startswith('linux'): + # Sanity check + self.assertIn(b"ELF", code_object[:10]) + + +class TestMCJit(BaseTest, JITWithTMTestMixin): + """ + Test JIT engines created with create_mcjit_compiler(). + """ + + def jit(self, mod, target_machine=None): + if target_machine is None: + target_machine = self.target_machine(jit=True) + return llvm.create_mcjit_compiler(mod, target_machine) + + +# There are some memory corruption issues with OrcJIT on AArch64 - see Issue +# #1000. Since OrcJIT is experimental, and we don't test regularly during +# llvmlite development on non-x86 platforms, it seems safest to skip these +# tests on non-x86 platforms. +@unittest.skipUnless(platform.machine().startswith("x86"), "x86 only") +class TestOrcLLJIT(BaseTest): + + def jit(self, asm=asm_sum, func_name="sum", target_machine=None, + add_process=False, func_type=CFUNCTYPE(c_int, c_int, c_int), + suppress_errors=False): + lljit = llvm.create_lljit_compiler(target_machine, + use_jit_link=False, + suppress_errors=suppress_errors) + builder = llvm.JITLibraryBuilder() + if add_process: + builder.add_current_process() + rt = builder\ + .add_ir(asm.format(triple=llvm.get_default_triple()))\ + .export_symbol(func_name)\ + .link(lljit, func_name) + cfptr = rt[func_name] + self.assertTrue(cfptr) + self.assertEqual(func_name, rt.name) + return lljit, rt, func_type(cfptr) + + # From test_dylib_symbols + def test_define_symbol(self): + lljit = llvm.create_lljit_compiler() + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertEqual(rt["__xyzzy"], 1234) + + def test_lookup_undefined_symbol_fails(self): + lljit = llvm.create_lljit_compiler() + with self.assertRaisesRegex(RuntimeError, 'No such library'): + lljit.lookup("foo", "__foobar") + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertNotEqual(rt["__xyzzy"], 0) + with self.assertRaisesRegex(RuntimeError, + 'Symbols not found.*__foobar'): + lljit.lookup("foo", "__foobar") + + def test_jit_link(self): + if sys.platform == "win32": + with self.assertRaisesRegex(RuntimeError, + 'JITLink .* Windows'): + llvm.create_lljit_compiler(use_jit_link=True) + else: + self.assertIsNotNone(llvm.create_lljit_compiler(use_jit_link=True)) + + def test_run_code(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + (lljit, rt, cfunc) = self.jit() + lljit.close() + lljit.close() + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_with(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + pass + with self.assertRaises(RuntimeError): + with lljit: + pass + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_add_ir_module(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_mul.format(triple=llvm.get_default_triple())) \ + .export_symbol("mul") \ + .link(lljit, "mul") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["mul"])(2, -5) + self.assertEqual(-10, res) + self.assertNotEqual(lljit.lookup("sum", "sum")["sum"], 0) + self.assertNotEqual(lljit.lookup("mul", "mul")["mul"], 0) + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "mul") + with self.assertRaises(RuntimeError): + lljit.lookup("mul", "sum") + + def test_remove_module(self): + (lljit, rt_sum, _) = self.jit() + del rt_sum + gc.collect() + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "sum") + lljit.close() + + def test_lib_depends(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_square_sum.format(triple=llvm.get_default_triple())) \ + .export_symbol("square_sum") \ + .add_jit_library("sum") \ + .link(lljit, "square_sum") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["square_sum"])(2, -5) + self.assertEqual(9, res) + + def test_target_data(self): + (lljit, rt, _) = self.jit() + td = lljit.target_data + # A singleton is returned + self.assertIs(lljit.target_data, td) + str(td) + del lljit + str(td) + + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + shared_value = c_int32(0) + lljit = llvm.create_lljit_compiler() + builder = llvm.JITLibraryBuilder() + rt = builder \ + .add_ir(asm_ext_ctors.format(triple=llvm.get_default_triple())) \ + .import_symbol("A", ctypes.addressof(shared_value)) \ + .export_symbol("foo") \ + .link(lljit, "foo") + foo = rt["foo"] + self.assertTrue(foo) + self.assertEqual(CFUNCTYPE(c_int)(foo)(), 12) + del rt + self.assertNotEqual(shared_value.value, 20) + + def test_lookup_current_process_symbol_fails(self): + # An attempt to lookup a symbol in the current process (Py_GetVersion, + # in this case) should fail with an appropriate error if we have not + # enabled searching the current process for symbols. + msg = 'Failed to materialize symbols:.*getversion' + with self.assertRaisesRegex(RuntimeError, msg): + self.jit(asm_getversion, "getversion", suppress_errors=True) + + def test_lookup_current_process_symbol(self): + self.jit(asm_getversion, "getversion", None, True) + + def test_thread_safe(self): + lljit = llvm.create_lljit_compiler() + llvm_ir = asm_sum.format(triple=llvm.get_default_triple()) + + def compile_many(i): + def do_work(): + tracking = [] + for c in range(50): + tracking.append(llvm.JITLibraryBuilder() + .add_ir(llvm_ir) + .export_symbol("sum") + .link(lljit, f"sum_{i}_{c}")) + + return do_work + + ths = [threading.Thread(target=compile_many(i)) + for i in range(os.cpu_count())] + for th in ths: + th.start() + for th in ths: + th.join() + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder()\ + .add_object_img(target_machine.emit_object(mod))\ + .export_symbol("sum")\ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + with os.fdopen(temp_desc, "wb") as f: + f.write(obj_bin) + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder() \ + .add_object_file(temp_path) \ + .export_symbol("sum") \ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + finally: + os.unlink(temp_path) + + +class TestValueRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob), "@glob = global i32 0") + + def test_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.name, "glob") + glob.name = "foobar" + self.assertEqual(glob.name, "foobar") + + def test_linkage(self): + mod = self.module() + glob = mod.get_global_variable("glob") + linkage = glob.linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + glob.linkage = linkage + self.assertEqual(glob.linkage, linkage) + for linkage in ("internal", "external"): + glob.linkage = linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + self.assertEqual(glob.linkage.name, linkage) + + def test_visibility(self): + mod = self.module() + glob = mod.get_global_variable("glob") + visibility = glob.visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + glob.visibility = visibility + self.assertEqual(glob.visibility, visibility) + for visibility in ("hidden", "protected", "default"): + glob.visibility = visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + self.assertEqual(glob.visibility.name, visibility) + + def test_storage_class(self): + mod = self.module() + glob = mod.get_global_variable("glob") + storage_class = glob.storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + glob.storage_class = storage_class + self.assertEqual(glob.storage_class, storage_class) + for storage_class in ("dllimport", "dllexport", "default"): + glob.storage_class = storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + self.assertEqual(glob.storage_class.name, storage_class) + + def test_add_function_attribute(self): + mod = self.module() + fn = mod.get_function("sum") + fn.add_function_attribute("nocapture") + with self.assertRaises(ValueError) as raises: + fn.add_function_attribute("zext") + self.assertEqual(str(raises.exception), "no such attribute 'zext'") + + def test_module(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertIs(glob.module, mod) + + def test_type(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertIsInstance(tp, llvm.TypeRef) + + def test_type_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertEqual(tp.name, "") + st = mod.get_global_variable("glob_struct") + self.assertIsNotNone(re.match(r"struct\.glob_type(\.[\d]+)?", + st.global_value_type.name)) + + def test_type_printing_variable(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.global_value_type + self.assertEqual(str(tp), 'i32') + + def test_type_printing_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertEqual(str(fn.global_value_type), "i32 (i32, i32)") + + def test_type_printing_struct(self): + mod = self.module() + st = mod.get_global_variable("glob_struct") + self.assertTrue(st.type.is_pointer) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIsNotNone(re.match(r'ptr', str(st.type))) + else: + self.assertIsNotNone(re.match(r'%struct\.glob_type(\.[\d]+)?\*', + str(st.type))) + self.assertIsNotNone(re.match( + r"%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }", + str(st.global_value_type))) + + def test_close(self): + glob = self.glob() + glob.close() + glob.close() + + def test_is_declaration(self): + defined = self.module().get_function('sum') + declared = self.module(asm_sum_declare).get_function('sum') + self.assertFalse(defined.is_declaration) + self.assertTrue(declared.is_declaration) + + def test_module_global_variables(self): + mod = self.module(asm_sum) + gvars = list(mod.global_variables) + self.assertEqual(len(gvars), 4) + for v in gvars: + self.assertTrue(v.is_global) + + def test_module_functions(self): + mod = self.module() + funcs = list(mod.functions) + self.assertEqual(len(funcs), 1) + func = funcs[0] + self.assertTrue(func.is_function) + self.assertEqual(func.name, 'sum') + + with self.assertRaises(ValueError): + func.instructions + with self.assertRaises(ValueError): + func.operands + with self.assertRaises(ValueError): + func.opcode + + def test_function_arguments(self): + mod = self.module() + func = mod.get_function('sum') + self.assertTrue(func.is_function) + args = list(func.arguments) + self.assertEqual(len(args), 2) + self.assertTrue(args[0].is_argument) + self.assertTrue(args[1].is_argument) + self.assertEqual(args[0].name, '.1') + self.assertEqual(str(args[0].type), 'i32') + self.assertEqual(args[1].name, '.2') + self.assertEqual(str(args[1].type), 'i32') + + with self.assertRaises(ValueError): + args[0].blocks + with self.assertRaises(ValueError): + args[0].arguments + + def test_function_blocks(self): + func = self.module().get_function('sum') + blocks = list(func.blocks) + self.assertEqual(len(blocks), 1) + block = blocks[0] + self.assertTrue(block.is_block) + + def test_block_instructions(self): + func = self.module().get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 3) + self.assertTrue(insts[0].is_instruction) + self.assertTrue(insts[1].is_instruction) + self.assertTrue(insts[2].is_instruction) + self.assertEqual(insts[0].opcode, 'add') + self.assertEqual(insts[1].opcode, 'add') + self.assertEqual(insts[2].opcode, 'ret') + + def test_instruction_operands(self): + func = self.module().get_function('sum') + add = list(list(func.blocks)[0].instructions)[0] + self.assertEqual(add.opcode, 'add') + operands = list(add.operands) + self.assertEqual(len(operands), 2) + self.assertTrue(operands[0].is_operand) + self.assertTrue(operands[1].is_operand) + self.assertEqual(operands[0].name, '.1') + self.assertEqual(str(operands[0].type), 'i32') + self.assertEqual(operands[1].name, '.2') + self.assertEqual(str(operands[1].type), 'i32') + + def test_function_attributes(self): + ver = llvm.llvm_version_info[0] + readonly_attrs = [b'memory(read)' if ver == 16 else b'readonly'] + mod = self.module(asm_attributes) + for func in mod.functions: + attrs = list(func.attributes) + if func.name == 'a_readonly_func': + self.assertEqual(attrs, readonly_attrs) + elif func.name == 'a_arg0_return_func': + self.assertEqual(attrs, []) + args = list(func.arguments) + self.assertEqual(list(args[0].attributes), [b'returned']) + self.assertEqual(list(args[1].attributes), []) + + def test_value_kind(self): + mod = self.module() + self.assertEqual(mod.get_global_variable('glob').value_kind, + llvm.ValueKind.global_variable) + func = mod.get_function('sum') + self.assertEqual(func.value_kind, llvm.ValueKind.function) + block = list(func.blocks)[0] + self.assertEqual(block.value_kind, llvm.ValueKind.basic_block) + inst = list(block.instructions)[1] + self.assertEqual(inst.value_kind, llvm.ValueKind.instruction) + self.assertEqual(list(inst.operands)[0].value_kind, + llvm.ValueKind.constant_int) + self.assertEqual(list(inst.operands)[1].value_kind, + llvm.ValueKind.instruction) + + iasm_func = self.module(asm_inlineasm).get_function('foo') + iasm_inst = list(list(iasm_func.blocks)[0].instructions)[0] + self.assertEqual(list(iasm_inst.operands)[0].value_kind, + llvm.ValueKind.inline_asm) + + def test_is_constant(self): + mod = self.module() + self.assertTrue(mod.get_global_variable('glob').is_constant) + constant_operands = 0 + for func in mod.functions: + self.assertTrue(func.is_constant) + for block in func.blocks: + self.assertFalse(block.is_constant) + for inst in block.instructions: + self.assertFalse(inst.is_constant) + for op in inst.operands: + if op.is_constant: + constant_operands += 1 + + self.assertEqual(constant_operands, 1) + + def test_constant_int(self): + mod = self.module() + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(insts[1].opcode, 'add') + operands = list(insts[1].operands) + self.assertTrue(operands[0].is_constant) + self.assertFalse(operands[1].is_constant) + self.assertEqual(operands[0].get_constant_value(), 0) + with self.assertRaises(ValueError): + operands[1].get_constant_value() + + mod = self.module(asm_sum3) + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + posint64 = list(insts[1].operands)[0] + negint64 = list(insts[2].operands)[0] + self.assertEqual(posint64.get_constant_value(), 5) + self.assertEqual(negint64.get_constant_value(signed_int=True), -5) + + # Convert from unsigned arbitrary-precision integer to signed i64 + as_u64 = negint64.get_constant_value(signed_int=False) + as_i64 = int.from_bytes(as_u64.to_bytes(8, 'little'), 'little', + signed=True) + self.assertEqual(as_i64, -5) + + def test_constant_fp(self): + mod = self.module(asm_double_locale) + func = mod.get_function('foo') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 2) + self.assertEqual(insts[0].opcode, 'fadd') + operands = list(insts[0].operands) + self.assertTrue(operands[0].is_constant) + self.assertAlmostEqual(operands[0].get_constant_value(), 0.0) + self.assertTrue(operands[1].is_constant) + self.assertAlmostEqual(operands[1].get_constant_value(), 3.14) + + mod = self.module(asm_double_inaccurate) + func = mod.get_function('foo') + inst = list(list(func.blocks)[0].instructions)[0] + operands = list(inst.operands) + with self.assertRaises(ValueError): + operands[0].get_constant_value() + self.assertAlmostEqual(operands[1].get_constant_value(round_fp=True), 0) + + def test_constant_as_string(self): + mod = self.module(asm_null_constant) + func = mod.get_function('bar') + inst = list(list(func.blocks)[0].instructions)[0] + arg = list(inst.operands)[0] + self.assertTrue(arg.is_constant) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(arg.get_constant_value(), 'ptr null') + else: + self.assertEqual(arg.get_constant_value(), 'i64* null') + + def test_incoming_phi_blocks(self): + mod = self.module(asm_phi_blocks) + func = mod.get_function('foo') + blocks = list(func.blocks) + instructions = list(blocks[-1].instructions) + self.assertTrue(instructions[0].is_instruction) + self.assertEqual(instructions[0].opcode, 'phi') + + incoming_blocks = list(instructions[0].incoming_blocks) + self.assertEqual(len(incoming_blocks), 2) + self.assertTrue(incoming_blocks[0].is_block) + self.assertTrue(incoming_blocks[1].is_block) + # Test reference to blocks (named or unnamed) + self.assertEqual(incoming_blocks[0], blocks[-1]) + self.assertEqual(incoming_blocks[1], blocks[0]) + + # Test case that should fail + self.assertNotEqual(instructions[1].opcode, 'phi') + with self.assertRaises(ValueError): + instructions[1].incoming_blocks + + +class TestTypeRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob.global_value_type), "i32") + glob_struct_type = mod.get_struct_type("struct.glob_type") + self.assertEqual(str(glob_struct_type), + "%struct.glob_type = type { i64, [2 x i64] }") + + elements = list(glob_struct_type.elements) + self.assertEqual(len(elements), 2) + self.assertEqual(str(elements[0]), "i64") + self.assertEqual(str(elements[1]), "[2 x i64]") + + def test_type_kind(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob.type.is_pointer) + + glob_struct = mod.get_global_variable("glob_struct") + self.assertEqual(glob_struct.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob_struct.type.is_pointer) + + stype = glob_struct.global_value_type + self.assertEqual(stype.type_kind, llvm.TypeKind.struct) + self.assertTrue(stype.is_struct) + + stype_a, stype_b = stype.elements + self.assertEqual(stype_a.type_kind, llvm.TypeKind.integer) + self.assertEqual(stype_b.type_kind, llvm.TypeKind.array) + self.assertTrue(stype_b.is_array) + + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(vector_type.type_kind, llvm.TypeKind.vector) + self.assertTrue(vector_type.is_vector) + + funcptr = mod.get_function("sum").type + self.assertEqual(funcptr.type_kind, llvm.TypeKind.pointer) + functype = mod.get_function("sum").global_value_type + self.assertEqual(functype.type_kind, llvm.TypeKind.function) + + def test_element_count(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + _, array_type = glob_struct_type.elements + self.assertEqual(array_type.element_count, 2) + with self.assertRaises(ValueError): + glob_struct_type.element_count + + def test_type_width(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + integer_type, array_type = glob_struct_type.elements + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(integer_type.type_width, 64) + self.assertEqual(vector_type.type_width, 64 * 2) + + # Structs and arrays are not primitive types + self.assertEqual(glob_struct_type.type_width, 0) + self.assertEqual(array_type.type_width, 0) + + def test_vararg_function(self): + # Variadic function + mod = self.module(asm_vararg_declare) + func = mod.get_function('vararg') + decltype = func.global_value_type + self.assertTrue(decltype.is_function_vararg) + + mod = self.module(asm_sum_declare) + func = mod.get_function('sum') + decltype = func.global_value_type + self.assertFalse(decltype.is_function_vararg) + + # test that the function pointer type cannot use is_function_vararg + self.assertTrue(func.type.is_pointer) + with self.assertRaises(ValueError) as raises: + func.type.is_function_vararg + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("Type ptr is not a function", str(raises.exception)) + else: + self.assertIn("Type i32 (i32, i32)* is not a function", + str(raises.exception)) + + def test_function_typeref_as_ir(self): + mod = self.module() + + [fn] = list(mod.functions) + # .type gives a pointer type, a problem if it's opaque (llvm15+) + self.assertEqual(fn.type.type_kind, llvm.TypeKind.pointer) + self.assertFalse(fn.type.is_function) + # Use .global_value_type instead + fnty = fn.global_value_type + self.assertEqual(fnty.type_kind, llvm.TypeKind.function) + self.assertTrue(fnty.is_function) + # Run .as_ir() to get llvmlite.ir.FunctionType + tyir = fnty.as_ir(ir.global_context) + self.assertIsInstance(tyir, ir.FunctionType) + self.assertEqual(tyir.args, (ir.IntType(32), ir.IntType(32))) + self.assertEqual(tyir.return_type ,ir.IntType(32)) + + def test_void_typeref_as_ir(self): + # Void type can only be used as return-type of llvmlite.ir.FunctionType. + fnty = ir.FunctionType(ir.VoidType(), ()) + irmod = ir.Module() + fn = ir.Function(irmod, fnty, "foo") + mod = self.module(str(irmod)) + fn = mod.get_function("foo") + gvty = fn.global_value_type + self.assertEqual(fnty.return_type, + gvty.as_ir(ir.global_context).return_type) + + def test_global_typeref_as_ir(self): + from llvmlite.binding.typeref import _TypeKindToIRType + ctx = ir.Context() + + skipped = { + "function", # tested in test_function_typeref_as_ir + "void", # tested in test_void_typeref_as_ir + } + + makers = {} + + def maker_half(): + yield ir.HalfType() + + makers['half'] = maker_half + + def maker_float(): + yield ir.FloatType() + + makers['float'] = maker_float + + def maker_double(): + yield ir.DoubleType() + + makers['double'] = maker_double + + def maker_integer(): + yield ir.IntType(32) + + makers['integer'] = maker_integer + + def maker_pointer(): + yield ir.PointerType(ir.IntType(8)) + # opaque struct ptr + yield ctx.get_identified_type("myclass").as_pointer() + # named struct with defined body + myclass2 = ctx.get_identified_type("myclass2") + myclass2.set_body(ir.IntType(8)) + yield myclass2.as_pointer() + + makers['pointer'] = maker_pointer + + def maker_array(): + yield ir.ArrayType(ir.IntType(8), 123) + + makers['array'] = maker_array + + def maker_vector(): + yield ir.VectorType(ir.FloatType(), 2) + + makers['vector'] = maker_vector + + def maker_struct(): + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)]) + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)], + packed=True) + + makers['struct'] = maker_struct + + # Ensure that number of supported TypeKind matches number of makers + self.assertEqual({x.name for x in _TypeKindToIRType.keys()}, + set(makers.keys()) | set(skipped)) + + # Test each type-kind + for type_kind, irtype in _TypeKindToIRType.items(): + if type_kind.name in skipped: + continue + for ty in makers[type_kind.name](): + with self.subTest(f"{type_kind!s} -> {ty}"): + irmod = ir.Module(context=ctx) + ir.GlobalVariable(irmod, ty, name='gv') + asm = str(irmod) + mod = llvm.parse_assembly(asm) + gv = mod.get_global_variable("gv") + gvty = gv.global_value_type + got = gvty.as_ir(ir.Context()) # fresh context + self.assertEqual(got, ty) + self.assertIsInstance(got, irtype) + + def _check_typeref_as_ir_for_wrappers(self, asm, target_symbol): + # Get a clang++ defined function from a llvm ir + mod = llvm.parse_assembly(asm) + cppfn = mod.get_function(target_symbol) + cppfntype = cppfn.global_value_type + + # Get the function type into a new context + my_context = ir.Context() # don't populate global context + ty = cppfntype.as_ir(ir_ctx=my_context) + + # Build a wrapper module for the cpp function + wrapper_mod = ir.Module(context=my_context) + # declare the original function + declfn = ir.Function(wrapper_mod, ty, name=cppfn.name) + # populate the wrapper function + wrapfn = ir.Function(wrapper_mod, ty, name="wrapper") + builder = ir.IRBuilder(wrapfn.append_basic_block()) + # just call the original function + builder.call(declfn, wrapfn.args) + builder.ret_void() + # Create a new LLVM module with the wrapper + new_mod = llvm.parse_assembly(str(wrapper_mod)) + self.assertTrue(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must not have a body") + # Merge/link the original module into the new module + new_mod.link_in(mod, preserve=True) + self.assertEqual(len(list(new_mod.functions)), + len(list(mod.functions)) + 1, + msg="the only new function is the wrapper") + self.assertFalse(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must have a body now") + self.assertEqual(new_mod.get_function(declfn.name).global_value_type, + new_mod.get_function(wrapfn.name).global_value_type, + msg="declfn and wrapfn must have the same llvm Type") + + def test_typeref_as_ir_for_wrappers_of_cpp_class(self): + """Exercise extracting C++ defined class types. + Contains both opaque and non-opaque class definitions. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_class, + "_Z3fooP7MyClass14MyClassDefined", + ) + + def test_typeref_as_ir_for_wrappers_of_cpp_vector_struct(self): + """Exercise extracting C++ struct types that are passed as vectors. + + IA64 ABI on x86_64 will put struct with two floats as + a vector of two floats. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_vector, + "_Z3foo8Vector2DPS_", + ) + + +class TestTarget(BaseTest): + + def test_from_triple(self): + f = llvm.Target.from_triple + with self.assertRaises(RuntimeError) as cm: + f("foobar") + self.assertIn("No available targets are compatible with", + str(cm.exception)) + triple = llvm.get_default_triple() + target = f(triple) + self.assertEqual(target.triple, triple) + target.close() + + def test_create_target_machine(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + # With the default settings + target.create_target_machine('', '', 1, 'default', 'default') + # With the host's CPU + cpu = llvm.get_host_cpu_name() + target.create_target_machine(cpu, '', 1, 'default', 'default') + + def test_name(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.name, str) + self.assertEqual(t.name, u.name) + + def test_description(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.description, str) + self.assertEqual(t.description, u.description) + + def test_str(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + s = str(target) + self.assertIn(target.name, s) + self.assertIn(target.description, s) + + def test_get_parts_from_triple(self): + # Tests adapted from llvm-14::llvm/unittests/ADT/TripleTest.cpp + cases = [ + ("x86_64-scei-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("x86_64-sie-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("powerpc-dunno-notsure", + llvm.targets.Triple(Arch="powerpc", SubArch='', + Vendor="unknown", OS="unknown", + Env="unknown", ObjectFormat="ELF")), + ("powerpcspe-unknown-freebsd", + llvm.targets.Triple(Arch="powerpc", SubArch='spe', + Vendor="unknown", OS="freebsd", + Env="unknown", ObjectFormat="ELF")), + ("armv6hl-none-linux-gnueabi", + llvm.targets.Triple(Arch="arm", SubArch='v6hl', + Vendor="unknown", OS="linux", + Env="gnueabi", ObjectFormat="ELF")), + ("i686-unknown-linux-gnu", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="linux", + Env="gnu", ObjectFormat="ELF")), + ("i686-apple-macosx", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="apple", OS="macosx", + Env="unknown", ObjectFormat="MachO")), + ("i686-dunno-win32", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="windows", + Env="msvc", ObjectFormat="COFF")), + ("s390x-ibm-zos", + llvm.targets.Triple(Arch="s390x", SubArch='', + Vendor="ibm", OS="zos", + Env="unknown", ObjectFormat="GOFF")), + ("wasm64-wasi", + llvm.targets.Triple(Arch="wasm64", SubArch='', + Vendor="unknown", OS="wasi", + Env="unknown", ObjectFormat="Wasm")), + ] + + for case in cases: + triple_str, triple_obj = case + res = llvm.get_triple_parts(triple_str) + + self.assertEqual(res, triple_obj) + + +class TestTargetData(BaseTest): + + def target_data(self): + return llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def test_get_abi_size(self): + td = self.target_data() + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.type), 8) + + def test_get_pointee_abi_size(self): + td = self.target_data() + + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.global_value_type), 4) + + glob = self.glob("glob_struct") + self.assertEqual(td.get_abi_size(glob.global_value_type), 24) + + def test_get_struct_element_offset(self): + td = self.target_data() + glob = self.glob("glob_struct") + + with self.assertRaises(ValueError): + td.get_element_offset(glob.type, 0) + + struct_type = glob.global_value_type + self.assertEqual(td.get_element_offset(struct_type, 0), 0) + self.assertEqual(td.get_element_offset(struct_type, 1), 8) + + +class TestTargetMachine(BaseTest): + + def test_add_analysis_passes(self): + tm = self.target_machine(jit=False) + pm = llvm.create_module_pass_manager() + tm.add_analysis_passes(pm) + + def test_target_data_from_tm(self): + tm = self.target_machine(jit=False) + td = tm.target_data + mod = self.module() + gv_i32 = mod.get_global_variable("glob") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + self.assertEqual(td.get_abi_size(gv_i32.type), pointer_size) + + +class TestPassManagerBuilder(BaseTest): + + def pmb(self): + return llvm.PassManagerBuilder() + + def test_old_api(self): + # Test the create_pass_manager_builder() factory function + pmb = llvm.create_pass_manager_builder() + pmb.inlining_threshold = 2 + pmb.opt_level = 3 + + def test_close(self): + pmb = self.pmb() + pmb.close() + pmb.close() + + def test_opt_level(self): + pmb = self.pmb() + self.assertIsInstance(pmb.opt_level, int) + for i in range(4): + pmb.opt_level = i + self.assertEqual(pmb.opt_level, i) + + def test_size_level(self): + pmb = self.pmb() + self.assertIsInstance(pmb.size_level, int) + for i in range(4): + pmb.size_level = i + self.assertEqual(pmb.size_level, i) + + def test_inlining_threshold(self): + pmb = self.pmb() + with self.assertRaises(NotImplementedError): + pmb.inlining_threshold + for i in (25, 80, 350): + pmb.inlining_threshold = i + + def test_disable_unroll_loops(self): + pmb = self.pmb() + self.assertIsInstance(pmb.disable_unroll_loops, bool) + for b in (True, False): + pmb.disable_unroll_loops = b + self.assertEqual(pmb.disable_unroll_loops, b) + + def test_loop_vectorize(self): + pmb = self.pmb() + self.assertIsInstance(pmb.loop_vectorize, bool) + for b in (True, False): + pmb.loop_vectorize = b + self.assertEqual(pmb.loop_vectorize, b) + + def test_slp_vectorize(self): + pmb = self.pmb() + self.assertIsInstance(pmb.slp_vectorize, bool) + for b in (True, False): + pmb.slp_vectorize = b + self.assertEqual(pmb.slp_vectorize, b) + + def test_populate_module_pass_manager(self): + pmb = self.pmb() + pm = llvm.create_module_pass_manager() + pmb.populate(pm) + pmb.close() + pm.close() + + def test_populate_function_pass_manager(self): + mod = self.module() + pmb = self.pmb() + pm = llvm.create_function_pass_manager(mod) + pmb.populate(pm) + pmb.close() + pm.close() + + +class PassManagerTestMixin(object): + + def pmb(self): + pmb = llvm.create_pass_manager_builder() + pmb.opt_level = 2 + pmb.inlining_threshold = 300 + return pmb + + def test_close(self): + pm = self.pm() + pm.close() + pm.close() + + +class TestModulePassManager(BaseTest, PassManagerTestMixin): + + def pm(self): + return llvm.create_module_pass_manager() + + def test_run(self): + pm = self.pm() + self.pmb().populate(pm) + mod = self.module() + orig_asm = str(mod) + pm.run(mod) + opt_asm = str(mod) + # Quick check that optimizations were run, should get: + # define i32 @sum(i32 %.1, i32 %.2) local_unnamed_addr #0 { + # %.X = add i32 %.2, %.1 + # ret i32 %.X + # } + # where X in %.X is 3 or 4 + opt_asm_split = opt_asm.splitlines() + for idx, l in enumerate(opt_asm_split): + if l.strip().startswith('ret i32'): + toks = {'%.3', '%.4'} + for t in toks: + if t in l: + break + else: + raise RuntimeError("expected tokens not found") + othertoken = (toks ^ {t}).pop() + + self.assertIn("%.3", orig_asm) + self.assertNotIn(othertoken, opt_asm) + break + else: + raise RuntimeError("expected IR not found") + + def test_run_with_remarks_successful_inline(self): + pm = self.pm() + pm.add_function_inlining_pass(70) + self.pmb().populate(pm) + mod = self.module(asm_inlineasm2) + (status, remarks) = pm.run_with_remarks(mod) + self.assertTrue(status) + # Inlining has happened? The remark will tell us. + self.assertIn("Passed", remarks) + self.assertIn("inlineme", remarks) + + def test_run_with_remarks_failed_inline(self): + pm = self.pm() + pm.add_function_inlining_pass(0) + self.pmb().populate(pm) + mod = self.module(asm_inlineasm3) + (status, remarks) = pm.run_with_remarks(mod) + self.assertTrue(status) + + # Inlining has not happened? The remark will tell us. + self.assertIn("Missed", remarks) + self.assertIn("inlineme", remarks) + self.assertIn("noinline function attribute", remarks) + + def test_run_with_remarks_inline_filter_out(self): + pm = self.pm() + pm.add_function_inlining_pass(70) + self.pmb().populate(pm) + mod = self.module(asm_inlineasm2) + (status, remarks) = pm.run_with_remarks(mod, remarks_filter="nothing") + self.assertTrue(status) + self.assertEqual("", remarks) + + def test_run_with_remarks_inline_filter_in(self): + pm = self.pm() + pm.add_function_inlining_pass(70) + self.pmb().populate(pm) + mod = self.module(asm_inlineasm2) + (status, remarks) = pm.run_with_remarks(mod, remarks_filter="inlin.*") + self.assertTrue(status) + self.assertIn("Passed", remarks) + self.assertIn("inlineme", remarks) + + +class TestFunctionPassManager(BaseTest, PassManagerTestMixin): + + def pm(self, mod=None): + mod = mod or self.module() + return llvm.create_function_pass_manager(mod) + + def test_initfini(self): + pm = self.pm() + pm.initialize() + pm.finalize() + + def test_run(self): + mod = self.module() + fn = mod.get_function("sum") + pm = self.pm(mod) + self.pmb().populate(pm) + mod.close() + orig_asm = str(fn) + pm.initialize() + pm.run(fn) + pm.finalize() + opt_asm = str(fn) + # Quick check that optimizations were run + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", opt_asm) + + def test_run_with_remarks(self): + mod = self.module(licm_asm) + fn = mod.get_function("licm") + pm = self.pm(mod) + pm.add_licm_pass() + self.pmb().populate(pm) + mod.close() + + pm.initialize() + (ok, remarks) = pm.run_with_remarks(fn) + pm.finalize() + self.assertTrue(ok) + self.assertIn("Passed", remarks) + self.assertIn("licm", remarks) + + def test_run_with_remarks_filter_out(self): + mod = self.module(licm_asm) + fn = mod.get_function("licm") + pm = self.pm(mod) + pm.add_licm_pass() + self.pmb().populate(pm) + mod.close() + + pm.initialize() + (ok, remarks) = pm.run_with_remarks(fn, remarks_filter="nothing") + pm.finalize() + self.assertTrue(ok) + self.assertEqual("", remarks) + + def test_run_with_remarks_filter_in(self): + mod = self.module(licm_asm) + fn = mod.get_function("licm") + pm = self.pm(mod) + pm.add_licm_pass() + self.pmb().populate(pm) + mod.close() + + pm.initialize() + (ok, remarks) = pm.run_with_remarks(fn, remarks_filter="licm") + pm.finalize() + self.assertTrue(ok) + self.assertIn("Passed", remarks) + self.assertIn("licm", remarks) + + +class TestPasses(BaseTest, PassManagerTestMixin): + + def pm(self): + return llvm.create_module_pass_manager() + + def test_populate(self): + llvm_ver = llvm.llvm_version_info[0] + + pm = self.pm() + pm.add_target_library_info("") # unspecified target triple + pm.add_constant_merge_pass() + pm.add_dead_arg_elimination_pass() + pm.add_function_attrs_pass() + pm.add_function_inlining_pass(225) + pm.add_global_dce_pass() + pm.add_global_optimizer_pass() + pm.add_ipsccp_pass() + pm.add_dead_code_elimination_pass() + pm.add_cfg_simplification_pass() + pm.add_gvn_pass() + pm.add_instruction_combining_pass() + pm.add_licm_pass() + pm.add_sccp_pass() + pm.add_sroa_pass() + pm.add_type_based_alias_analysis_pass() + pm.add_basic_alias_analysis_pass() + pm.add_loop_rotate_pass() + pm.add_region_info_pass() + pm.add_scalar_evolution_aa_pass() + pm.add_aggressive_dead_code_elimination_pass() + pm.add_aa_eval_pass() + pm.add_always_inliner_pass() + pm.add_break_critical_edges_pass() + pm.add_dead_store_elimination_pass() + pm.add_reverse_post_order_function_attrs_pass() + + if llvm_ver < 16: + pm.add_aggressive_instruction_combining_pass() + + pm.add_internalize_pass() + pm.add_jump_threading_pass(7) + pm.add_lcssa_pass() + pm.add_loop_deletion_pass() + pm.add_loop_extractor_pass() + pm.add_single_loop_extractor_pass() + pm.add_loop_strength_reduce_pass() + pm.add_loop_simplification_pass() + pm.add_loop_unroll_pass() + pm.add_loop_unroll_and_jam_pass() + pm.add_lower_atomic_pass() + pm.add_lower_invoke_pass() + pm.add_lower_switch_pass() + pm.add_memcpy_optimization_pass() + pm.add_merge_functions_pass() + pm.add_merge_returns_pass() + pm.add_partial_inlining_pass() + + if llvm_ver < 16: + pm.add_prune_exception_handling_pass() + + pm.add_reassociate_expressions_pass() + pm.add_demote_register_to_memory_pass() + pm.add_sink_pass() + pm.add_strip_symbols_pass() + pm.add_strip_dead_debug_info_pass() + pm.add_strip_dead_prototypes_pass() + pm.add_strip_debug_declare_pass() + pm.add_strip_nondebug_symbols_pass() + pm.add_tail_call_elimination_pass() + pm.add_basic_aa_pass() + pm.add_dependence_analysis_pass() + pm.add_dot_call_graph_pass() + pm.add_dot_cfg_printer_pass() + pm.add_dot_dom_printer_pass() + pm.add_dot_postdom_printer_pass() + pm.add_globals_mod_ref_aa_pass() + pm.add_iv_users_pass() + pm.add_lazy_value_info_pass() + pm.add_lint_pass() + pm.add_module_debug_info_pass() + pm.add_refprune_pass() + pm.add_instruction_namer_pass() + + @unittest.skipUnless(platform.machine().startswith("x86"), "x86 only") + def test_target_library_info_behavior(self): + """Test a specific situation that demonstrate TLI is affecting + optimization. See https://github.com/numba/numba/issues/8898. + """ + def run(use_tli): + mod = llvm.parse_assembly(asm_tli_exp2) + target = llvm.Target.from_triple(mod.triple) + tm = target.create_target_machine() + pm = llvm.ModulePassManager() + tm.add_analysis_passes(pm) + if use_tli: + pm.add_target_library_info(mod.triple) + pm.add_instruction_combining_pass() + pm.run(mod) + return mod + + # Run with TLI should suppress transformation of exp2 -> ldexpf + mod = run(use_tli=True) + self.assertIn("call float @llvm.exp2.f32", str(mod)) + + # Run without TLI will enable the transformation + mod = run(use_tli=False) + self.assertNotIn("call float @llvm.exp2.f32", str(mod)) + self.assertIn("call float @ldexpf", str(mod)) + + def test_instruction_namer_pass(self): + asm = asm_inlineasm3.format(triple=llvm.get_default_triple()) + mod = llvm.parse_assembly(asm) + + # Run instnamer pass + pm = llvm.ModulePassManager() + pm.add_instruction_namer_pass() + pm.run(mod) + + # Test that unnamed instructions are now named + func = mod.get_function('foo') + first_block = next(func.blocks) + instructions = list(first_block.instructions) + self.assertEqual(instructions[0].name, 'i') + self.assertEqual(instructions[1].name, 'i2') + + +class TestDylib(BaseTest): + + def test_bad_library(self): + with self.assertRaises(RuntimeError): + llvm.load_library_permanently("zzzasdkf;jasd;l") + + @unittest.skipUnless(platform.system() in ["Linux"], + "test only works on Linux") + def test_libm(self): + libm = find_library("m") + llvm.load_library_permanently(libm) + + +class TestAnalysis(BaseTest): + def build_ir_module(self): + m = ir.Module() + ft = ir.FunctionType(ir.IntType(32), [ir.IntType(32), ir.IntType(32)]) + fn = ir.Function(m, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block()) + x, y = fn.args + z = bd.add(x, y) + bd.ret(z) + return m + + def test_get_function_cfg_on_ir(self): + mod = self.build_ir_module() + foo = mod.get_global('foo') + dot_showing_inst = llvm.get_function_cfg(foo) + dot_without_inst = llvm.get_function_cfg(foo, show_inst=False) + inst = "%.5 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + def test_function_cfg_on_llvm_value(self): + defined = self.module().get_function('sum') + dot_showing_inst = llvm.get_function_cfg(defined, show_inst=True) + dot_without_inst = llvm.get_function_cfg(defined, show_inst=False) + # Check "digraph" + prefix = 'digraph' + self.assertIn(prefix, dot_showing_inst) + self.assertIn(prefix, dot_without_inst) + # Check function name + fname = "CFG for 'sum' function" + self.assertIn(fname, dot_showing_inst) + self.assertIn(fname, dot_without_inst) + # Check instruction + inst = "%.3 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + +class TestTypeParsing(BaseTest): + @contextmanager + def check_parsing(self): + mod = ir.Module() + # Yield to caller and provide the module for adding + # new GV. + yield mod + # Caller yield back and continue with testing + asm = str(mod) + llvm.parse_assembly(asm) + + def test_literal_struct(self): + # Natural layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)]) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)], + packed=True) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout created from Constant.literal_struct + with self.check_parsing() as mod: + const = ir.Constant.literal_struct([ir.IntType(32)(1), + ir.IntType(32)(2)], + packed=True) + gv = ir.GlobalVariable(mod, const.type, "foo") + gv.initializer = const + + +class TestGlobalConstructors(TestMCJit): + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + mod = self.module(asm_global_ctors) + ee = self.jit(mod) + ee.finalize_object() + + ee.run_static_constructors() + + # global variable should have been initialized + ptr_addr = ee.get_global_value_address("A") + ptr_t = ctypes.POINTER(ctypes.c_int32) + ptr = ctypes.cast(ptr_addr, ptr_t) + self.assertEqual(ptr.contents.value, 10) + + foo_addr = ee.get_function_address("foo") + foo = ctypes.CFUNCTYPE(ctypes.c_int32)(foo_addr) + self.assertEqual(foo(), 12) + + ee.run_static_destructors() + + # destructor should have run + self.assertEqual(ptr.contents.value, 20) + + +class TestGlobalVariables(BaseTest): + def check_global_variable_linkage(self, linkage, has_undef=True): + # This test default initializer on global variables with different + # linkages. Some linkages requires an initializer be present, while + # it is optional for others. This test uses ``parse_assembly()`` + # to verify that we are adding an `undef` automatically if user didn't + # specific one for certain linkages. It is a IR syntax error if the + # initializer is not present for certain linkages e.g. "external". + mod = ir.Module() + typ = ir.IntType(32) + gv = ir.GlobalVariable(mod, typ, "foo") + gv.linkage = linkage + asm = str(mod) + # check if 'undef' is present + if has_undef: + self.assertIn('undef', asm) + else: + self.assertNotIn('undef', asm) + # parse assembly to ensure correctness + self.module(asm) + + def test_internal_linkage(self): + self.check_global_variable_linkage('internal') + + def test_common_linkage(self): + self.check_global_variable_linkage('common') + + def test_external_linkage(self): + self.check_global_variable_linkage('external', has_undef=False) + + def test_available_externally_linkage(self): + self.check_global_variable_linkage('available_externally') + + def test_private_linkage(self): + self.check_global_variable_linkage('private') + + def test_linkonce_linkage(self): + self.check_global_variable_linkage('linkonce') + + def test_weak_linkage(self): + self.check_global_variable_linkage('weak') + + def test_appending_linkage(self): + self.check_global_variable_linkage('appending') + + def test_extern_weak_linkage(self): + self.check_global_variable_linkage('extern_weak', has_undef=False) + + def test_linkonce_odr_linkage(self): + self.check_global_variable_linkage('linkonce_odr') + + def test_weak_odr_linkage(self): + self.check_global_variable_linkage('weak_odr') + + +@unittest.skipUnless(platform.machine().startswith('x86'), "only on x86") +class TestInlineAsm(BaseTest): + def test_inlineasm(self): + llvm.initialize_native_asmparser() + m = self.module(asm=asm_inlineasm) + tm = self.target_machine(jit=False) + asm = tm.emit_assembly(m) + self.assertIn('nop', asm) + + +class TestObjectFile(BaseTest): + + mod_asm = """ + ;ModuleID = + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + + define i32 @sum_twice(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = call i32 @sum(i32 %.3, i32 %.3) + ret i32 %.4 + }} + """ + + def test_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + # Check that we have a text section, and that she has a name and data + has_text = False + last_address = -1 + for s in obj.sections(): + if s.is_text(): + has_text = True + self.assertIsNotNone(s.name()) + self.assertTrue(s.size() > 0) + self.assertTrue(len(s.data()) > 0) + self.assertIsNotNone(s.address()) + self.assertTrue(last_address < s.address()) + last_address = s.address() + break + self.assertTrue(has_text) + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(obj) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + try: + f = os.fdopen(temp_desc, "wb") + f.write(obj_bin) + f.flush() + finally: + f.close() + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(temp_path) + finally: + os.unlink(temp_path) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_get_section_content(self): + # See Issue #632 - section contents were getting truncated at null + # bytes. + elf = bytes.fromhex(issue_632_elf) + obj = llvm.ObjectFileRef.from_data(elf) + for s in obj.sections(): + if s.is_text(): + self.assertEqual(len(s.data()), 31) + self.assertEqual(s.data().hex(), issue_632_text) + + +class TestTimePasses(BaseTest): + def test_reporting(self): + mp = llvm.create_module_pass_manager() + + pmb = llvm.create_pass_manager_builder() + pmb.opt_level = 3 + pmb.populate(mp) + + try: + llvm.set_time_passes(True) + mp.run(self.module()) + mp.run(self.module()) + mp.run(self.module()) + finally: + report = llvm.report_and_reset_timings() + llvm.set_time_passes(False) + + self.assertIsInstance(report, str) + self.assertEqual(report.count("Pass execution timing report"), 1) + + def test_empty_report(self): + # Returns empty str if no data is collected + self.assertFalse(llvm.report_and_reset_timings()) + + +class TestLLVMLockCallbacks(BaseTest): + def test_lock_callbacks(self): + events = [] + + def acq(): + events.append('acq') + + def rel(): + events.append('rel') + + # register callback + llvm.ffi.register_lock_callback(acq, rel) + + # Check: events are initially empty + self.assertFalse(events) + # Call LLVM functions + llvm.create_module_pass_manager() + # Check: there must be at least one acq and one rel + self.assertIn("acq", events) + self.assertIn("rel", events) + + # unregister callback + llvm.ffi.unregister_lock_callback(acq, rel) + + # Check: removing non-existent callbacks will trigger a ValueError + with self.assertRaises(ValueError): + llvm.ffi.unregister_lock_callback(acq, rel) + + +class TestPipelineTuningOptions(BaseTest): + + def pto(self): + return llvm.create_pipeline_tuning_options() + + def test_close(self): + pto = self.pto() + pto.close() + + def test_speed_level(self): + pto = self.pto() + self.assertIsInstance(pto.speed_level, int) + for i in range(4): + pto.speed_level = i + self.assertEqual(pto.speed_level, i) + + def test_size_level(self): + pto = self.pto() + self.assertIsInstance(pto.size_level, int) + for i in range(3): + pto.size_level = i + self.assertEqual(pto.size_level, i) + + # // FIXME: Available from llvm16 + # def test_inlining_threshold(self): + # pto = self.pto() + # with self.assertRaises(NotImplementedError): + # pto.inlining_threshold + # for i in (25, 80, 350): + # pto.inlining_threshold = i + + def test_loop_interleaving(self): + pto = self.pto() + self.assertIsInstance(pto.loop_interleaving, bool) + for b in (True, False): + pto.loop_interleaving = b + self.assertEqual(pto.loop_interleaving, b) + + def test_loop_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.loop_vectorization, bool) + for b in (True, False): + pto.loop_vectorization = b + self.assertEqual(pto.loop_vectorization, b) + + def test_slp_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.slp_vectorization, bool) + for b in (True, False): + pto.slp_vectorization = b + self.assertEqual(pto.slp_vectorization, b) + + def test_loop_unrolling(self): + pto = self.pto() + self.assertIsInstance(pto.loop_unrolling, bool) + for b in (True, False): + pto.loop_unrolling = b + self.assertEqual(pto.loop_unrolling, b) + + def test_speed_level_constraints(self): + pto = self.pto() + with self.assertRaises(ValueError): + pto.speed_level = 4 + with self.assertRaises(ValueError): + pto.speed_level = -1 + + def test_size_level_constraints(self): + pto = self.pto() + with self.assertRaises(ValueError): + pto.size_level = 3 + with self.assertRaises(ValueError): + pto.speed_level = -1 + with self.assertRaises(ValueError): + pto.speed_level = 3 + pto.size_level = 2 + + +class NewPassManagerMixin(object): + + def pb(self, speed_level=0, size_level=0): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(speed_level, size_level) + pb = llvm.create_pass_builder(tm, pto) + return pb + + +class TestPassBuilder(BaseTest, NewPassManagerMixin): + + def test_close(self): + pb = self.pb() + pb.close() + + def test_pto(self): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(3, 0) + pto.inlining_threshold = 2 + pto.loop_interleaving = True + pto.loop_vectorization = True + pto.slp_vectorization = True + pto.loop_unrolling = False + pb = llvm.create_pass_builder(tm, pto) + pb.close() + + def test_get_module_pass_manager(self): + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(self.module(), pb) + pb.close() + + def test_get_function_pass_manager(self): + pb = self.pb() + fpm = pb.getFunctionPassManager() + fpm.run(self.module().get_function("sum"), pb) + pb.close() + + +class TestNewModulePassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_module_pass_manager() + + def run_o_n(self, level): + mod = self.module() + orig_asm = str(mod) + pb = self.pb(speed_level=level, size_level=0) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + return orig_asm, optimized_asm + + def test_close(self): + mpm = self.pm() + mpm.close() + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_instcombine(self): + pb = self.pb() + mpm = self.pm() + mpm.add_instruction_combine_pass() + mod = self.module(asm_sum4) + orig_asm = str(mod) + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3, size_level=0) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + mod = llvm.parse_assembly(orig_asm) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Module shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + mpm = pb.getModulePassManager() + mod = llvm.parse_assembly(orig_asm_optnone) + mpm.run(mod, pb) + optimized_asm_optnone = str(mod) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_add_passes(self): + mpm = self.pm() + mpm.add_verifier() + mpm.add_aa_eval_pass() + mpm.add_simplify_cfg_pass() + mpm.add_loop_unroll_pass() + mpm.add_loop_rotate_pass() + mpm.add_instruction_combine_pass() + mpm.add_jump_threading_pass() + mpm.add_refprune_pass() + + +class TestNewFunctionPassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_function_pass_manager() + + def test_close(self): + fpm = self.pm() + fpm.close() + + def run_o_n(self, level): + mod = self.module() + fun = mod.get_function("sum") + orig_asm = str(fun) + pb = self.pb(speed_level=level, size_level=0) + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + return orig_asm, optimized_asm + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3, size_level=0) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + fun = llvm.parse_assembly(orig_asm).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Function shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + fun = llvm.parse_assembly(orig_asm_optnone).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm_optnone = str(fun) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_instcombine(self): + pb = self.pb() + fpm = self.pm() + fun = self.module(asm_sum4).get_function("sum") + fpm.add_instruction_combine_pass() + orig_asm = str(fun) + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + # This should not crash + def test_declarations(self): + pb = self.pb(3) + fpm = pb.getFunctionPassManager() + for fun in llvm.parse_assembly(asm_declaration).functions: + fpm.run(fun, pb) + + def test_add_passes(self): + fpm = self.pm() + fpm.add_aa_eval_pass() + fpm.add_simplify_cfg_pass() + fpm.add_loop_unroll_pass() + fpm.add_loop_rotate_pass() + fpm.add_instruction_combine_pass() + fpm.add_jump_threading_pass() + fpm.add_refprune_pass() + + +if __name__ == "__main__": + unittest.main() diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/test_ir.py b/python_embeded/Lib/site-packages/llvmlite/tests/test_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..5ecef3210d15a5dc9b05ff671f3f29cb7c1bff90 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/test_ir.py @@ -0,0 +1,2994 @@ +""" +IR Construction Tests +""" + +import copy +import itertools +import pickle +import re +import textwrap +import unittest + +from . import TestCase +from llvmlite import ir +from llvmlite import binding as llvm + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled + + +int1 = ir.IntType(1) +int8 = ir.IntType(8) +int16 = ir.IntType(16) +int32 = ir.IntType(32) +int64 = ir.IntType(64) +hlf = ir.HalfType() +flt = ir.FloatType() +dbl = ir.DoubleType() + + +class TestBase(TestCase): + """ + Utilities for IR tests. + """ + + def assertInText(self, pattern, text): + """ + Assert *pattern* is in *text*, ignoring any whitespace differences + (including newlines). + """ + + def escape(c): + if not c.isalnum() and not c.isspace(): + return '\\' + c + return c + + pattern = ''.join(map(escape, pattern)) + regex = re.sub(r'\s+', r'\\s*', pattern) + self.assertRegex(text, regex) + + def assert_ir_line(self, line, mod): + lines = [line.strip() for line in str(mod).splitlines()] + self.assertIn(line, lines) + + def assert_valid_ir(self, mod): + llvm.parse_assembly(str(mod)) + + def assert_pickle_correctly(self, irobject): + """Assert that the IR object pickles and unpickles correctly. + The IR string is equal and that their type is equal + """ + newobject = pickle.loads(pickle.dumps(irobject, protocol=-1)) + self.assertIs(irobject.__class__, newobject.__class__) + self.assertEqual(str(irobject), str(newobject)) + return newobject + + def module(self): + return ir.Module() + + def function(self, module=None, name='my_func'): + module = module or self.module() + fnty = ir.FunctionType(int32, (int32, int32, dbl, + ir.PointerType(int32))) + return ir.Function(module, fnty, name) + + def block(self, func=None, name=''): + func = func or self.function() + return func.append_basic_block(name) + + def descr(self, thing): + buf = [] + thing.descr(buf) + return "".join(buf) + + def _normalize_asm(self, asm): + asm = textwrap.dedent(asm) + # Normalize indent + asm = asm.replace("\n ", "\n ") + return asm + + def check_descr_regex(self, descr, asm): + expected = self._normalize_asm(asm) + self.assertRegex(descr, expected) + + def check_descr(self, descr, asm): + expected = self._normalize_asm(asm) + self.assertEqual(descr, expected) + + def check_block(self, block, asm): + self.check_descr(self.descr(block), asm) + + def check_block_regex(self, block, asm): + self.check_descr_regex(self.descr(block), asm) + + def check_module_body(self, module, asm): + expected = self._normalize_asm(asm) + actual = module._stringify_body() + self.assertEqual(actual.strip(), expected.strip()) + + def check_metadata(self, module, asm): + """ + Check module metadata against *asm*. + """ + expected = self._normalize_asm(asm) + actual = module._stringify_metadata() + self.assertEqual(actual.strip(), expected.strip()) + + def check_func_body(self, func, asm): + expected = self._normalize_asm(asm) + actual = self.descr(func) + actual = actual.partition('{')[2].rpartition('}')[0] + self.assertEqual(actual.strip(), expected.strip()) + + +class TestFunction(TestBase): + + # FIXME: Remove `else' once TP are no longer supported. + proto = \ + """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", ptr %".4")""" \ + if opaque_pointers_enabled else \ + """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", i32* %".4")""" + + def test_declare(self): + # A simple declaration + func = self.function() + asm = self.descr(func).strip() + self.assertEqual(asm.strip(), "declare %s" % self.proto) + + def test_declare_attributes(self): + # Now with function attributes + func = self.function() + func.attributes.add("optsize") + func.attributes.add("alwaysinline") + func.attributes.add("convergent") + func.attributes.alignstack = 16 + tp_pers = ir.FunctionType(int8, (), var_arg=True) + pers = ir.Function(self.module(), tp_pers, '__gxx_personality_v0') + func.attributes.personality = pers + asm = self.descr(func).strip() + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(asm, + ("declare %s alwaysinline convergent optsize " + "alignstack(16) " + "personality ptr @\"__gxx_personality_v0\"") % + self.proto) + else: + self.assertEqual(asm, + ("declare %s alwaysinline convergent optsize " + "alignstack(16) personality " + "i8 (...)* @\"__gxx_personality_v0\"") % + self.proto) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attributes(self): + # Now with parameter attributes + func = self.function() + func.args[0].add_attribute("zeroext") + func.args[1].attributes.dereferenceable = 5 + func.args[1].attributes.dereferenceable_or_null = 10 + func.args[3].attributes.align = 4 + func.args[3].add_attribute("nonnull") + func.return_value.add_attribute("noalias") + asm = self.descr(func).strip() + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(asm, + """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", ptr nonnull align 4 %".4")""" # noqa E501 + ) + else: + self.assertEqual(asm, + """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", i32* nonnull align 4 %".4")""" # noqa E501 + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_metadata(self): + # Now with function metadata + module = self.module() + func = self.function(module) + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_section(self): + # Test function with section + func = self.function() + func.section = "a_section" + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} section "a_section"' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_section_meta(self): + # Test function with section and metadata + module = self.module() + func = self.function(module) + func.section = "a_section" + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} section "a_section" !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_meta(self): + # Test function with attributes and metadata + module = self.module() + func = self.function(module) + func.attributes.add("alwaysinline") + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} alwaysinline !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_section(self): + # Test function with attributes and section + func = self.function() + func.attributes.add("optsize") + func.section = "a_section" + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} optsize section "a_section"') + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_section_meta(self): + # Test function with attributes, section and metadata + module = self.module() + func = self.function(module) + func.attributes.add("alwaysinline") + func.section = "a_section" + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} alwaysinline section "a_section" !dbg !0' # noqa E501 + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_define(self): + # A simple definition + func = self.function() + func.attributes.add("alwaysinline") + block = func.append_basic_block('my_block') + builder = ir.IRBuilder(block) + builder.ret_void() + asm = self.descr(func) + self.check_descr(asm, """\ + define {proto} alwaysinline + {{ + my_block: + ret void + }} + """.format(proto=self.proto)) + + def test_declare_intrinsics(self): + module = self.module() + pint8 = int8.as_pointer() + + powi = module.declare_intrinsic('llvm.powi', [dbl]) + memset = module.declare_intrinsic('llvm.memset', [pint8, int32]) + memcpy = module.declare_intrinsic('llvm.memcpy', [pint8, pint8, int32]) + assume = module.declare_intrinsic('llvm.assume') + self.check_descr(self.descr(powi).strip(), """\ + declare double @"llvm.powi.f64"(double %".1", i32 %".2")""") + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_descr(self.descr(memset).strip(), """\ + declare void @"llvm.memset.p0i8.i32"(ptr %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(memcpy).strip(), """\ + declare void @"llvm.memcpy.p0i8.p0i8.i32"(ptr %".1", ptr %".2", i32 %".3", i1 %".4")""") # noqa E501 + else: + self.check_descr(self.descr(memset).strip(), """\ + declare void @"llvm.memset.p0i8.i32"(i8* %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(memcpy).strip(), """\ + declare void @"llvm.memcpy.p0i8.p0i8.i32"(i8* %".1", i8* %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(assume).strip(), """\ + declare void @"llvm.assume"(i1 %".1")""") + + def test_redeclare_intrinsic(self): + module = self.module() + powi = module.declare_intrinsic('llvm.powi', [dbl]) + powi2 = module.declare_intrinsic('llvm.powi', [dbl]) + self.assertIs(powi, powi2) + + def test_pickling(self): + fn = self.function() + self.assert_pickle_correctly(fn) + + def test_alwaysinline_noinline_disallowed(self): + module = self.module() + func = self.function(module) + func.attributes.add('alwaysinline') + + msg = "Can't have alwaysinline and noinline" + with self.assertRaisesRegex(ValueError, msg): + func.attributes.add('noinline') + + def test_noinline_alwaysinline_disallowed(self): + module = self.module() + func = self.function(module) + func.attributes.add('noinline') + + msg = "Can't have alwaysinline and noinline" + with self.assertRaisesRegex(ValueError, msg): + func.attributes.add('alwaysinline') + + +class TestIR(TestBase): + + def test_unnamed_metadata(self): + # An unnamed metadata node + mod = self.module() + mod.add_metadata([int32(123), int8(42)]) + self.assert_ir_line("!0 = !{ i32 123, i8 42 }", mod) + self.assert_valid_ir(mod) + + def test_unnamed_metadata_2(self): + # Several unnamed metadata nodes + mod = self.module() + # First node has a literal metadata string + m0 = mod.add_metadata([int32(123), "kernel"]) + # Second node refers to the first one + m1 = mod.add_metadata([int64(456), m0]) + # Third node is the same as the second one + m2 = mod.add_metadata([int64(456), m0]) + self.assertIs(m2, m1) + # Fourth node refers to the first three + mod.add_metadata([m0, m1, m2]) + self.assert_ir_line('!0 = !{ i32 123, !"kernel" }', mod) + self.assert_ir_line('!1 = !{ i64 456, !0 }', mod) + self.assert_ir_line('!2 = !{ !0, !1, !1 }', mod) + + def test_unnamed_metadata_3(self): + # Passing nested metadata as a sequence + mod = self.module() + mod.add_metadata([int32(123), [int32(456)], [int32(789)], [int32(456)]]) + self.assert_ir_line('!0 = !{ i32 456 }', mod) + self.assert_ir_line('!1 = !{ i32 789 }', mod) + self.assert_ir_line('!2 = !{ i32 123, !0, !1, !0 }', mod) + + def test_metadata_string(self): + # Escaping contents of a metadata string + mod = self.module() + mod.add_metadata(["\"\\$"]) + self.assert_ir_line('!0 = !{ !"\\22\\5c$" }', mod) + + def test_named_metadata(self): + # Add a named metadata node and add metadata values to it + mod = self.module() + m0 = mod.add_metadata([int32(123)]) + m1 = mod.add_metadata([int64(456)]) + nmd = mod.add_named_metadata("foo") + nmd.add(m0) + nmd.add(m1) + nmd.add(m0) + self.assert_ir_line("!foo = !{ !0, !1, !0 }", mod) + self.assert_valid_ir(mod) + # Check get_named_metadata() + self.assertIs(nmd, mod.get_named_metadata("foo")) + with self.assertRaises(KeyError): + mod.get_named_metadata("bar") + + def test_named_metadata_2(self): + # Add and set named metadata through a single add_named_metadata() call + mod = self.module() + m0 = mod.add_metadata([int32(123)]) + mod.add_named_metadata("foo", m0) + mod.add_named_metadata("foo", [int64(456)]) + mod.add_named_metadata("foo", ["kernel"]) + mod.add_named_metadata("bar", []) + self.assert_ir_line("!foo = !{ !0, !1, !2 }", mod) + self.assert_ir_line("!0 = !{ i32 123 }", mod) + self.assert_ir_line("!1 = !{ i64 456 }", mod) + self.assert_ir_line('!2 = !{ !"kernel" }', mod) + self.assert_ir_line("!bar = !{ !3 }", mod) + self.assert_ir_line('!3 = !{ }', mod) + self.assert_valid_ir(mod) + + def test_metadata_null(self): + # A null metadata (typed) value + mod = self.module() + mod.add_metadata([int32.as_pointer()(None)]) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assert_ir_line("!0 = !{ ptr null }", mod) + else: + self.assert_ir_line("!0 = !{ i32* null }", mod) + self.assert_valid_ir(mod) + # A null metadata (untyped) value + mod = self.module() + mod.add_metadata([None, int32(123)]) + self.assert_ir_line("!0 = !{ null, i32 123 }", mod) + self.assert_valid_ir(mod) + + def test_debug_info(self): + # Add real world-looking debug information to a module + # (with various value types) + mod = self.module() + di_file = mod.add_debug_info("DIFile", { + "filename": "foo", + "directory": "bar", + }) + di_func_type = mod.add_debug_info("DISubroutineType", { + # None as `null` + "types": mod.add_metadata([None]), + }) + di_compileunit = mod.add_debug_info("DICompileUnit", { + "language": ir.DIToken("DW_LANG_Python"), + "file": di_file, + "producer": "ARTIQ", + "runtimeVersion": 0, + "isOptimized": True, + }, is_distinct=True) + mod.add_debug_info("DISubprogram", { + "name": "my_func", + "file": di_file, + "line": 11, + "type": di_func_type, + "isLocal": False, + "unit": di_compileunit, + }, is_distinct=True) + + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")', + strmod) + self.assert_ir_line('!1 = !{ null }', strmod) + self.assert_ir_line('!2 = !DISubroutineType(types: !1)', strmod) + # self.assert_ir_line('!4 = !{ !3 }', strmod) + self.assert_ir_line('!3 = distinct !DICompileUnit(file: !0, ' + 'isOptimized: true, language: DW_LANG_Python, ' + 'producer: "ARTIQ", runtimeVersion: 0)', + strmod) + self.assert_ir_line('!4 = distinct !DISubprogram(file: !0, isLocal: ' + 'false, line: 11, name: "my_func", type: !2, unit: ' + '!3)', + strmod) + self.assert_valid_ir(mod) + + def test_debug_info_2(self): + # Identical debug info nodes should be merged + mod = self.module() + di1 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }) + di2 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }) + di3 = mod.add_debug_info("DIFile", + {"filename": "bar", + "directory": "foo", + }) + di4 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }, is_distinct=True) + self.assertIs(di1, di2) + self.assertEqual(len({di1, di2, di3, di4}), 3) + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")', + strmod) + self.assert_ir_line('!1 = !DIFile(directory: "foo", filename: "bar")', + strmod) + self.assert_ir_line('!2 = distinct !DIFile(directory: "bar", filename: ' + '"foo")', strmod) + self.assert_valid_ir(mod) + + def test_debug_info_gvar(self): + # This test defines a module with a global variable named 'gvar'. + # When the module is compiled and linked with a main function, gdb can + # be used to interpret and print the the value of 'gvar'. + mod = self.module() + + gvar = ir.GlobalVariable(mod, ir.FloatType(), 'gvar') + gvar.initializer = ir.Constant(ir.FloatType(), 42) + + di_float = mod.add_debug_info("DIBasicType", { + "name": "float", + "size": 32, + "encoding": ir.DIToken("DW_ATE_float") + }) + di_gvar = mod.add_debug_info("DIGlobalVariableExpression", { + "expr": mod.add_debug_info("DIExpression", {}), + "var": mod.add_debug_info("DIGlobalVariable", { + "name": gvar.name, + "type": di_float, + "isDefinition": True + }, is_distinct=True) + }) + gvar.set_metadata('dbg', di_gvar) + + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIBasicType(encoding: DW_ATE_float, ' + 'name: "float", size: 32)', strmod) + self.assert_ir_line('!1 = !DIExpression()', strmod) + self.assert_ir_line('!2 = distinct !DIGlobalVariable(isDefinition: ' + 'true, name: "gvar", type: !0)', strmod) + self.assert_ir_line('!3 = !DIGlobalVariableExpression(expr: !1, ' + 'var: !2)', strmod) + self.assert_ir_line('@"gvar" = global float 0x4045000000000000, ' + '!dbg !3', strmod) + + # The remaining debug info is not part of the automated test, but + # can be used to produce an object file that can be loaded into a + # debugger to print the value of gvar. This can be done by printing the + # module then compiling it with clang and inspecting with gdb: + # + # clang test_debug_info_gvar.ll -c + # printf "file test_debug_info_gvar.o \n p gvar" | gdb + # + # Which should result in the output: + # + # (gdb) $1 = 42 + + dver = [ir.IntType(32)(2), 'Dwarf Version', ir.IntType(32)(4)] + diver = [ir.IntType(32)(2), 'Debug Info Version', ir.IntType(32)(3)] + dver = mod.add_metadata(dver) + diver = mod.add_metadata(diver) + flags = mod.add_named_metadata('llvm.module.flags') + flags.add(dver) + flags.add(diver) + + di_file = mod.add_debug_info("DIFile", { + "filename": "foo", + "directory": "bar", + }) + di_cu = mod.add_debug_info("DICompileUnit", { + "language": ir.DIToken("DW_LANG_Python"), + "file": di_file, + 'emissionKind': ir.DIToken('FullDebug'), + "globals": mod.add_metadata([di_gvar]) + }, is_distinct=True) + mod.add_named_metadata('llvm.dbg.cu', di_cu) + + def test_debug_info_unicode_string(self): + mod = self.module() + mod.add_debug_info("DILocalVariable", {"name": "a∆"}) + # Check output + strmod = str(mod) + # The unicode character is utf8 encoded with \XX format, where XX is hex + name = ''.join(map(lambda x: f"\\{x:02x}", "∆".encode())) + self.assert_ir_line(f'!0 = !DILocalVariable(name: "a{name}")', strmod) + + def test_inline_assembly(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + asmty = ir.FunctionType(int32, [int32]) + asm = ir.InlineAsm(asmty, "mov $1, $2", "=r,r", side_effect=True) + builder.call(asm, [int32(123)]) + builder.ret_void() + pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r" ( i32 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_asm(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + asmty = ir.FunctionType(int32, [int32]) + builder.asm(asmty, "mov $1, $2", "=r,r", [int32(123)], side_effect=True) + builder.ret_void() + pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r" ( i32 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_load_reg(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + builder.load_reg(ir.IntType(64), "rax") + builder.ret_void() + pat = 'call i64 asm "", "={rax}"' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_store_reg(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + builder.store_reg(int64(123), ir.IntType(64), "rax") + builder.ret_void() + pat = 'call void asm sideeffect "", "{rax}" ( i64 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + +class TestGlobalValues(TestBase): + + def test_globals_access(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'bar') + globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble') + self.assertEqual(mod.get_global('foo'), foo) + self.assertEqual(mod.get_global('globdouble'), globdouble) + with self.assertRaises(KeyError): + mod.get_global('kkk') + # Globals should have a useful repr() + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(repr(globdouble), + "") + else: + self.assertEqual( + repr(globdouble), + "") + + def test_functions_global_values_access(self): + """ + Accessing functions and global values through Module.functions + and Module.global_values. + """ + mod = self.module() + fty = ir.FunctionType(ir.VoidType(), []) + foo = ir.Function(mod, fty, 'foo') + bar = ir.Function(mod, fty, 'bar') + globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble') + self.assertEqual(set(mod.functions), set((foo, bar))) + self.assertEqual(set(mod.global_values), set((foo, bar, globdouble))) + + def test_global_variables_ir(self): + """ + IR serialization of global variables. + """ + mod = self.module() + # the following have side effects and write to self.module() + a = ir.GlobalVariable(mod, int8, 'a') # noqa F841 + b = ir.GlobalVariable(mod, int8, 'b', addrspace=42) # noqa F841 + # Initialized global variable doesn't default to "external" + c = ir.GlobalVariable(mod, int32, 'c') + c.initializer = int32(123) + d = ir.GlobalVariable(mod, int32, 'd') + d.global_constant = True + # Non-external linkage implies default "undef" initializer + e = ir.GlobalVariable(mod, int32, 'e') + e.linkage = "internal" + f = ir.GlobalVariable(mod, int32, 'f', addrspace=456) + f.unnamed_addr = True + g = ir.GlobalVariable(mod, int32, 'g') + g.linkage = "internal" + g.initializer = int32(123) + g.align = 16 + h = ir.GlobalVariable(mod, int32, 'h') + h.linkage = "internal" + h.initializer = int32(123) + h.section = "h_section" + i = ir.GlobalVariable(mod, int32, 'i') + i.linkage = "internal" + i.initializer = int32(456) + i.align = 8 + i.section = "i_section" + self.check_module_body(mod, """\ + @"a" = external global i8 + @"b" = external addrspace(42) global i8 + @"c" = global i32 123 + @"d" = external constant i32 + @"e" = internal global i32 undef + @"f" = external unnamed_addr addrspace(456) global i32 + @"g" = internal global i32 123, align 16 + @"h" = internal global i32 123, section "h_section" + @"i" = internal global i32 456, section "i_section", align 8 + """) + + def test_pickle(self): + mod = self.module() + self.assert_pickle_correctly(mod) + + +class TestBlock(TestBase): + + def test_attributes(self): + func = self.function() + block = ir.Block(parent=func, name='start') + self.assertIs(block.parent, func) + self.assertFalse(block.is_terminated) + + def test_descr(self): + block = self.block(name='my_block') + self.assertEqual(self.descr(block), "my_block:\n") + block.instructions.extend(['a', 'b']) + self.assertEqual(self.descr(block), "my_block:\n a\n b\n") + + def test_replace(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.add(a, b, 'c') + d = builder.sub(a, b, 'd') + builder.mul(d, b, 'e') + f = ir.Instruction(block, a.type, 'sdiv', (c, b), 'f') + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"d" = sub i32 %".1", %".2" + %"e" = mul i32 %"d", %".2" + """) + block.replace(d, f) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"f" = sdiv i32 %"c", %".2" + %"e" = mul i32 %"f", %".2" + """) + + def test_repr(self): + """ + Blocks should have a useful repr() + """ + func = self.function() + block = ir.Block(parent=func, name='start') + self.assertEqual(repr(block), "") + + +class TestBuildInstructions(TestBase): + """ + Test IR generation of LLVM instructions through the IRBuilder class. + """ + + maxDiff = 4000 + + def test_simple(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + inst = builder.add(a, b, 'res') + self.check_block(block, """\ + my_block: + %"res" = add i32 %".1", %".2" + """) + # Instructions should have a useful repr() + self.assertEqual(repr(inst), + ", " + ")>") + + def test_binops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, ff = builder.function.args[:3] + builder.add(a, b, 'c') + builder.fadd(a, b, 'd') + builder.sub(a, b, 'e') + builder.fsub(a, b, 'f') + builder.mul(a, b, 'g') + builder.fmul(a, b, 'h') + builder.udiv(a, b, 'i') + builder.sdiv(a, b, 'j') + builder.fdiv(a, b, 'k') + builder.urem(a, b, 'l') + builder.srem(a, b, 'm') + builder.frem(a, b, 'n') + builder.or_(a, b, 'o') + builder.and_(a, b, 'p') + builder.xor(a, b, 'q') + builder.shl(a, b, 'r') + builder.ashr(a, b, 's') + builder.lshr(a, b, 't') + with self.assertRaises(ValueError) as cm: + builder.add(a, ff) + self.assertEqual(str(cm.exception), + "Operands must be the same type, got (i32, double)") + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"d" = fadd i32 %".1", %".2" + %"e" = sub i32 %".1", %".2" + %"f" = fsub i32 %".1", %".2" + %"g" = mul i32 %".1", %".2" + %"h" = fmul i32 %".1", %".2" + %"i" = udiv i32 %".1", %".2" + %"j" = sdiv i32 %".1", %".2" + %"k" = fdiv i32 %".1", %".2" + %"l" = urem i32 %".1", %".2" + %"m" = srem i32 %".1", %".2" + %"n" = frem i32 %".1", %".2" + %"o" = or i32 %".1", %".2" + %"p" = and i32 %".1", %".2" + %"q" = xor i32 %".1", %".2" + %"r" = shl i32 %".1", %".2" + %"s" = ashr i32 %".1", %".2" + %"t" = lshr i32 %".1", %".2" + """) + + def test_binop_flags(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + # As tuple + builder.add(a, b, 'c', flags=('nuw',)) + # and as list + builder.sub(a, b, 'd', flags=['nuw', 'nsw']) + self.check_block(block, """\ + my_block: + %"c" = add nuw i32 %".1", %".2" + %"d" = sub nuw nsw i32 %".1", %".2" + """) + + def test_binop_fastmath_flags(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + # As tuple + builder.fadd(a, b, 'c', flags=('fast',)) + # and as list + builder.fsub(a, b, 'd', flags=['ninf', 'nsz']) + self.check_block(block, """\ + my_block: + %"c" = fadd fast i32 %".1", %".2" + %"d" = fsub ninf nsz i32 %".1", %".2" + """) + + def test_binops_with_overflow(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.sadd_with_overflow(a, b, 'c') + builder.smul_with_overflow(a, b, 'd') + builder.ssub_with_overflow(a, b, 'e') + builder.uadd_with_overflow(a, b, 'f') + builder.umul_with_overflow(a, b, 'g') + builder.usub_with_overflow(a, b, 'h') + self.check_block(block, """\ +my_block: + %"c" = call {i32, i1} @"llvm.sadd.with.overflow.i32"(i32 %".1", i32 %".2") + %"d" = call {i32, i1} @"llvm.smul.with.overflow.i32"(i32 %".1", i32 %".2") + %"e" = call {i32, i1} @"llvm.ssub.with.overflow.i32"(i32 %".1", i32 %".2") + %"f" = call {i32, i1} @"llvm.uadd.with.overflow.i32"(i32 %".1", i32 %".2") + %"g" = call {i32, i1} @"llvm.umul.with.overflow.i32"(i32 %".1", i32 %".2") + %"h" = call {i32, i1} @"llvm.usub.with.overflow.i32"(i32 %".1", i32 %".2") + """) + + def test_unary_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, c = builder.function.args[:3] + builder.neg(a, 'd') + builder.not_(b, 'e') + builder.fneg(c, 'f') + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"d" = sub i32 0, %".1" + %"e" = xor i32 %".2", -1 + %"f" = fneg double %".3" + """) + + def test_replace_operand(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + undef1 = ir.Constant(ir.IntType(32), ir.Undefined) + undef2 = ir.Constant(ir.IntType(32), ir.Undefined) + c = builder.add(undef1, undef2, 'c') + self.check_block(block, """\ + my_block: + %"c" = add i32 undef, undef + """) + c.replace_usage(undef1, a) + c.replace_usage(undef2, b) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + """) + + def test_integer_comparisons(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.icmp_unsigned('==', a, b, 'c') + builder.icmp_unsigned('!=', a, b, 'd') + builder.icmp_unsigned('<', a, b, 'e') + builder.icmp_unsigned('<=', a, b, 'f') + builder.icmp_unsigned('>', a, b, 'g') + builder.icmp_unsigned('>=', a, b, 'h') + builder.icmp_signed('==', a, b, 'i') + builder.icmp_signed('!=', a, b, 'j') + builder.icmp_signed('<', a, b, 'k') + builder.icmp_signed('<=', a, b, 'l') + builder.icmp_signed('>', a, b, 'm') + builder.icmp_signed('>=', a, b, 'n') + with self.assertRaises(ValueError): + builder.icmp_signed('uno', a, b, 'zz') + with self.assertRaises(ValueError): + builder.icmp_signed('foo', a, b, 'zz') + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = icmp eq i32 %".1", %".2" + %"d" = icmp ne i32 %".1", %".2" + %"e" = icmp ult i32 %".1", %".2" + %"f" = icmp ule i32 %".1", %".2" + %"g" = icmp ugt i32 %".1", %".2" + %"h" = icmp uge i32 %".1", %".2" + %"i" = icmp eq i32 %".1", %".2" + %"j" = icmp ne i32 %".1", %".2" + %"k" = icmp slt i32 %".1", %".2" + %"l" = icmp sle i32 %".1", %".2" + %"m" = icmp sgt i32 %".1", %".2" + %"n" = icmp sge i32 %".1", %".2" + """) + + def test_float_comparisons(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.fcmp_ordered('==', a, b, 'c') + builder.fcmp_ordered('!=', a, b, 'd') + builder.fcmp_ordered('<', a, b, 'e') + builder.fcmp_ordered('<=', a, b, 'f') + builder.fcmp_ordered('>', a, b, 'g') + builder.fcmp_ordered('>=', a, b, 'h') + builder.fcmp_unordered('==', a, b, 'i') + builder.fcmp_unordered('!=', a, b, 'j') + builder.fcmp_unordered('<', a, b, 'k') + builder.fcmp_unordered('<=', a, b, 'l') + builder.fcmp_unordered('>', a, b, 'm') + builder.fcmp_unordered('>=', a, b, 'n') + # fcmp_ordered and fcmp_unordered are the same for these cases + builder.fcmp_ordered('ord', a, b, 'u') + builder.fcmp_ordered('uno', a, b, 'v') + builder.fcmp_unordered('ord', a, b, 'w') + builder.fcmp_unordered('uno', a, b, 'x') + builder.fcmp_unordered('olt', a, b, 'y', + flags=['nnan', 'ninf', 'nsz', 'arcp', 'fast']) + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = fcmp oeq i32 %".1", %".2" + %"d" = fcmp one i32 %".1", %".2" + %"e" = fcmp olt i32 %".1", %".2" + %"f" = fcmp ole i32 %".1", %".2" + %"g" = fcmp ogt i32 %".1", %".2" + %"h" = fcmp oge i32 %".1", %".2" + %"i" = fcmp ueq i32 %".1", %".2" + %"j" = fcmp une i32 %".1", %".2" + %"k" = fcmp ult i32 %".1", %".2" + %"l" = fcmp ule i32 %".1", %".2" + %"m" = fcmp ugt i32 %".1", %".2" + %"n" = fcmp uge i32 %".1", %".2" + %"u" = fcmp ord i32 %".1", %".2" + %"v" = fcmp uno i32 %".1", %".2" + %"w" = fcmp ord i32 %".1", %".2" + %"x" = fcmp uno i32 %".1", %".2" + %"y" = fcmp nnan ninf nsz arcp fast olt i32 %".1", %".2" + """) + + def test_misc_ops(self): + block = self.block(name='my_block') + t = ir.Constant(int1, True) + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.select(t, a, b, 'c', flags=('arcp', 'nnan')) + self.assertFalse(block.is_terminated) + builder.unreachable() + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = select arcp nnan i1 true, i32 %".1", i32 %".2" + unreachable + """) + + def test_phi(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + bb2 = builder.function.append_basic_block('b2') + bb3 = builder.function.append_basic_block('b3') + phi = builder.phi(int32, 'my_phi', flags=('fast',)) + phi.add_incoming(a, bb2) + phi.add_incoming(b, bb3) + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"my_phi" = phi fast i32 [%".1", %"b2"], [%".2", %"b3"] + """) + + def test_mem_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, z = builder.function.args[:3] + c = builder.alloca(int32, name='c') + d = builder.alloca(int32, size=42, name='d') # noqa F841 + e = builder.alloca(dbl, size=a, name='e') + e.align = 8 + self.assertEqual(e.type, ir.PointerType(dbl)) + ee = builder.store(z, e) + self.assertEqual(ee.type, ir.VoidType()) + f = builder.store(b, c) + self.assertEqual(f.type, ir.VoidType()) + g = builder.load(c, 'g') + self.assertEqual(g.type, int32) + # With alignment + h = builder.store(b, c, align=1) + self.assertEqual(h.type, ir.VoidType()) + i = builder.load(c, 'i', align=1) + self.assertEqual(i.type, int32) + # Atomics + j = builder.store_atomic(b, c, ordering="seq_cst", align=4) + self.assertEqual(j.type, ir.VoidType()) + k = builder.load_atomic(c, ordering="seq_cst", align=4, name='k') + self.assertEqual(k.type, int32) + if opaque_pointers_enabled: + ptr = ir.Constant(ir.PointerType(), None) + else: + ptr = ir.Constant(ir.PointerType(int32), None) + builder.store(ir.Constant(int32, 5), ptr) + # Not pointer types + with self.assertRaises(TypeError): + builder.store(b, a) + with self.assertRaises(TypeError): + builder.load(b) + # Mismatching pointer type + with self.assertRaises(TypeError) as cm: + builder.store(b, e) + + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(cm.exception), + "cannot store i32 to ptr: mismatching types") + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = alloca i32, i32 42 + %"e" = alloca double, i32 %".1", align 8 + store double %".3", ptr %"e" + store i32 %".2", ptr %"c" + %"g" = load i32, ptr %"c" + store i32 %".2", ptr %"c", align 1 + %"i" = load i32, ptr %"c", align 1 + store atomic i32 %".2", ptr %"c" seq_cst, align 4 + %"k" = load atomic i32, ptr %"c" seq_cst, align 4 + store i32 5, ptr null + """) + else: + self.assertEqual(str(cm.exception), + "cannot store i32 to double*: mismatching types") + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = alloca i32, i32 42 + %"e" = alloca double, i32 %".1", align 8 + store double %".3", double* %"e" + store i32 %".2", i32* %"c" + %"g" = load i32, i32* %"c" + store i32 %".2", i32* %"c", align 1 + %"i" = load i32, i32* %"c", align 1 + store atomic i32 %".2", i32* %"c" seq_cst, align 4 + %"k" = load atomic i32, i32* %"c" seq_cst, align 4 + store i32 5, i32* null + """) + + def test_gep(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.alloca(ir.PointerType(int32), name='c') + d = builder.gep(c, [ir.Constant(int32, 5), a], name='d') + self.assertEqual(d.type, ir.PointerType(int32)) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr + %"d" = getelementptr ptr, ptr %"c", i32 5, i32 %".1" + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32* + %"d" = getelementptr i32*, i32** %"c", i32 5, i32 %".1" + """) + # XXX test with more complex types + + def test_gep_castinstr(self): + # similar to: + # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data() + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + int8ptr = int8.as_pointer() + ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64]) + d = builder.bitcast(a, ls.as_pointer(), name='d') + e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e') + self.assertEqual(e.type, ir.PointerType(int8ptr)) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to ptr + %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr %"d", i32 0, i32 3 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64}* + %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64}* %"d", i32 0, i32 3 + """) # noqa E501 + + def test_gep_castinstr_addrspace(self): + # similar to: + # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data() + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + addrspace = 4 + int8ptr = int8.as_pointer() + ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64]) + d = builder.bitcast(a, ls.as_pointer(addrspace=addrspace), name='d') + e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e') + self.assertEqual(e.type.addrspace, addrspace) + self.assertEqual(e.type, ir.PointerType(int8ptr, addrspace=addrspace)) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to ptr addrspace(4) + %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr addrspace(4) %"d", i32 0, i32 3 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64} addrspace(4)* + %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64} addrspace(4)* %"d", i32 0, i32 3 + """) # noqa E501 + + def test_gep_addrspace(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + addrspace = 4 + c = builder.alloca(ir.PointerType(int32, addrspace=addrspace), name='c') + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c.type), 'ptr') + else: + self.assertEqual(str(c.type), 'i32 addrspace(4)**') + self.assertEqual(c.type.pointee.addrspace, addrspace) + d = builder.gep(c, [ir.Constant(int32, 5), a], name='d') + self.assertEqual(d.type.addrspace, addrspace) + e = builder.gep(d, [ir.Constant(int32, 10)], name='e') + self.assertEqual(e.type.addrspace, addrspace) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr addrspace(4) + %"d" = getelementptr ptr addrspace(4), ptr %"c", i32 5, i32 %".1" + %"e" = getelementptr i32, ptr addrspace(4) %"d", i32 10 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 addrspace(4)* + %"d" = getelementptr i32 addrspace(4)*, i32 addrspace(4)** %"c", i32 5, i32 %".1" + %"e" = getelementptr i32, i32 addrspace(4)* %"d", i32 10 + """) # noqa E501 + + def test_extract_insert_value(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_inner = ir.LiteralStructType([int32, int1]) + tp_outer = ir.LiteralStructType([int8, tp_inner]) + c_inner = ir.Constant(tp_inner, (ir.Constant(int32, 4), + ir.Constant(int1, True))) + # Flat structure + c = builder.extract_value(c_inner, 0, name='c') # noqa F841 + d = builder.insert_value(c_inner, a, 0, name='d') # noqa F841 + e = builder.insert_value(d, ir.Constant(int1, False), 1, name='e') # noqa F841 E501 + self.assertEqual(d.type, tp_inner) + self.assertEqual(e.type, tp_inner) + # Nested structure + p_outer = builder.alloca(tp_outer, name='ptr') + j = builder.load(p_outer, name='j') + k = builder.extract_value(j, 0, name='k') + l = builder.extract_value(j, 1, name='l') + m = builder.extract_value(j, (1, 0), name='m') + n = builder.extract_value(j, (1, 1), name='n') + o = builder.insert_value(j, l, 1, name='o') + p = builder.insert_value(j, a, (1, 0), name='p') + self.assertEqual(k.type, int8) + self.assertEqual(l.type, tp_inner) + self.assertEqual(m.type, int32) + self.assertEqual(n.type, int1) + self.assertEqual(o.type, tp_outer) + self.assertEqual(p.type, tp_outer) + + with self.assertRaises(TypeError): + # Not an aggregate + builder.extract_value(p_outer, 0) + with self.assertRaises(TypeError): + # Indexing too deep + builder.extract_value(c_inner, (0, 0)) + with self.assertRaises(TypeError): + # Index out of structure bounds + builder.extract_value(c_inner, 5) + with self.assertRaises(TypeError): + # Not an aggregate + builder.insert_value(a, b, 0) + with self.assertRaises(TypeError): + # Replacement value has the wrong type + builder.insert_value(c_inner, a, 1) + + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0 + %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0 + %"e" = insertvalue {i32, i1} %"d", i1 false, 1 + %"ptr" = alloca {i8, {i32, i1}} + %"j" = load {i8, {i32, i1}}, ptr %"ptr" + %"k" = extractvalue {i8, {i32, i1}} %"j", 0 + %"l" = extractvalue {i8, {i32, i1}} %"j", 1 + %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0 + %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1 + %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1 + %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0 + """) + else: + self.check_block(block, """\ + my_block: + %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0 + %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0 + %"e" = insertvalue {i32, i1} %"d", i1 false, 1 + %"ptr" = alloca {i8, {i32, i1}} + %"j" = load {i8, {i32, i1}}, {i8, {i32, i1}}* %"ptr" + %"k" = extractvalue {i8, {i32, i1}} %"j", 0 + %"l" = extractvalue {i8, {i32, i1}} %"j", 1 + %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0 + %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1 + %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1 + %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0 + """) + + def test_cast_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, fa, ptr = builder.function.args[:4] + c = builder.trunc(a, int8, name='c') + d = builder.zext(c, int32, name='d') # noqa F841 + e = builder.sext(c, int32, name='e') # noqa F841 + fb = builder.fptrunc(fa, flt, 'fb') + fc = builder.fpext(fb, dbl, 'fc') # noqa F841 + g = builder.fptoui(fa, int32, 'g') + h = builder.fptosi(fa, int8, 'h') + fd = builder.uitofp(g, flt, 'fd') # noqa F841 + fe = builder.sitofp(h, dbl, 'fe') # noqa F841 + i = builder.ptrtoint(ptr, int32, 'i') + j = builder.inttoptr(i, ir.PointerType(int8), 'j') # noqa F841 + k = builder.bitcast(a, flt, "k") # noqa F841 + self.assertFalse(block.is_terminated) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = trunc i32 %".1" to i8 + %"d" = zext i8 %"c" to i32 + %"e" = sext i8 %"c" to i32 + %"fb" = fptrunc double %".3" to float + %"fc" = fpext float %"fb" to double + %"g" = fptoui double %".3" to i32 + %"h" = fptosi double %".3" to i8 + %"fd" = uitofp i32 %"g" to float + %"fe" = sitofp i8 %"h" to double + %"i" = ptrtoint ptr %".4" to i32 + %"j" = inttoptr i32 %"i" to ptr + %"k" = bitcast i32 %".1" to float + """) + else: + self.check_block(block, """\ + my_block: + %"c" = trunc i32 %".1" to i8 + %"d" = zext i8 %"c" to i32 + %"e" = sext i8 %"c" to i32 + %"fb" = fptrunc double %".3" to float + %"fc" = fpext float %"fb" to double + %"g" = fptoui double %".3" to i32 + %"h" = fptosi double %".3" to i8 + %"fd" = uitofp i32 %"g" to float + %"fe" = sitofp i8 %"h" to double + %"i" = ptrtoint i32* %".4" to i32 + %"j" = inttoptr i32 %"i" to i8* + %"k" = bitcast i32 %".1" to float + """) + + def test_atomicrmw(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.alloca(int32, name='c') + d = builder.atomic_rmw('add', c, a, 'monotonic', 'd') + self.assertEqual(d.type, int32) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = atomicrmw add ptr %"c", i32 %".1" monotonic + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = atomicrmw add i32* %"c", i32 %".1" monotonic + """) + + def test_branch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_target = builder.function.append_basic_block(name='target') + builder.branch(bb_target) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br label %"target" + """) + + def test_cbranch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_true = builder.function.append_basic_block(name='b_true') + bb_false = builder.function.append_basic_block(name='b_false') + builder.cbranch(ir.Constant(int1, False), bb_true, bb_false) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br i1 false, label %"b_true", label %"b_false" + """) + + def test_cbranch_weights(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_true = builder.function.append_basic_block(name='b_true') + bb_false = builder.function.append_basic_block(name='b_false') + br = builder.cbranch(ir.Constant(int1, False), bb_true, bb_false) + br.set_weights([5, 42]) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br i1 false, label %"b_true", label %"b_false", !prof !0 + """) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 5, i32 42 } + """) + + def test_branch_indirect(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_1 = builder.function.append_basic_block(name='b_1') + bb_2 = builder.function.append_basic_block(name='b_2') + indirectbr = builder.branch_indirect( + ir.BlockAddress(builder.function, bb_1)) + indirectbr.add_destination(bb_1) + indirectbr.add_destination(bb_2) + self.assertTrue(block.is_terminated) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + indirectbr ptr blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"] + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + indirectbr i8* blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"] + """) # noqa E501 + + def test_returns(self): + def check(block, expected_ir): + self.assertTrue(block.is_terminated) + self.check_block(block, expected_ir) + + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + builder.ret_void() + check(block, """\ + my_block: + ret void + """) + + block = self.block(name='other_block') + builder = ir.IRBuilder(block) + builder.ret(int32(5)) + check(block, """\ + other_block: + ret i32 5 + """) + + # With metadata + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + inst = builder.ret_void() + inst.set_metadata("dbg", block.module.add_metadata(())) + check(block, """\ + my_block: + ret void, !dbg !0 + """) + + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + inst = builder.ret(int32(6)) + inst.set_metadata("dbg", block.module.add_metadata(())) + check(block, """\ + my_block: + ret i32 6, !dbg !0 + """) + + def test_switch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + bb_onzero = builder.function.append_basic_block(name='onzero') + bb_onone = builder.function.append_basic_block(name='onone') + bb_ontwo = builder.function.append_basic_block(name='ontwo') + bb_else = builder.function.append_basic_block(name='otherwise') + sw = builder.switch(a, bb_else) + sw.add_case(ir.Constant(int32, 0), bb_onzero) + sw.add_case(ir.Constant(int32, 1), bb_onone) + # A plain Python value gets converted into the right IR constant + sw.add_case(2, bb_ontwo) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + switch i32 %".1", label %"otherwise" [i32 0, label %"onzero" i32 1, label %"onone" i32 2, label %"ontwo"] + """) # noqa E501 + + def test_call(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_f = ir.FunctionType(flt, (int32, int32)) + tp_g = ir.FunctionType(dbl, (int32,), var_arg=True) + tp_h = ir.FunctionType(hlf, (int32, int32)) + f = ir.Function(builder.function.module, tp_f, 'f') + g = ir.Function(builder.function.module, tp_g, 'g') + h = ir.Function(builder.function.module, tp_h, 'h') + builder.call(f, (a, b), 'res_f') + builder.call(g, (b, a), 'res_g') + builder.call(h, (a, b), 'res_h') + builder.call(f, (a, b), 'res_f_fast', cconv='fastcc') + res_f_readonly = builder.call(f, (a, b), 'res_f_readonly') + res_f_readonly.attributes.add('readonly') + builder.call(f, (a, b), 'res_fast', fastmath='fast') + builder.call(f, (a, b), 'res_nnan_ninf', fastmath=('nnan', 'ninf')) + builder.call(f, (a, b), 'res_noinline', attrs='noinline') + builder.call(f, (a, b), 'res_alwaysinline', attrs='alwaysinline') + builder.call(f, (a, b), 'res_noinline_ro', attrs=('noinline', + 'readonly')) + builder.call(f, (a, b), 'res_convergent', attrs='convergent') + self.check_block(block, """\ + my_block: + %"res_f" = call float @"f"(i32 %".1", i32 %".2") + %"res_g" = call double (i32, ...) @"g"(i32 %".2", i32 %".1") + %"res_h" = call half @"h"(i32 %".1", i32 %".2") + %"res_f_fast" = call fastcc float @"f"(i32 %".1", i32 %".2") + %"res_f_readonly" = call float @"f"(i32 %".1", i32 %".2") readonly + %"res_fast" = call fast float @"f"(i32 %".1", i32 %".2") + %"res_nnan_ninf" = call ninf nnan float @"f"(i32 %".1", i32 %".2") + %"res_noinline" = call float @"f"(i32 %".1", i32 %".2") noinline + %"res_alwaysinline" = call float @"f"(i32 %".1", i32 %".2") alwaysinline + %"res_noinline_ro" = call float @"f"(i32 %".1", i32 %".2") noinline readonly + %"res_convergent" = call float @"f"(i32 %".1", i32 %".2") convergent + """) # noqa E501 + + def test_call_metadata(self): + """ + Function calls with metadata arguments. + """ + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + dbg_declare_ty = ir.FunctionType(ir.VoidType(), [ir.MetaDataType()] * 3) + dbg_declare = ir.Function( + builder.module, + dbg_declare_ty, + 'llvm.dbg.declare') + a = builder.alloca(int32, name="a") + b = builder.module.add_metadata(()) + builder.call(dbg_declare, (a, b, b)) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"a" = alloca i32 + call void @"llvm.dbg.declare"(metadata ptr %"a", metadata !0, metadata !0) + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"a" = alloca i32 + call void @"llvm.dbg.declare"(metadata i32* %"a", metadata !0, metadata !0) + """) # noqa E501 + + def test_call_attributes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType( + ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer())) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + fun.args[0].add_attribute('sret') + retval = builder.alloca(int32, name='retval') + other = builder.alloca(int32, name='other') + builder.call( + fun, + (retval, ir.Constant(int32, 42), other), + arg_attrs={ + 0: ('sret', 'noalias'), + 2: 'noalias' + } + ) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + call void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\) + """) # noqa E501 + else: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + call void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\) + """) # noqa E501 + + def test_call_tail(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType(ir.VoidType(), ()) + fun = ir.Function(builder.function.module, fun_ty, 'my_fun') + + builder.call(fun, ()) + builder.call(fun, (), tail=False) + builder.call(fun, (), tail=True) + builder.call(fun, (), tail='tail') + builder.call(fun, (), tail='notail') + builder.call(fun, (), tail='musttail') + builder.call(fun, (), tail=[]) # This is a falsy value + builder.call(fun, (), tail='not a marker') # This is a truthy value + + self.check_block(block, """\ + my_block: + call void @"my_fun"() + call void @"my_fun"() + tail call void @"my_fun"() + tail call void @"my_fun"() + notail call void @"my_fun"() + musttail call void @"my_fun"() + call void @"my_fun"() + tail call void @"my_fun"() + """) # noqa E501 + + def test_invalid_call_attributes(self): + block = self.block() + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType(ir.VoidType(), ()) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + with self.assertRaises(ValueError): + # The function has no arguments, so this should fail. + builder.call(fun, (), arg_attrs={0: 'sret'}) + + def test_invoke(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_f = ir.FunctionType(flt, (int32, int32)) + f = ir.Function(builder.function.module, tp_f, 'f') + bb_normal = builder.function.append_basic_block(name='normal') + bb_unwind = builder.function.append_basic_block(name='unwind') + builder.invoke(f, (a, b), bb_normal, bb_unwind, 'res_f') + self.check_block(block, """\ + my_block: + %"res_f" = invoke float @"f"(i32 %".1", i32 %".2") + to label %"normal" unwind label %"unwind" + """) + + def test_invoke_attributes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType( + ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer())) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + fun.calling_convention = "fastcc" + fun.args[0].add_attribute('sret') + retval = builder.alloca(int32, name='retval') + other = builder.alloca(int32, name='other') + bb_normal = builder.function.append_basic_block(name='normal') + bb_unwind = builder.function.append_basic_block(name='unwind') + builder.invoke( + fun, + (retval, ir.Constant(int32, 42), other), + bb_normal, + bb_unwind, + cconv='fastcc', + fastmath='fast', + attrs='noinline', + arg_attrs={ + 0: ('sret', 'noalias'), + 2: 'noalias' + } + ) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + invoke fast fastcc void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\) noinline + to label %"normal" unwind label %"unwind" + """) # noqa E501 + else: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + invoke fast fastcc void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\) noinline + to label %"normal" unwind label %"unwind" + """) # noqa E501 + + def test_landingpad(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + lp = builder.landingpad(ir.LiteralStructType([int32, + int8.as_pointer()]), 'lp') + int_typeinfo = ir.GlobalVariable(builder.function.module, + int8.as_pointer(), "_ZTIi") + int_typeinfo.global_constant = True + lp.add_clause(ir.CatchClause(int_typeinfo)) + lp.add_clause(ir.FilterClause(ir.Constant(ir.ArrayType( + int_typeinfo.type, 1), [int_typeinfo]))) + builder.resume(lp) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"lp" = landingpad {i32, ptr} + catch ptr @"_ZTIi" + filter [1 x ptr] [ptr @"_ZTIi"] + resume {i32, ptr} %"lp" + """) + else: + self.check_block(block, """\ + my_block: + %"lp" = landingpad {i32, i8*} + catch i8** @"_ZTIi" + filter [1 x i8**] [i8** @"_ZTIi"] + resume {i32, i8*} %"lp" + """) + + def test_assume(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.icmp_signed('>', a, b, name='c') + builder.assume(c) + self.check_block(block, """\ + my_block: + %"c" = icmp sgt i32 %".1", %".2" + call void @"llvm.assume"(i1 %"c") + """) + + def test_vector_ops(self): + block = self.block(name='insert_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + a.name = 'a' + b.name = 'b' + + vecty = ir.VectorType(a.type, 2) + vec = ir.Constant(vecty, ir.Undefined) + idxty = ir.IntType(32) + vec = builder.insert_element(vec, a, idxty(0), name='vec1') + vec = builder.insert_element(vec, b, idxty(1), name='vec2') + + self.check_block(block, """\ +insert_block: + %"vec1" = insertelement <2 x i32> , i32 %"a", i32 0 + %"vec2" = insertelement <2 x i32> %"vec1", i32 %"b", i32 1 + """) + + block = builder.append_basic_block("shuffle_block") + builder.branch(block) + builder.position_at_end(block) + + mask = ir.Constant(vecty, [1, 0]) + builder.shuffle_vector(vec, vec, mask, name='shuf') + + self.check_block(block, """\ + shuffle_block: + %"shuf" = shufflevector <2 x i32> %"vec2", <2 x i32> %"vec2", <2 x i32> + """) # noqa E501 + + block = builder.append_basic_block("add_block") + builder.branch(block) + builder.position_at_end(block) + + builder.add(vec, vec, name='sum') + + self.check_block(block, """\ + add_block: + %"sum" = add <2 x i32> %"vec2", %"vec2" + """) + + block = builder.append_basic_block("extract_block") + builder.branch(block) + builder.position_at_end(block) + + c = builder.extract_element(vec, idxty(0), name='ex1') + d = builder.extract_element(vec, idxty(1), name='ex2') + + self.check_block(block, """\ + extract_block: + %"ex1" = extractelement <2 x i32> %"vec2", i32 0 + %"ex2" = extractelement <2 x i32> %"vec2", i32 1 + """) + + builder.ret(builder.add(c, d)) + self.assert_valid_ir(builder.module) + + def test_bitreverse(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + c = builder.bitreverse(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i64 @"llvm.bitreverse.i64"(i64 5) + ret i64 %"c" + """) + + def test_bitreverse_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + + with self.assertRaises(TypeError) as raises: + builder.bitreverse(a, name='c') + self.assertIn( + "expected an integer type, got float", + str(raises.exception)) + + def test_fence(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + with self.assertRaises(ValueError) as raises: + builder.fence("monotonic", None) + self.assertIn( + "Invalid fence ordering \"monotonic\"!", + str(raises.exception)) + with self.assertRaises(ValueError) as raises: + builder.fence(None, "monotonic") + self.assertIn( + "Invalid fence ordering \"None\"!", + str(raises.exception)) + builder.fence("acquire", None) + builder.fence("release", "singlethread") + builder.fence("acq_rel", "singlethread") + builder.fence("seq_cst") + builder.ret_void() + self.check_block(block, """\ + my_block: + fence acquire + fence syncscope("singlethread") release + fence syncscope("singlethread") acq_rel + fence seq_cst + ret void + """) + + def test_comment(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + with self.assertRaises(AssertionError): + builder.comment("so\nmany lines") + builder.comment("my comment") + builder.ret_void() + self.check_block(block, """\ + my_block: + ; my comment + ret void + """) + + def test_bswap(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int32, 5) + c = builder.bswap(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i32 @"llvm.bswap.i32"(i32 5) + ret i32 %"c" + """) + + def test_ctpop(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + c = builder.ctpop(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i16 @"llvm.ctpop.i16"(i16 5) + ret i16 %"c" + """) + + def test_ctlz(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + b = ir.Constant(int1, 1) + c = builder.ctlz(a, b, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i16 @"llvm.ctlz.i16"(i16 5, i1 1) + ret i16 %"c" + """) + + def test_convert_to_fp16_f32(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.0) + b = builder.convert_to_fp16(a, name='b') + builder.ret(b) + self.check_block(block, """\ + my_block: + %"b" = call i16 @"llvm.convert.to.fp16.f32"(float 0x4014000000000000) + ret i16 %"b" + """) # noqa E501 + + def test_convert_to_fp16_f32_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + + with self.assertRaises(TypeError) as raises: + builder.convert_to_fp16(a, name='b') + self.assertIn( + "expected a float type, got i16", + str(raises.exception)) + + def test_convert_from_fp16_f32(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + b = builder.convert_from_fp16(a, name='b', to=flt) + builder.ret(b) + self.check_block(block, """\ + my_block: + %"b" = call float @"llvm.convert.from.fp16.f32"(i16 5) + ret float %"b" + """) + + def test_convert_from_fp16_f32_notype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b') + self.assertIn( + "expected a float return type", + str(raises.exception)) + + def test_convert_from_fp16_f32_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b', to=flt) + self.assertIn( + "expected an i16 type, got float", + str(raises.exception)) + + def test_convert_from_fp16_f32_wrongtype2(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b', to=int16) + self.assertIn( + "expected a float type, got i16", + str(raises.exception)) + + def test_cttz(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + b = ir.Constant(int1, 1) + c = builder.cttz(a, b, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i64 @"llvm.cttz.i64"(i64 5, i1 1) + ret i64 %"c" + """) + + def test_cttz_wrongflag(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + b = ir.Constant(int32, 3) + + with self.assertRaises(TypeError) as raises: + builder.cttz(a, b, name='c') + self.assertIn( + "expected an i1 type, got i32", + str(raises.exception)) + + def test_cttz_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(int1, 1) + + with self.assertRaises(TypeError) as raises: + builder.cttz(a, b, name='c') + self.assertIn( + "expected an integer type, got float", + str(raises.exception)) + + def test_fma(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(flt, 1) + c = ir.Constant(flt, 2) + fma = builder.fma(a, b, c, name='fma') + builder.ret(fma) + self.check_block(block, """\ + my_block: + %"fma" = call float @"llvm.fma.f32"(float 0x4014000000000000, float 0x3ff0000000000000, float 0x4000000000000000) + ret float %"fma" + """) # noqa E501 + + def test_fma_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int32, 5) + b = ir.Constant(int32, 1) + c = ir.Constant(int32, 2) + + with self.assertRaises(TypeError) as raises: + builder.fma(a, b, c, name='fma') + self.assertIn( + "expected an floating point type, got i32", + str(raises.exception)) + + def test_fma_mixedtypes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(dbl, 1) + c = ir.Constant(flt, 2) + + with self.assertRaises(TypeError) as raises: + builder.fma(a, b, c, name='fma') + self.assertIn( + "expected types to be the same, got float, double, float", + str(raises.exception)) + + def test_arg_attributes(self): + def gen_code(attr_name): + fnty = ir.FunctionType(ir.IntType(32), [ir.IntType(32).as_pointer(), + ir.IntType(32)]) + module = ir.Module() + + func = ir.Function(module, fnty, name="sum") + + bb_entry = func.append_basic_block() + bb_loop = func.append_basic_block() + bb_exit = func.append_basic_block() + + builder = ir.IRBuilder() + builder.position_at_end(bb_entry) + + builder.branch(bb_loop) + builder.position_at_end(bb_loop) + + index = builder.phi(ir.IntType(32)) + index.add_incoming(ir.Constant(index.type, 0), bb_entry) + accum = builder.phi(ir.IntType(32)) + accum.add_incoming(ir.Constant(accum.type, 0), bb_entry) + + func.args[0].add_attribute(attr_name) + ptr = builder.gep(func.args[0], [index]) + value = builder.load(ptr) + + added = builder.add(accum, value) + accum.add_incoming(added, bb_loop) + + indexp1 = builder.add(index, ir.Constant(index.type, 1)) + index.add_incoming(indexp1, bb_loop) + + cond = builder.icmp_unsigned('<', indexp1, func.args[1]) + builder.cbranch(cond, bb_loop, bb_exit) + + builder.position_at_end(bb_exit) + builder.ret(added) + + return str(module) + + for attr_name in ( + 'byref', + 'byval', + 'elementtype', + 'immarg', + 'inalloca', + 'inreg', + 'nest', + 'noalias', + 'nocapture', + 'nofree', + 'nonnull', + 'noundef', + 'preallocated', + 'returned', + 'signext', + 'swiftasync', + 'swifterror', + 'swiftself', + 'zeroext', + ): + # If this parses, we emitted the right byval attribute format + llvm.parse_assembly(gen_code(attr_name)) + # sret doesn't fit this pattern and is tested in test_call_attributes + + +class TestBuilderMisc(TestBase): + """ + Test various other features of the IRBuilder class. + """ + + def test_attributes(self): + block = self.block(name='start') + builder = ir.IRBuilder(block) + self.assertIs(builder.function, block.parent) + self.assertIsInstance(builder.function, ir.Function) + self.assertIs(builder.module, block.parent.module) + self.assertIsInstance(builder.module, ir.Module) + + def test_goto_block(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.add(a, b, 'c') + bb_new = builder.append_basic_block(name='foo') + with builder.goto_block(bb_new): + builder.fadd(a, b, 'd') + with builder.goto_entry_block(): + builder.sub(a, b, 'e') + builder.fsub(a, b, 'f') + builder.branch(bb_new) + builder.mul(a, b, 'g') + with builder.goto_block(bb_new): + builder.fmul(a, b, 'h') + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"e" = sub i32 %".1", %".2" + %"g" = mul i32 %".1", %".2" + """) + self.check_block(bb_new, """\ + foo: + %"d" = fadd i32 %".1", %".2" + %"f" = fsub i32 %".1", %".2" + %"h" = fmul i32 %".1", %".2" + br label %"foo" + """) + + def test_if_then(self): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a) as bbend: + builder.add(z, z, 'b') + # Block will be terminated implicitly + self.assertIs(builder.block, bbend) + c = builder.add(z, z, 'c') + with builder.if_then(c): + builder.add(z, z, 'd') + builder.branch(block) + # No implicit termination + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.endif" + one.if: + %"b" = add i1 0, 0 + br label %"one.endif" + one.endif: + %"c" = add i1 0, 0 + br i1 %"c", label %"one.endif.if", label %"one.endif.endif" + one.endif.if: + %"d" = add i1 0, 0 + br label %"one" + one.endif.endif: + """) + + def test_if_then_nested(self): + # Implicit termination in a nested if/then + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a): + b = builder.add(z, z, 'b') + with builder.if_then(b): + builder.add(z, z, 'c') + builder.ret_void() + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.endif" + one.if: + %"b" = add i1 0, 0 + br i1 %"b", label %"one.if.if", label %"one.if.endif" + one.endif: + ret void + one.if.if: + %"c" = add i1 0, 0 + br label %"one.if.endif" + one.if.endif: + br label %"one.endif" + """) + + def test_if_then_long_label(self): + full_label = 'Long' * 20 + block = self.block(name=full_label) + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a): + b = builder.add(z, z, 'b') + with builder.if_then(b): + builder.add(z, z, 'c') + builder.ret_void() + self.check_func_body(builder.function, """\ + {full_label}: + %"a" = add i1 0, 0 + br i1 %"a", label %"{label}.if", label %"{label}.endif" + {label}.if: + %"b" = add i1 0, 0 + br i1 %"b", label %"{label}.if.if", label %"{label}.if.endif" + {label}.endif: + ret void + {label}.if.if: + %"c" = add i1 0, 0 + br label %"{label}.if.endif" + {label}.if.endif: + br label %"{label}.endif" + """.format(full_label=full_label, label=full_label[:25] + '..')) + + def test_if_then_likely(self): + def check(likely): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + with builder.if_then(z, likely=likely): + pass + self.check_block(block, """\ + one: + br i1 0, label %"one.if", label %"one.endif", !prof !0 + """) + return builder + builder = check(True) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 99, i32 1 } + """) + builder = check(False) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 1, i32 99 } + """) + + def test_if_else(self): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_else(a) as (then, otherwise): + with then: + builder.add(z, z, 'b') + with otherwise: + builder.add(z, z, 'c') + # Each block will be terminated implicitly + with builder.if_else(a) as (then, otherwise): + with then: + builder.branch(block) + with otherwise: + builder.ret_void() + # No implicit termination + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.else" + one.if: + %"b" = add i1 0, 0 + br label %"one.endif" + one.else: + %"c" = add i1 0, 0 + br label %"one.endif" + one.endif: + br i1 %"a", label %"one.endif.if", label %"one.endif.else" + one.endif.if: + br label %"one" + one.endif.else: + ret void + one.endif.endif: + """) + + def test_if_else_likely(self): + def check(likely): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + with builder.if_else(z, likely=likely) as (then, otherwise): + with then: + builder.branch(block) + with otherwise: + builder.ret_void() + self.check_func_body(builder.function, """\ + one: + br i1 0, label %"one.if", label %"one.else", !prof !0 + one.if: + br label %"one" + one.else: + ret void + one.endif: + """) + return builder + builder = check(True) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 99, i32 1 } + """) + builder = check(False) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 1, i32 99 } + """) + + def test_positioning(self): + """ + Test IRBuilder.position_{before,after,at_start,at_end}. + """ + func = self.function() + builder = ir.IRBuilder() + z = ir.Constant(int32, 0) + bb_one = func.append_basic_block(name='one') + bb_two = func.append_basic_block(name='two') + bb_three = func.append_basic_block(name='three') + # .at_start(empty block) + builder.position_at_start(bb_one) + builder.add(z, z, 'a') + # .at_end(empty block) + builder.position_at_end(bb_two) + builder.add(z, z, 'm') + builder.add(z, z, 'n') + # .at_start(block) + builder.position_at_start(bb_two) + o = builder.add(z, z, 'o') + builder.add(z, z, 'p') + # .at_end(block) + builder.position_at_end(bb_one) + b = builder.add(z, z, 'b') + # .after(instr) + builder.position_after(o) + builder.add(z, z, 'q') + # .before(instr) + builder.position_before(b) + builder.add(z, z, 'c') + self.check_block(bb_one, """\ + one: + %"a" = add i32 0, 0 + %"c" = add i32 0, 0 + %"b" = add i32 0, 0 + """) + self.check_block(bb_two, """\ + two: + %"o" = add i32 0, 0 + %"q" = add i32 0, 0 + %"p" = add i32 0, 0 + %"m" = add i32 0, 0 + %"n" = add i32 0, 0 + """) + self.check_block(bb_three, """\ + three: + """) + + def test_instruction_removal(self): + func = self.function() + builder = ir.IRBuilder() + blk = func.append_basic_block(name='entry') + builder.position_at_end(blk) + k = ir.Constant(int32, 1234) + a = builder.add(k, k, 'a') + retvoid = builder.ret_void() + self.assertTrue(blk.is_terminated) + builder.remove(retvoid) + self.assertFalse(blk.is_terminated) + b = builder.mul(a, a, 'b') + c = builder.add(b, b, 'c') + builder.remove(c) + builder.ret_void() + self.assertTrue(blk.is_terminated) + self.check_block(blk, """\ + entry: + %"a" = add i32 1234, 1234 + %"b" = mul i32 %"a", %"a" + ret void + """) + + def test_metadata(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + builder.debug_metadata = builder.module.add_metadata([]) + builder.alloca(ir.PointerType(int32), name='c') + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr, !dbg !0 + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32*, !dbg !0 + """) + + +class TestTypes(TestBase): + + def has_logical_equality(self, ty): + while isinstance(ty, ir.PointerType): + ty = ty.pointee + return not isinstance(ty, ir.LabelType) + + def assorted_types(self): + """ + A bunch of mutually unequal types + """ + # Avoid polluting the namespace + context = ir.Context() + types = [ + ir.LabelType(), ir.VoidType(), + ir.FunctionType(int1, (int8, int8)), ir.FunctionType(int1, (int8,)), + ir.FunctionType(int1, (int8,), var_arg=True), + ir.FunctionType(int8, (int8,)), + int1, int8, int32, flt, dbl, + ir.ArrayType(flt, 5), ir.ArrayType(dbl, 5), ir.ArrayType(dbl, 4), + ir.LiteralStructType((int1, int8)), ir.LiteralStructType((int8, + int1)), + context.get_identified_type("MyType1"), + context.get_identified_type("MyType2"), + ] + types += [ir.PointerType(tp) for tp in types + if not isinstance(tp, (ir.VoidType, ir.LabelType))] + + return types + + def test_pickling(self): + types = self.assorted_types() + for ty in types: + newty = self.assert_pickle_correctly(ty) + if self.has_logical_equality(ty): + self.assertEqual(newty, ty) + + def test_comparisons(self): + types = self.assorted_types() + for a, b in itertools.product(types, types): + if a is not b: + self.assertFalse(a == b, (a, b)) + self.assertTrue(a != b, (a, b)) + # We assume copy.copy() works fine here... + for tp in types: + other = copy.copy(tp) + if self.has_logical_equality(tp): + self.assertTrue(tp == other, (tp, other)) + self.assertFalse(tp != other, (tp, other)) + else: + self.assertFalse(tp == other, (tp, other)) + self.assertTrue(tp != other, (tp, other)) + + def test_str(self): + """ + Test the string representation of types. + """ + self.assertEqual(str(int1), 'i1') + self.assertEqual(str(ir.IntType(29)), 'i29') + self.assertEqual(str(flt), 'float') + self.assertEqual(str(dbl), 'double') + self.assertEqual(str(ir.VoidType()), 'void') + self.assertEqual(str(ir.FunctionType(int1, ())), 'i1 ()') + self.assertEqual(str(ir.FunctionType(int1, (flt,))), 'i1 (float)') + self.assertEqual(str(ir.FunctionType(int1, (flt, dbl))), + 'i1 (float, double)') + self.assertEqual(str(ir.FunctionType(int1, (), var_arg=True)), + 'i1 (...)') + self.assertEqual(str(ir.FunctionType(int1, (flt,), var_arg=True)), + 'i1 (float, ...)') + self.assertEqual(str(ir.FunctionType(int1, (flt, dbl), var_arg=True)), + 'i1 (float, double, ...)') + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(ir.PointerType(int32)), 'ptr') + self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), 'ptr') + else: + self.assertEqual(str(ir.PointerType(int32)), 'i32*') + self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), + 'i32**') + self.assertEqual(str(ir.ArrayType(int1, 5)), '[5 x i1]') + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)), + '[5 x ptr]') + self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))), 'ptr') + else: + self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)), + '[5 x i1*]') + self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))), + '[5 x i1]*') + self.assertEqual(str(ir.LiteralStructType((int1,))), '{i1}') + self.assertEqual(str(ir.LiteralStructType((int1, flt))), '{i1, float}') + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(ir.LiteralStructType(( + ir.PointerType(int1), ir.LiteralStructType((int32, int8))))), + '{ptr, {i32, i8}}') + else: + self.assertEqual(str(ir.LiteralStructType(( + ir.PointerType(int1), ir.LiteralStructType((int32, int8))))), + '{i1*, {i32, i8}}') + self.assertEqual(str(ir.LiteralStructType((int1,), packed=True)), + '<{i1}>') + self.assertEqual(str(ir.LiteralStructType((int1, flt), packed=True)), + '<{i1, float}>') + + # Avoid polluting the namespace + context = ir.Context() + mytype = context.get_identified_type("MyType") + self.assertEqual(str(mytype), "%\"MyType\"") + mytype1 = context.get_identified_type("MyType\\") + self.assertEqual(str(mytype1), "%\"MyType\\5c\"") + mytype2 = context.get_identified_type("MyType\"") + self.assertEqual(str(mytype2), "%\"MyType\\22\"") + + def test_hash(self): + for typ in filter(self.has_logical_equality, self.assorted_types()): + self.assertEqual(hash(typ), hash(copy.copy(typ))) + + def test_gep(self): + def check_constant(tp, i, expected): + actual = tp.gep(ir.Constant(int32, i)) + self.assertEqual(actual, expected) + + def check_index_type(tp): + index = ir.Constant(dbl, 1.0) + with self.assertRaises(TypeError): + tp.gep(index) + + tp = ir.PointerType(dbl) + for i in range(5): + check_constant(tp, i, dbl) + check_index_type(tp) + + tp = ir.ArrayType(int1, 3) + for i in range(3): + check_constant(tp, i, int1) + check_index_type(tp) + + tp = ir.LiteralStructType((dbl, ir.LiteralStructType((int1, int8)))) + check_constant(tp, 0, dbl) + check_constant(tp, 1, ir.LiteralStructType((int1, int8))) + with self.assertRaises(IndexError): + tp.gep(ir.Constant(int32, 2)) + check_index_type(tp) + + context = ir.Context() + tp = ir.IdentifiedStructType(context, "MyType") + tp.set_body(dbl, ir.LiteralStructType((int1, int8))) + check_constant(tp, 0, dbl) + check_constant(tp, 1, ir.LiteralStructType((int1, int8))) + with self.assertRaises(IndexError): + tp.gep(ir.Constant(int32, 2)) + check_index_type(tp) + + def test_abi_size(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def check(tp, expected): + self.assertEqual(tp.get_abi_size(td), expected) + check(int8, 1) + check(int32, 4) + check(int64, 8) + check(ir.ArrayType(int8, 5), 5) + check(ir.ArrayType(int32, 5), 20) + check(ir.LiteralStructType((dbl, flt, flt)), 16) + + def test_abi_alignment(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def check(tp, expected): + self.assertIn(tp.get_abi_alignment(td), expected) + check(int8, (1, 2, 4)) + check(int32, (4,)) + check(int64, (8,)) + check(ir.ArrayType(int8, 5), (1, 2, 4)) + check(ir.ArrayType(int32, 5), (4,)) + check(ir.LiteralStructType((dbl, flt, flt)), (8,)) + + def test_identified_struct(self): + context = ir.Context() + mytype = context.get_identified_type("MyType") + module = ir.Module(context=context) + self.assertTrue(mytype.is_opaque) + self.assert_valid_ir(module) + oldstr = str(module) + mytype.set_body(ir.IntType(32), ir.IntType(64), ir.FloatType()) + self.assertFalse(mytype.is_opaque) + self.assert_valid_ir(module) + self.assertNotEqual(oldstr, str(module)) + + def test_identified_struct_packed(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + context = ir.Context() + mytype = context.get_identified_type("MyType", True) + module = ir.Module(context=context) + self.assertTrue(mytype.is_opaque) + self.assert_valid_ir(module) + oldstr = str(module) + mytype.set_body(ir.IntType(16), ir.IntType(64), ir.FloatType()) + self.assertEqual(mytype.get_element_offset(td, 1, context), 2) + self.assertFalse(mytype.is_opaque) + self.assert_valid_ir(module) + self.assertNotEqual(oldstr, str(module)) + + def test_target_data_non_default_context(self): + context = ir.Context() + mytype = context.get_identified_type("MyType") + mytype.elements = [ir.IntType(32)] + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + self.assertEqual(mytype.get_abi_size(td, context=context), 4) + + def test_vector(self): + vecty = ir.VectorType(ir.IntType(32), 8) + self.assertEqual(str(vecty), "<8 x i32>") + + +def c32(i): + return ir.Constant(int32, i) + + +class TestConstant(TestBase): + + def test_integers(self): + c = ir.Constant(int32, 42) + self.assertEqual(str(c), 'i32 42') + c = ir.Constant(int1, 1) + self.assertEqual(str(c), 'i1 1') + c = ir.Constant(int1, 0) + self.assertEqual(str(c), 'i1 0') + c = ir.Constant(int1, True) + self.assertEqual(str(c), 'i1 true') + c = ir.Constant(int1, False) + self.assertEqual(str(c), 'i1 false') + c = ir.Constant(int1, ir.Undefined) + self.assertEqual(str(c), 'i1 undef') + c = ir.Constant(int1, None) + self.assertEqual(str(c), 'i1 0') + + def test_reals(self): + # XXX Test NaNs and infs + c = ir.Constant(flt, 1.5) + self.assertEqual(str(c), 'float 0x3ff8000000000000') + c = ir.Constant(flt, -1.5) + self.assertEqual(str(c), 'float 0xbff8000000000000') + c = ir.Constant(dbl, 1.5) + self.assertEqual(str(c), 'double 0x3ff8000000000000') + c = ir.Constant(dbl, -1.5) + self.assertEqual(str(c), 'double 0xbff8000000000000') + c = ir.Constant(dbl, ir.Undefined) + self.assertEqual(str(c), 'double undef') + c = ir.Constant(dbl, None) + self.assertEqual(str(c), 'double 0.0') + + def test_arrays(self): + c = ir.Constant(ir.ArrayType(int32, 3), (c32(5), c32(6), c32(4))) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 4]') + c = ir.Constant(ir.ArrayType(int32, 2), (c32(5), c32(ir.Undefined))) + self.assertEqual(str(c), '[2 x i32] [i32 5, i32 undef]') + + c = ir.Constant.literal_array((c32(5), c32(6), c32(ir.Undefined))) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 undef]') + with self.assertRaises(TypeError) as raises: + ir.Constant.literal_array((c32(5), ir.Constant(flt, 1.5))) + self.assertEqual(str(raises.exception), + "all elements must have the same type") + + c = ir.Constant(ir.ArrayType(int32, 2), ir.Undefined) + self.assertEqual(str(c), '[2 x i32] undef') + c = ir.Constant(ir.ArrayType(int32, 2), None) + self.assertEqual(str(c), '[2 x i32] zeroinitializer') + # Raw array syntax + c = ir.Constant(ir.ArrayType(int8, 11), bytearray(b"foobar_123\x80")) + self.assertEqual(str(c), r'[11 x i8] c"foobar_123\80"') + c = ir.Constant(ir.ArrayType(int8, 4), bytearray(b"\x00\x01\x04\xff")) + self.assertEqual(str(c), r'[4 x i8] c"\00\01\04\ff"') + # Recursive instantiation of inner constants + c = ir.Constant(ir.ArrayType(int32, 3), (5, ir.Undefined, 6)) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 undef, i32 6]') + # Invalid number of args + with self.assertRaises(ValueError): + ir.Constant(ir.ArrayType(int32, 3), (5, 6)) + + def test_vector(self): + vecty = ir.VectorType(ir.IntType(32), 8) + vals = [1, 2, 4, 3, 8, 6, 9, 7] + vec = ir.Constant(vecty, vals) + vec_repr = "<8 x i32> <{}>".format( + ', '.join(map('i32 {}'.format, vals))) + self.assertEqual(str(vec), vec_repr) + + def test_non_nullable_int(self): + constant = ir.Constant(ir.IntType(32), None).constant + self.assertEqual(constant, 0) + + def test_structs(self): + st1 = ir.LiteralStructType((flt, int1)) + st2 = ir.LiteralStructType((int32, st1)) + c = ir.Constant(st1, (ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, True))) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, True))) + self.assertEqual(c.type, st1) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, ir.Undefined))) + self.assertEqual(c.type, st1) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 undef}') + c = ir.Constant(st1, ir.Undefined) + self.assertEqual(str(c), '{float, i1} undef') + c = ir.Constant(st1, None) + self.assertEqual(str(c), '{float, i1} zeroinitializer') + # Recursive instantiation of inner constants + c1 = ir.Constant(st1, (1.5, True)) + self.assertEqual(str(c1), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c2 = ir.Constant(st2, (42, c1)) + self.assertEqual(str(c2), ('{i32, {float, i1}} {i32 42, {float, i1} ' + '{float 0x3ff8000000000000, i1 true}}')) + c3 = ir.Constant(st2, (42, (1.5, True))) + self.assertEqual(str(c3), str(c2)) + # Invalid number of args + with self.assertRaises(ValueError): + ir.Constant(st2, (4, 5, 6)) + + def test_undefined_literal_struct_pickling(self): + i8 = ir.IntType(8) + st = ir.Constant(ir.LiteralStructType([i8, i8]), ir.Undefined) + self.assert_pickle_correctly(st) + + def test_type_instantiaton(self): + """ + Instantiating a type should create a constant. + """ + c = int8(42) + self.assertIsInstance(c, ir.Constant) + self.assertEqual(str(c), 'i8 42') + c = int1(True) + self.assertIsInstance(c, ir.Constant) + self.assertEqual(str(c), 'i1 true') + # Arrays + at = ir.ArrayType(int32, 3) + c = at([c32(4), c32(5), c32(6)]) + self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]') + c = at([4, 5, 6]) + self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]') + c = at(None) + self.assertEqual(str(c), '[3 x i32] zeroinitializer') + with self.assertRaises(ValueError): + at([4, 5, 6, 7]) + # Structs + st1 = ir.LiteralStructType((flt, int1)) + st2 = ir.LiteralStructType((int32, st1)) + c = st1((1.5, True)) + self.assertEqual(str(c), ('{float, i1} {float 0x3ff8000000000000, i1 ' + 'true}')) + c = st2((42, (1.5, True))) + self.assertEqual(str(c), ('{i32, {float, i1}} {i32 42, {float, i1} ' + '{float 0x3ff8000000000000, i1 true}}')) + + def test_repr(self): + """ + Constants should have a useful repr(). + """ + c = int32(42) + self.assertEqual(repr(c), "") + + def test_encoding_problem(self): + c = ir.Constant(ir.ArrayType(ir.IntType(8), 256), + bytearray(range(256))) + m = self.module() + gv = ir.GlobalVariable(m, c.type, "myconstant") + gv.global_constant = True + gv.initializer = c + # With utf-8, the following will cause: + # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position + # 136: invalid continuation byte + parsed = llvm.parse_assembly(str(m)) + # Make sure the encoding does not modify the IR + reparsed = llvm.parse_assembly(str(parsed)) + self.assertEqual(str(parsed), str(reparsed)) + + def test_gep(self): + m = self.module() + tp = ir.LiteralStructType((flt, int1)) + gv = ir.GlobalVariable(m, tp, "myconstant") + c = gv.gep([ir.Constant(int32, x) for x in (0, 1)]) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), + 'getelementptr ({float, i1}, ptr @"myconstant", i32 0, i32 1)') # noqa E501 + else: + self.assertEqual(str(c), + 'getelementptr ({float, i1}, {float, i1}* @"myconstant", i32 0, i32 1)') # noqa E501 + self.assertEqual(c.type, ir.PointerType(int1)) + + const = ir.Constant(tp, None) + with self.assertRaises(TypeError): + const.gep([ir.Constant(int32, 0)]) + + const_ptr = ir.Constant(tp.as_pointer(), None) + c2 = const_ptr.gep([ir.Constant(int32, 0)]) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c2), + 'getelementptr ({float, i1}, ptr null, i32 0)') # noqa E501 + else: + self.assertEqual(str(c2), + 'getelementptr ({float, i1}, {float, i1}* null, i32 0)') # noqa E501 + self.assertEqual(c.type, ir.PointerType(int1)) + + def test_gep_addrspace_globalvar(self): + m = self.module() + tp = ir.LiteralStructType((flt, int1)) + addrspace = 4 + + gv = ir.GlobalVariable(m, tp, "myconstant", addrspace=addrspace) + self.assertEqual(gv.addrspace, addrspace) + c = gv.gep([ir.Constant(int32, x) for x in (0, 1)]) + self.assertEqual(c.type.addrspace, addrspace) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), + ('getelementptr ({float, i1}, ptr ' + 'addrspace(4) @"myconstant", i32 0, i32 1)')) + else: + self.assertEqual(str(c), + ('getelementptr ({float, i1}, {float, i1} ' + 'addrspace(4)* @"myconstant", i32 0, i32 1)')) + self.assertEqual(c.type, ir.PointerType(int1, addrspace=addrspace)) + + def test_trunc(self): + c = ir.Constant(int64, 1).trunc(int32) + self.assertEqual(str(c), 'trunc (i64 1 to i32)') + + def test_zext(self): + c = ir.Constant(int32, 1).zext(int64) + self.assertEqual(str(c), 'zext (i32 1 to i64)') + + def test_sext(self): + c = ir.Constant(int32, -1).sext(int64) + self.assertEqual(str(c), 'sext (i32 -1 to i64)') + + def test_fptrunc(self): + c = ir.Constant(flt, 1).fptrunc(hlf) + self.assertEqual(str(c), 'fptrunc (float 0x3ff0000000000000 to half)') + + def test_fpext(self): + c = ir.Constant(flt, 1).fpext(dbl) + self.assertEqual(str(c), 'fpext (float 0x3ff0000000000000 to double)') + + def test_bitcast(self): + m = self.module() + gv = ir.GlobalVariable(m, int32, "myconstant") + c = gv.bitcast(int64.as_pointer()) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), 'bitcast (ptr @"myconstant" to ptr)') + else: + self.assertEqual(str(c), 'bitcast (i32* @"myconstant" to i64*)') + + def test_fptoui(self): + c = ir.Constant(flt, 1).fptoui(int32) + self.assertEqual(str(c), 'fptoui (float 0x3ff0000000000000 to i32)') + + def test_uitofp(self): + c = ir.Constant(int32, 1).uitofp(flt) + self.assertEqual(str(c), 'uitofp (i32 1 to float)') + + def test_fptosi(self): + c = ir.Constant(flt, 1).fptosi(int32) + self.assertEqual(str(c), 'fptosi (float 0x3ff0000000000000 to i32)') + + def test_sitofp(self): + c = ir.Constant(int32, 1).sitofp(flt) + self.assertEqual(str(c), 'sitofp (i32 1 to float)') + + def test_ptrtoint_1(self): + ptr = ir.Constant(int64.as_pointer(), None) + one = ir.Constant(int32, 1) + c = ptr.ptrtoint(int32) + + self.assertRaises(TypeError, one.ptrtoint, int64) + self.assertRaises(TypeError, ptr.ptrtoint, flt) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), 'ptrtoint (ptr null to i32)') + else: + self.assertEqual(str(c), 'ptrtoint (i64* null to i32)') + + def test_ptrtoint_2(self): + m = self.module() + gv = ir.GlobalVariable(m, int32, "myconstant") + c = gv.ptrtoint(int64) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), 'ptrtoint (ptr @"myconstant" to i64)') + + self.assertRaisesRegex( + TypeError, + r"can only ptrtoint\(\) to integer type, not 'ptr'", + gv.ptrtoint, + int64.as_pointer()) + else: + self.assertEqual(str(c), 'ptrtoint (i32* @"myconstant" to i64)') + + self.assertRaisesRegex( + TypeError, + r"can only ptrtoint\(\) to integer type, not 'i64\*'", + gv.ptrtoint, + int64.as_pointer()) + + c2 = ir.Constant(int32, 0) + self.assertRaisesRegex( + TypeError, + r"can only call ptrtoint\(\) on pointer type, not 'i32'", + c2.ptrtoint, + int64) + + def test_inttoptr(self): + one = ir.Constant(int32, 1) + pi = ir.Constant(flt, 3.14) + c = one.inttoptr(int64.as_pointer()) + + self.assertRaises(TypeError, one.inttoptr, int64) + self.assertRaises(TypeError, pi.inttoptr, int64.as_pointer()) + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertEqual(str(c), 'inttoptr (i32 1 to ptr)') + else: + self.assertEqual(str(c), 'inttoptr (i32 1 to i64*)') + + def test_neg(self): + one = ir.Constant(int32, 1) + self.assertEqual(str(one.neg()), 'sub (i32 0, i32 1)') + + def test_not(self): + one = ir.Constant(int32, 1) + self.assertEqual(str(one.not_()), 'xor (i32 1, i32 -1)') + + def test_fneg(self): + one = ir.Constant(flt, 1) + self.assertEqual(str(one.fneg()), 'fneg (float 0x3ff0000000000000)') + + def test_int_binops(self): + one = ir.Constant(int32, 1) + two = ir.Constant(int32, 2) + + oracle = {one.shl: 'shl', one.lshr: 'lshr', one.ashr: 'ashr', + one.add: 'add', one.sub: 'sub', one.mul: 'mul', + one.udiv: 'udiv', one.sdiv: 'sdiv', one.urem: 'urem', + one.srem: 'srem', one.or_: 'or', one.and_: 'and', + one.xor: 'xor'} + for fn, irop in oracle.items(): + self.assertEqual(str(fn(two)), irop + ' (i32 1, i32 2)') + + # unsigned integer compare + oracle = {'==': 'eq', '!=': 'ne', '>': + 'ugt', '>=': 'uge', '<': 'ult', '<=': 'ule'} + for cop, cond in oracle.items(): + actual = str(one.icmp_unsigned(cop, two)) + expected = 'icmp ' + cond + ' (i32 1, i32 2)' + self.assertEqual(actual, expected) + + # signed integer compare + oracle = {'==': 'eq', '!=': 'ne', + '>': 'sgt', '>=': 'sge', '<': 'slt', '<=': 'sle'} + for cop, cond in oracle.items(): + actual = str(one.icmp_signed(cop, two)) + expected = 'icmp ' + cond + ' (i32 1, i32 2)' + self.assertEqual(actual, expected) + + def test_flt_binops(self): + one = ir.Constant(flt, 1) + two = ir.Constant(flt, 2) + + oracle = {one.fadd: 'fadd', one.fsub: 'fsub', one.fmul: 'fmul', + one.fdiv: 'fdiv', one.frem: 'frem'} + for fn, irop in oracle.items(): + actual = str(fn(two)) + expected = irop + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + # ordered float compare + oracle = {'==': 'oeq', '!=': 'one', '>': 'ogt', '>=': 'oge', + '<': 'olt', '<=': 'ole'} + for cop, cond in oracle.items(): + actual = str(one.fcmp_ordered(cop, two)) + expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + # unordered float compare + oracle = {'==': 'ueq', '!=': 'une', '>': 'ugt', '>=': 'uge', + '<': 'ult', '<=': 'ule'} + for cop, cond in oracle.items(): + actual = str(one.fcmp_unordered(cop, two)) + expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + +class TestTransforms(TestBase): + def test_call_transform(self): + mod = ir.Module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "foo") + bar = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "bar") + builder = ir.IRBuilder() + builder.position_at_end(foo.append_basic_block()) + call = builder.call(foo, ()) + self.assertEqual(call.callee, foo) + modified = ir.replace_all_calls(mod, foo, bar) + self.assertIn(call, modified) + self.assertNotEqual(call.callee, foo) + self.assertEqual(call.callee, bar) + + +class TestSingleton(TestBase): + def test_undefined(self): + self.assertIs(ir.Undefined, ir.values._Undefined()) + self.assertIs(ir.Undefined, copy.copy(ir.Undefined)) + self.assertIs(ir.Undefined, copy.deepcopy(ir.Undefined)) + self.assert_pickle_correctly(ir.Undefined) + + +if __name__ == '__main__': + unittest.main() diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/test_refprune.py b/python_embeded/Lib/site-packages/llvmlite/tests/test_refprune.py new file mode 100644 index 0000000000000000000000000000000000000000..ff293f30b52015f075198ca19510bb421bc820e9 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/test_refprune.py @@ -0,0 +1,730 @@ +import unittest +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite.tests import TestCase + +import llvmlite.tests.refprune_proto as proto + +# TODO:: Get rid of Legacy tests once completely transitioned to NewPassManager + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled + + +def _iterate_cases(generate_test): + def wrap(fn): + def wrapped(self): + return generate_test(self, fn) + wrapped.__doc__ = f"generated test for {fn.__module__}.{fn.__name__}" + return wrapped + + for k, case_fn in proto.__dict__.items(): + if k.startswith('case'): + yield f'test_{k}', wrap(case_fn) + + +class PassManagerMixin(): + + def pb(self): + llvm.initialize_native_target() + tm = llvm.Target.from_default_triple().create_target_machine() + pto = llvm.create_pipeline_tuning_options(speed_level=0, size_level=0) + return llvm.create_pass_builder(tm, pto) + + +class TestRefPrunePrototype(TestCase): + """ + Test that the prototype is working. + """ + def generate_test(self, case_gen): + nodes, edges, expected = case_gen() + got = proto.FanoutAlgorithm(nodes, edges).run() + self.assertEqual(expected, got) + + # Generate tests + for name, case in _iterate_cases(generate_test): + locals()[name] = case + + +ptr_ty = ir.IntType(8).as_pointer() + + +class TestRefPrunePass(TestCase, PassManagerMixin): + """ + Test that the C++ implementation matches the expected behavior as for + the prototype. + + This generates a LLVM module for each test case, runs the pruner and checks + that the expected results are achieved. + """ + + def make_incref(self, m): + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + return ir.Function(m, fnty, name='NRT_incref') + + def make_decref(self, m): + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + return ir.Function(m, fnty, name='NRT_decref') + + def make_switcher(self, m): + fnty = ir.FunctionType(ir.IntType(32), ()) + return ir.Function(m, fnty, name='switcher') + + def make_brancher(self, m): + fnty = ir.FunctionType(ir.IntType(1), ()) + return ir.Function(m, fnty, name='brancher') + + def generate_ir(self, nodes, edges): + # Build LLVM module for the CFG + m = ir.Module() + + incref_fn = self.make_incref(m) + decref_fn = self.make_decref(m) + switcher_fn = self.make_switcher(m) + brancher_fn = self.make_brancher(m) + + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + fn = ir.Function(m, fnty, name='main') + [ptr] = fn.args + ptr.name = 'mem' + # populate the BB nodes + bbmap = {} + for bb in edges: + bbmap[bb] = fn.append_basic_block(bb) + # populate the BB + builder = ir.IRBuilder() + for bb, jump_targets in edges.items(): + builder.position_at_end(bbmap[bb]) + # Insert increfs and decrefs + for action in nodes[bb]: + if action == 'incref': + builder.call(incref_fn, [ptr]) + elif action == 'decref': + builder.call(decref_fn, [ptr]) + else: + raise AssertionError('unreachable') + + # Insert the terminator. + # Switch base on the number of jump targets. + n_targets = len(jump_targets) + if n_targets == 0: + builder.ret_void() + elif n_targets == 1: + [dst] = jump_targets + builder.branch(bbmap[dst]) + elif n_targets == 2: + [left, right] = jump_targets + sel = builder.call(brancher_fn, ()) + builder.cbranch(sel, bbmap[left], bbmap[right]) + elif n_targets > 2: + sel = builder.call(switcher_fn, ()) + [head, *tail] = jump_targets + + sw = builder.switch(sel, default=bbmap[head]) + for i, dst in enumerate(tail): + sw.add_case(sel.type(i), bbmap[dst]) + else: + raise AssertionError('unreachable') + + return m + + def apply_refprune(self, irmod): + mod = llvm.parse_assembly(str(irmod)) + pb = self.pb() + pm = pb.getModulePassManager() + pm.add_refprune_pass() + pm.run(mod, pb) + return mod + + def apply_refprune_legacy(self, irmod): + mod = llvm.parse_assembly(str(irmod)) + pm = llvm.ModulePassManager() + pm.add_refprune_pass() + pm.run(mod) + return mod + + def check(self, mod, expected, nodes): + # preprocess incref/decref locations + d = {} + for k, vs in nodes.items(): + n_incref = vs.count('incref') + n_decref = vs.count('decref') + d[k] = {'incref': n_incref, 'decref': n_decref} + for k, stats in d.items(): + if expected.get(k): + stats['incref'] -= 1 + for dec_bb in expected[k]: + d[dec_bb]['decref'] -= 1 + + # find the main function + for f in mod.functions: + if f.name == 'main': + break + # check each BB + for bb in f.blocks: + stats = d[bb.name] + text = str(bb) + n_incref = text.count('NRT_incref') + n_decref = text.count('NRT_decref') + self.assertEqual(stats['incref'], n_incref, msg=f'BB {bb}') + self.assertEqual(stats['decref'], n_decref, msg=f'BB {bb}') + + def generate_test(self, case_gen): + nodes, edges, expected = case_gen() + irmod = self.generate_ir(nodes, edges) + outmod = self.apply_refprune(irmod) + self.check(outmod, expected, nodes) + + def generate_test_legacy(self, case_gen): + nodes, edges, expected = case_gen() + irmod = self.generate_ir(nodes, edges) + outmod = self.apply_refprune_legacy(irmod) + self.check(outmod, expected, nodes) + + # Generate tests + for name, case in _iterate_cases(generate_test): + locals()[name] = case + + for name, case in _iterate_cases(generate_test_legacy): + locals()[name + "_legacy"] = case + + +class BaseTestByIR(TestCase, PassManagerMixin): + refprune_bitmask = 0 + + prologue = r""" +declare void @NRT_incref(i8* %ptr) +declare void @NRT_decref(i8* %ptr) +""" + + def check(self, irmod, subgraph_limit=None): + mod = llvm.parse_assembly(f"{self.prologue}\n{irmod}") + pb = self.pb() + pm = pb.getModulePassManager() + if subgraph_limit is None: + pm.add_refprune_pass(self.refprune_bitmask) + else: + pm.add_refprune_pass(self.refprune_bitmask, + subgraph_limit=subgraph_limit) + before = llvm.dump_refprune_stats() + pm.run(mod, pb) + after = llvm.dump_refprune_stats() + return mod, after - before + + def check_legacy(self, irmod, subgraph_limit=None): + mod = llvm.parse_assembly(f"{self.prologue}\n{irmod}") + pm = llvm.ModulePassManager() + if subgraph_limit is None: + pm.add_refprune_pass(self.refprune_bitmask) + else: + pm.add_refprune_pass(self.refprune_bitmask, + subgraph_limit=subgraph_limit) + before = llvm.dump_refprune_stats() + pm.run(mod) + after = llvm.dump_refprune_stats() + return mod, after - before + + +class TestPerBB(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.PER_BB + + per_bb_ir_1 = r""" +define void @main(i8* %ptr) { + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_bb_1(self): + mod, stats = self.check(self.per_bb_ir_1) + self.assertEqual(stats.basicblock, 2) + + def test_per_bb_1_legacy(self): + mod, stats = self.check_legacy(self.per_bb_ir_1) + self.assertEqual(stats.basicblock, 2) + + per_bb_ir_2 = r""" +define void @main(i8* %ptr) { + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_bb_2(self): + mod, stats = self.check(self.per_bb_ir_2) + self.assertEqual(stats.basicblock, 4) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_incref(ptr %ptr)", str(mod)) + else: + self.assertIn("call void @NRT_incref(i8* %ptr)", str(mod)) + + def test_per_bb_2_legacy(self): + mod, stats = self.check_legacy(self.per_bb_ir_2) + self.assertEqual(stats.basicblock, 4) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_incref(ptr %ptr)", str(mod)) + else: + self.assertIn("call void @NRT_incref(i8* %ptr)", str(mod)) + + per_bb_ir_3 = r""" +define void @main(ptr %ptr, ptr %other) { + call void @NRT_incref(ptr %ptr) + call void @NRT_incref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %other) + ret void +} +""" if opaque_pointers_enabled else r""" +define void @main(i8* %ptr, i8* %other) { + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %other) + ret void +} +""" + + def test_per_bb_3(self): + mod, stats = self.check(self.per_bb_ir_3) + self.assertEqual(stats.basicblock, 2) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + else: + self.assertIn("call void @NRT_decref(i8* %other)", str(mod)) + + def test_per_bb_3_legacy(self): + mod, stats = self.check_legacy(self.per_bb_ir_3) + self.assertEqual(stats.basicblock, 2) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + else: + self.assertIn("call void @NRT_decref(i8* %other)", str(mod)) + + per_bb_ir_4 = r""" +; reordered +define void @main(ptr %ptr, ptr %other) { + call void @NRT_incref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %other) + call void @NRT_incref(ptr %ptr) + ret void +} +""" if opaque_pointers_enabled else r""" +; reordered +define void @main(i8* %ptr, i8* %other) { + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %other) + call void @NRT_incref(i8* %ptr) + ret void +} +""" + + def test_per_bb_4(self): + mod, stats = self.check(self.per_bb_ir_4) + self.assertEqual(stats.basicblock, 4) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + else: + self.assertIn("call void @NRT_decref(i8* %other)", str(mod)) + + def test_per_bb_4_legacy(self): + mod, stats = self.check_legacy(self.per_bb_ir_4) + self.assertEqual(stats.basicblock, 4) + # not pruned + # FIXME: Remove `else' once TP are no longer supported. + if opaque_pointers_enabled: + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + else: + self.assertIn("call void @NRT_decref(i8* %other)", str(mod)) + + +class TestDiamond(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.DIAMOND + + per_diamond_1 = r""" +define void @main(i8* %ptr) { +bb_A: + call void @NRT_incref(i8* %ptr) + br label %bb_B +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_1(self): + mod, stats = self.check(self.per_diamond_1) + self.assertEqual(stats.diamond, 2) + + def test_per_diamond_1_legacy(self): + mod, stats = self.check_legacy(self.per_diamond_1) + self.assertEqual(stats.diamond, 2) + + per_diamond_2 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_2(self): + mod, stats = self.check(self.per_diamond_2) + self.assertEqual(stats.diamond, 2) + + def test_per_diamond_2_legacy(self): + mod, stats = self.check_legacy(self.per_diamond_2) + self.assertEqual(stats.diamond, 2) + + per_diamond_3 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + call void @NRT_decref(i8* %ptr) ; reject because of decref in diamond + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_3(self): + mod, stats = self.check(self.per_diamond_3) + self.assertEqual(stats.diamond, 0) + + def test_per_diamond_3_legacy(self): + mod, stats = self.check_legacy(self.per_diamond_3) + self.assertEqual(stats.diamond, 0) + + per_diamond_4 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_incref(i8* %ptr) ; extra incref will not affect prune + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_4(self): + mod, stats = self.check(self.per_diamond_4) + self.assertEqual(stats.diamond, 2) + + def test_per_diamond_4_legacy(self): + mod, stats = self.check_legacy(self.per_diamond_4) + self.assertEqual(stats.diamond, 2) + + per_diamond_5 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_5(self): + mod, stats = self.check(self.per_diamond_5) + self.assertEqual(stats.diamond, 4) + + def test_per_diamond_5_legacy(self): + mod, stats = self.check_legacy(self.per_diamond_5) + self.assertEqual(stats.diamond, 4) + + +class TestFanout(BaseTestByIR): + """More complex cases are tested in TestRefPrunePass + """ + + refprune_bitmask = llvm.RefPruneSubpasses.FANOUT + + fanout_1 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_fanout_1(self): + mod, stats = self.check(self.fanout_1) + self.assertEqual(stats.fanout, 3) + + def test_fanout_1_legacy(self): + mod, stats = self.check_legacy(self.fanout_1) + self.assertEqual(stats.fanout, 3) + + fanout_2 = r""" +define void @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + br label %bb_B ; illegal jump to other decref +} +""" + + def test_fanout_2(self): + mod, stats = self.check(self.fanout_2) + self.assertEqual(stats.fanout, 0) + + def test_fanout_2_legacy(self): + mod, stats = self.check_legacy(self.fanout_2) + self.assertEqual(stats.fanout, 0) + + fanout_3 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_fanout_3(self): + mod, stats = self.check(self.fanout_3) + self.assertEqual(stats.fanout, 6) + + def test_fanout_3_limited(self): + # With subgraph limit at 1, it is essentially turning off the fanout + # pruner. + mod, stats = self.check(self.fanout_3, subgraph_limit=1) + self.assertEqual(stats.fanout, 0) + + def test_fanout_3_legacy(self): + mod, stats = self.check_legacy(self.fanout_3) + self.assertEqual(stats.fanout, 6) + + def test_fanout_3_limited_legacy(self): + # With subgraph limit at 1, it is essentially turning off the fanout + # pruner. + mod, stats = self.check_legacy(self.fanout_3, subgraph_limit=1) + self.assertEqual(stats.fanout, 0) + + +class TestFanoutRaise(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.FANOUT_RAISE + + fanout_raise_1 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +} +!0 = !{i1 true} +""" + + def test_fanout_raise_1(self): + mod, stats = self.check(self.fanout_raise_1) + self.assertEqual(stats.fanout_raise, 2) + + def test_fanout_raise_1_legacy(self): + mod, stats = self.check_legacy(self.fanout_raise_1) + self.assertEqual(stats.fanout_raise, 2) + + fanout_raise_2 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_typo !0 ; bad metadata + ret i32 1 +} + +!0 = !{i1 true} +""" + + def test_fanout_raise_2(self): + # This is ensuring that fanout_raise is not pruning when the metadata + # is incorrectly named. + mod, stats = self.check(self.fanout_raise_2) + self.assertEqual(stats.fanout_raise, 0) + + def test_fanout_raise_2_legacy(self): + # This is ensuring that fanout_raise is not pruning when the metadata + # is incorrectly named. + mod, stats = self.check_legacy(self.fanout_raise_2) + self.assertEqual(stats.fanout_raise, 0) + + fanout_raise_3 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +} + +!0 = !{i32 1} ; ok; use i32 +""" + + def test_fanout_raise_3(self): + mod, stats = self.check(self.fanout_raise_3) + self.assertEqual(stats.fanout_raise, 2) + + def test_fanout_raise_3_legacy(self): + mod, stats = self.check_legacy(self.fanout_raise_3) + self.assertEqual(stats.fanout_raise, 2) + + fanout_raise_4 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + ret i32 1 ; BAD; all tails are raising without decref +bb_C: + ret i32 1 ; BAD; all tails are raising without decref +} + +!0 = !{i1 1} +""" + + def test_fanout_raise_4(self): + mod, stats = self.check(self.fanout_raise_4) + self.assertEqual(stats.fanout_raise, 0) + + def test_fanout_raise_4_legacy(self): + mod, stats = self.check_legacy(self.fanout_raise_4) + self.assertEqual(stats.fanout_raise, 0) + + fanout_raise_5 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + br label %common.ret +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + br label %common.ret +common.ret: + %common.ret.op = phi i32 [ 0, %bb_B ], [ 1, %bb_C ] + ret i32 %common.ret.op +} +!0 = !{i1 1} +""" + + def test_fanout_raise_5(self): + mod, stats = self.check(self.fanout_raise_5) + self.assertEqual(stats.fanout_raise, 2) + + def test_fanout_raise_5_legacy(self): + mod, stats = self.check_legacy(self.fanout_raise_5) + self.assertEqual(stats.fanout_raise, 2) + + # test case 6 is from https://github.com/numba/llvmlite/issues/1023 + fanout_raise_6 = r""" +define i32 @main(i8* %ptr, i1 %cond1, i1 %cond2, i1 %cond3, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond1, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + br i1 %cond2, label %bb_D, label %bb_E +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +bb_D: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_E: + call void @NRT_incref(i8* %ptr) + br i1 %cond3, label %bb_F, label %bb_C +bb_F: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret i32 0 +} +!0 = !{i1 1} +""" + + def test_fanout_raise_6(self): + mod, stats = self.check(self.fanout_raise_6) + self.assertEqual(stats.fanout_raise, 7) + + def test_fanout_raise_6_legacy(self): + mod, stats = self.check_legacy(self.fanout_raise_6) + self.assertEqual(stats.fanout_raise, 7) + + +if __name__ == '__main__': + unittest.main() diff --git a/python_embeded/Lib/site-packages/llvmlite/tests/test_valuerepr.py b/python_embeded/Lib/site-packages/llvmlite/tests/test_valuerepr.py new file mode 100644 index 0000000000000000000000000000000000000000..72022650d42ce705ca3708d5d6442f2405d1f287 --- /dev/null +++ b/python_embeded/Lib/site-packages/llvmlite/tests/test_valuerepr.py @@ -0,0 +1,60 @@ +import math +import sys +import unittest + +from llvmlite.ir import ( + Constant, FloatType, DoubleType, LiteralStructType, IntType, + ArrayType, HalfType) +from llvmlite.tests import TestCase + + +int8 = IntType(8) +int16 = IntType(16) + + +PY36_OR_LATER = sys.version_info[:2] >= (3, 6) + + +class TestValueRepr(TestCase): + + def test_double_repr(self): + def check_repr(val, expected): + c = Constant(DoubleType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "double 0x400921fb54442d18") + check_repr(float('inf'), "double 0x7ff0000000000000") + check_repr(float('-inf'), "double 0xfff0000000000000") + + def test_float_repr(self): + def check_repr(val, expected): + c = Constant(FloatType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "float 0x400921fb60000000") + check_repr(float('inf'), "float 0x7ff0000000000000") + check_repr(float('-inf'), "float 0xfff0000000000000") + + @unittest.skipUnless(PY36_OR_LATER, 'py36+ only') + def test_half_repr(self): + def check_repr(val, expected): + c = Constant(HalfType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "half 0x4009200000000000") + check_repr(float('inf'), "half 0x7ff0000000000000") + check_repr(float('-inf'), "half 0xfff0000000000000") + + def test_struct_repr(self): + tp = LiteralStructType([int8, int16]) + c = Constant(tp, (Constant(int8, 100), Constant(int16, 1000))) + self.assertEqual(str(c), "{i8, i16} {i8 100, i16 1000}") + + def test_array_repr(self): + tp = ArrayType(int8, 3) + values = [Constant(int8, x) for x in (5, 10, -15)] + c = Constant(tp, values) + self.assertEqual(str(c), "[3 x i8] [i8 5, i8 10, i8 -15]") + c = Constant(tp, bytearray(b"\x01\x02\x03")) + self.assertEqual(str(c), '[3 x i8] c"\\01\\02\\03"') + + +if __name__ == "__main__": + unittest.main() diff --git a/python_embeded/Lib/site-packages/mako-1.3.10.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/mako-1.3.10.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4c18adee3da2a51fb5b2b77567cb408ea4395b50 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako-1.3.10.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright 2006-2025 the Mako authors and contributors . + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python_embeded/Lib/site-packages/mako/ext/__init__.py b/python_embeded/Lib/site-packages/mako/ext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/mako/ext/autohandler.py b/python_embeded/Lib/site-packages/mako/ext/autohandler.py new file mode 100644 index 0000000000000000000000000000000000000000..829ed097ce1dd90fd517760f0f49ee23d41cf8c6 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/autohandler.py @@ -0,0 +1,70 @@ +# ext/autohandler.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +"""adds autohandler functionality to Mako templates. + +requires that the TemplateLookup class is used with templates. + +usage:: + + <%! + from mako.ext.autohandler import autohandler + %> + <%inherit file="${autohandler(template, context)}"/> + + +or with custom autohandler filename:: + + <%! + from mako.ext.autohandler import autohandler + %> + <%inherit file="${autohandler(template, context, name='somefilename')}"/> + +""" + +import os +import posixpath +import re + + +def autohandler(template, context, name="autohandler"): + lookup = context.lookup + _template_uri = template.module._template_uri + if not lookup.filesystem_checks: + try: + return lookup._uri_cache[(autohandler, _template_uri, name)] + except KeyError: + pass + + tokens = re.findall(r"([^/]+)", posixpath.dirname(_template_uri)) + [name] + while len(tokens): + path = "/" + "/".join(tokens) + if path != _template_uri and _file_exists(lookup, path): + if not lookup.filesystem_checks: + return lookup._uri_cache.setdefault( + (autohandler, _template_uri, name), path + ) + else: + return path + if len(tokens) == 1: + break + tokens[-2:] = [name] + + if not lookup.filesystem_checks: + return lookup._uri_cache.setdefault( + (autohandler, _template_uri, name), None + ) + else: + return None + + +def _file_exists(lookup, path): + psub = re.sub(r"^/", "", path) + for d in lookup.directories: + if os.path.exists(d + "/" + psub): + return True + else: + return False diff --git a/python_embeded/Lib/site-packages/mako/ext/babelplugin.py b/python_embeded/Lib/site-packages/mako/ext/babelplugin.py new file mode 100644 index 0000000000000000000000000000000000000000..541ea54091c80974ab9091ad478692673816befa --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/babelplugin.py @@ -0,0 +1,57 @@ +# ext/babelplugin.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +"""gettext message extraction via Babel: https://pypi.org/project/Babel/""" +from babel.messages.extract import extract_python + +from mako.ext.extract import MessageExtractor + + +class BabelMakoExtractor(MessageExtractor): + def __init__(self, keywords, comment_tags, options): + self.keywords = keywords + self.options = options + self.config = { + "comment-tags": " ".join(comment_tags), + "encoding": options.get( + "input_encoding", options.get("encoding", None) + ), + } + super().__init__() + + def __call__(self, fileobj): + return self.process_file(fileobj) + + def process_python(self, code, code_lineno, translator_strings): + comment_tags = self.config["comment-tags"] + for ( + lineno, + funcname, + messages, + python_translator_comments, + ) in extract_python(code, self.keywords, comment_tags, self.options): + yield ( + code_lineno + (lineno - 1), + funcname, + messages, + translator_strings + python_translator_comments, + ) + + +def extract(fileobj, keywords, comment_tags, options): + """Extract messages from Mako templates. + + :param fileobj: the file-like object the messages should be extracted from + :param keywords: a list of keywords (i.e. function names) that should be + recognized as translation functions + :param comment_tags: a list of translator tags to search for and include + in the results + :param options: a dictionary of additional options (optional) + :return: an iterator over ``(lineno, funcname, message, comments)`` tuples + :rtype: ``iterator`` + """ + extractor = BabelMakoExtractor(keywords, comment_tags, options) + yield from extractor(fileobj) diff --git a/python_embeded/Lib/site-packages/mako/ext/beaker_cache.py b/python_embeded/Lib/site-packages/mako/ext/beaker_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..b1392f30f684de1dc830888a11337d20afb478bc --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/beaker_cache.py @@ -0,0 +1,82 @@ +# ext/beaker_cache.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +"""Provide a :class:`.CacheImpl` for the Beaker caching system.""" + +from mako import exceptions +from mako.cache import CacheImpl + +try: + from beaker import cache as beaker_cache +except: + has_beaker = False +else: + has_beaker = True + +_beaker_cache = None + + +class BeakerCacheImpl(CacheImpl): + + """A :class:`.CacheImpl` provided for the Beaker caching system. + + This plugin is used by default, based on the default + value of ``'beaker'`` for the ``cache_impl`` parameter of the + :class:`.Template` or :class:`.TemplateLookup` classes. + + """ + + def __init__(self, cache): + if not has_beaker: + raise exceptions.RuntimeException( + "Can't initialize Beaker plugin; Beaker is not installed." + ) + global _beaker_cache + if _beaker_cache is None: + if "manager" in cache.template.cache_args: + _beaker_cache = cache.template.cache_args["manager"] + else: + _beaker_cache = beaker_cache.CacheManager() + super().__init__(cache) + + def _get_cache(self, **kw): + expiretime = kw.pop("timeout", None) + if "dir" in kw: + kw["data_dir"] = kw.pop("dir") + elif self.cache.template.module_directory: + kw["data_dir"] = self.cache.template.module_directory + + if "manager" in kw: + kw.pop("manager") + + if kw.get("type") == "memcached": + kw["type"] = "ext:memcached" + + if "region" in kw: + region = kw.pop("region") + cache = _beaker_cache.get_cache_region(self.cache.id, region, **kw) + else: + cache = _beaker_cache.get_cache(self.cache.id, **kw) + cache_args = {"starttime": self.cache.starttime} + if expiretime: + cache_args["expiretime"] = expiretime + return cache, cache_args + + def get_or_create(self, key, creation_function, **kw): + cache, kw = self._get_cache(**kw) + return cache.get(key, createfunc=creation_function, **kw) + + def put(self, key, value, **kw): + cache, kw = self._get_cache(**kw) + cache.put(key, value, **kw) + + def get(self, key, **kw): + cache, kw = self._get_cache(**kw) + return cache.get(key, **kw) + + def invalidate(self, key, **kw): + cache, kw = self._get_cache(**kw) + cache.remove_value(key, **kw) diff --git a/python_embeded/Lib/site-packages/mako/ext/extract.py b/python_embeded/Lib/site-packages/mako/ext/extract.py new file mode 100644 index 0000000000000000000000000000000000000000..609c5c29882b36165a381f527938f939c55010ee --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/extract.py @@ -0,0 +1,129 @@ +# ext/extract.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +from io import BytesIO +from io import StringIO +import re + +from mako import lexer +from mako import parsetree + + +class MessageExtractor: + use_bytes = True + + def process_file(self, fileobj): + template_node = lexer.Lexer( + fileobj.read(), input_encoding=self.config["encoding"] + ).parse() + yield from self.extract_nodes(template_node.get_children()) + + def extract_nodes(self, nodes): + translator_comments = [] + in_translator_comments = False + input_encoding = self.config["encoding"] or "ascii" + comment_tags = list( + filter(None, re.split(r"\s+", self.config["comment-tags"])) + ) + + for node in nodes: + child_nodes = None + if ( + in_translator_comments + and isinstance(node, parsetree.Text) + and not node.content.strip() + ): + # Ignore whitespace within translator comments + continue + + if isinstance(node, parsetree.Comment): + value = node.text.strip() + if in_translator_comments: + translator_comments.extend( + self._split_comment(node.lineno, value) + ) + continue + for comment_tag in comment_tags: + if value.startswith(comment_tag): + in_translator_comments = True + translator_comments.extend( + self._split_comment(node.lineno, value) + ) + continue + + if isinstance(node, parsetree.DefTag): + code = node.function_decl.code + child_nodes = node.nodes + elif isinstance(node, parsetree.BlockTag): + code = node.body_decl.code + child_nodes = node.nodes + elif isinstance(node, parsetree.CallTag): + code = node.code.code + child_nodes = node.nodes + elif isinstance(node, parsetree.PageTag): + code = node.body_decl.code + elif isinstance(node, parsetree.CallNamespaceTag): + code = node.expression + child_nodes = node.nodes + elif isinstance(node, parsetree.ControlLine): + if node.isend: + in_translator_comments = False + continue + code = node.text + elif isinstance(node, parsetree.Code): + in_translator_comments = False + code = node.code.code + elif isinstance(node, parsetree.Expression): + code = node.code.code + else: + continue + + # Comments don't apply unless they immediately precede the message + if ( + translator_comments + and translator_comments[-1][0] < node.lineno - 1 + ): + translator_comments = [] + + translator_strings = [ + comment[1] for comment in translator_comments + ] + + if isinstance(code, str) and self.use_bytes: + code = code.encode(input_encoding, "backslashreplace") + + used_translator_comments = False + # We add extra newline to work around a pybabel bug + # (see python-babel/babel#274, parse_encoding dies if the first + # input string of the input is non-ascii) + # Also, because we added it, we have to subtract one from + # node.lineno + if self.use_bytes: + code = BytesIO(b"\n" + code) + else: + code = StringIO("\n" + code) + + for message in self.process_python( + code, node.lineno - 1, translator_strings + ): + yield message + used_translator_comments = True + + if used_translator_comments: + translator_comments = [] + in_translator_comments = False + + if child_nodes: + yield from self.extract_nodes(child_nodes) + + @staticmethod + def _split_comment(lineno, comment): + """Return the multiline comment at lineno split into a list of + comment line numbers and the accompanying comment line""" + return [ + (lineno + index, line) + for index, line in enumerate(comment.splitlines()) + ] diff --git a/python_embeded/Lib/site-packages/mako/ext/linguaplugin.py b/python_embeded/Lib/site-packages/mako/ext/linguaplugin.py new file mode 100644 index 0000000000000000000000000000000000000000..118668de2c19d987a15eea5f0e29ca3c9a068035 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/linguaplugin.py @@ -0,0 +1,57 @@ +# ext/linguaplugin.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +import contextlib +import io + +from lingua.extractors import Extractor +from lingua.extractors import get_extractor +from lingua.extractors import Message + +from mako.ext.extract import MessageExtractor + + +class LinguaMakoExtractor(Extractor, MessageExtractor): + """Mako templates""" + + use_bytes = False + extensions = [".mako"] + default_config = {"encoding": "utf-8", "comment-tags": ""} + + def __call__(self, filename, options, fileobj=None): + self.options = options + self.filename = filename + self.python_extractor = get_extractor("x.py") + if fileobj is None: + ctx = open(filename, "r") + else: + ctx = contextlib.nullcontext(fileobj) + with ctx as file_: + yield from self.process_file(file_) + + def process_python(self, code, code_lineno, translator_strings): + source = code.getvalue().strip() + if source.endswith(":"): + if source in ("try:", "else:") or source.startswith("except"): + source = "" # Ignore try/except and else + elif source.startswith("elif"): + source = source[2:] # Replace "elif" with "if" + source += "pass" + code = io.StringIO(source) + for msg in self.python_extractor( + self.filename, self.options, code, code_lineno - 1 + ): + if translator_strings: + msg = Message( + msg.msgctxt, + msg.msgid, + msg.msgid_plural, + msg.flags, + " ".join(translator_strings + [msg.comment]), + msg.tcomment, + msg.location, + ) + yield msg diff --git a/python_embeded/Lib/site-packages/mako/ext/preprocessors.py b/python_embeded/Lib/site-packages/mako/ext/preprocessors.py new file mode 100644 index 0000000000000000000000000000000000000000..21f2db54db507b236146432c39d4b4cc40bb2f9a --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/preprocessors.py @@ -0,0 +1,20 @@ +# ext/preprocessors.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +"""preprocessing functions, used with the 'preprocessor' +argument on Template, TemplateLookup""" + +import re + + +def convert_comments(text): + """preprocess old style comments. + + example: + + from mako.ext.preprocessors import convert_comments + t = Template(..., preprocessor=convert_comments)""" + return re.sub(r"(?<=\n)\s*#[^#]", "##", text) diff --git a/python_embeded/Lib/site-packages/mako/ext/pygmentplugin.py b/python_embeded/Lib/site-packages/mako/ext/pygmentplugin.py new file mode 100644 index 0000000000000000000000000000000000000000..74a8fb9dbcf6578b30ba8874ac31838c221ac19e --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/pygmentplugin.py @@ -0,0 +1,150 @@ +# ext/pygmentplugin.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +from pygments import highlight +from pygments.formatters.html import HtmlFormatter +from pygments.lexer import bygroups +from pygments.lexer import DelegatingLexer +from pygments.lexer import include +from pygments.lexer import RegexLexer +from pygments.lexer import using +from pygments.lexers.agile import Python3Lexer +from pygments.lexers.agile import PythonLexer +from pygments.lexers.web import CssLexer +from pygments.lexers.web import HtmlLexer +from pygments.lexers.web import JavascriptLexer +from pygments.lexers.web import XmlLexer +from pygments.token import Comment +from pygments.token import Keyword +from pygments.token import Name +from pygments.token import Operator +from pygments.token import Other +from pygments.token import String +from pygments.token import Text + + +class MakoLexer(RegexLexer): + name = "Mako" + aliases = ["mako"] + filenames = ["*.mao"] + + tokens = { + "root": [ + ( + r"(\s*)(\%)(\s*end(?:\w+))(\n|\Z)", + bygroups(Text, Comment.Preproc, Keyword, Other), + ), + ( + r"(\s*)(\%(?!%))([^\n]*)(\n|\Z)", + bygroups(Text, Comment.Preproc, using(PythonLexer), Other), + ), + ( + r"(\s*)(##[^\n]*)(\n|\Z)", + bygroups(Text, Comment.Preproc, Other), + ), + (r"""(?s)<%doc>.*?""", Comment.Preproc), + ( + r"(<%)([\w\.\:]+)", + bygroups(Comment.Preproc, Name.Builtin), + "tag", + ), + ( + r"()", + bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc), + ), + (r"<%(?=([\w\.\:]+))", Comment.Preproc, "ondeftags"), + ( + r"(?s)(<%(?:!?))(.*?)(%>)", + bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc), + ), + ( + r"(\$\{)(.*?)(\})", + bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc), + ), + ( + r"""(?sx) + (.+?) # anything, followed by: + (?: + (?<=\n)(?=%(?!%)|\#\#) | # an eval or comment line + (?=\#\*) | # multiline comment + (?=", Comment.Preproc, "#pop"), + (r"\s+", Text), + ], + "attr": [ + ('".*?"', String, "#pop"), + ("'.*?'", String, "#pop"), + (r"[^\s>]+", String, "#pop"), + ], + } + + +class MakoHtmlLexer(DelegatingLexer): + name = "HTML+Mako" + aliases = ["html+mako"] + + def __init__(self, **options): + super().__init__(HtmlLexer, MakoLexer, **options) + + +class MakoXmlLexer(DelegatingLexer): + name = "XML+Mako" + aliases = ["xml+mako"] + + def __init__(self, **options): + super().__init__(XmlLexer, MakoLexer, **options) + + +class MakoJavascriptLexer(DelegatingLexer): + name = "JavaScript+Mako" + aliases = ["js+mako", "javascript+mako"] + + def __init__(self, **options): + super().__init__(JavascriptLexer, MakoLexer, **options) + + +class MakoCssLexer(DelegatingLexer): + name = "CSS+Mako" + aliases = ["css+mako"] + + def __init__(self, **options): + super().__init__(CssLexer, MakoLexer, **options) + + +pygments_html_formatter = HtmlFormatter( + cssclass="syntax-highlighted", linenos=True +) + + +def syntax_highlight(filename="", language=None): + mako_lexer = MakoLexer() + python_lexer = Python3Lexer() + if filename.startswith("memory:") or language == "mako": + return lambda string: highlight( + string, mako_lexer, pygments_html_formatter + ) + return lambda string: highlight( + string, python_lexer, pygments_html_formatter + ) diff --git a/python_embeded/Lib/site-packages/mako/ext/turbogears.py b/python_embeded/Lib/site-packages/mako/ext/turbogears.py new file mode 100644 index 0000000000000000000000000000000000000000..25ad35e7746b82a2e65a4c33c70da701912ccf00 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/ext/turbogears.py @@ -0,0 +1,61 @@ +# ext/turbogears.py +# Copyright 2006-2025 the Mako authors and contributors +# +# This module is part of Mako and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +from mako import compat +from mako.lookup import TemplateLookup +from mako.template import Template + + +class TGPlugin: + + """TurboGears compatible Template Plugin.""" + + def __init__(self, extra_vars_func=None, options=None, extension="mak"): + self.extra_vars_func = extra_vars_func + self.extension = extension + if not options: + options = {} + + # Pull the options out and initialize the lookup + lookup_options = {} + for k, v in options.items(): + if k.startswith("mako."): + lookup_options[k[5:]] = v + elif k in ["directories", "filesystem_checks", "module_directory"]: + lookup_options[k] = v + self.lookup = TemplateLookup(**lookup_options) + + self.tmpl_options = {} + # transfer lookup args to template args, based on those available + # in getargspec + for kw in compat.inspect_getargspec(Template.__init__)[0]: + if kw in lookup_options: + self.tmpl_options[kw] = lookup_options[kw] + + def load_template(self, templatename, template_string=None): + """Loads a template from a file or a string""" + if template_string is not None: + return Template(template_string, **self.tmpl_options) + # Translate TG dot notation to normal / template path + if "/" not in templatename: + templatename = ( + "/" + templatename.replace(".", "/") + "." + self.extension + ) + + # Lookup template + return self.lookup.get_template(templatename) + + def render( + self, info, format="html", fragment=False, template=None # noqa + ): + if isinstance(template, str): + template = self.load_template(template) + + # Load extra vars func if provided + if self.extra_vars_func: + info.update(self.extra_vars_func()) + + return template.render(**info) diff --git a/python_embeded/Lib/site-packages/mako/testing/__init__.py b/python_embeded/Lib/site-packages/mako/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/mako/testing/_config.py b/python_embeded/Lib/site-packages/mako/testing/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee3d0a6ed770aba19adb757ffd552d504c5b9e2 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/_config.py @@ -0,0 +1,128 @@ +import configparser +import dataclasses +from dataclasses import dataclass +from pathlib import Path +from typing import Callable +from typing import ClassVar +from typing import Optional +from typing import Union + +from .helpers import make_path + + +class ConfigError(BaseException): + pass + + +class MissingConfig(ConfigError): + pass + + +class MissingConfigSection(ConfigError): + pass + + +class MissingConfigItem(ConfigError): + pass + + +class ConfigValueTypeError(ConfigError): + pass + + +class _GetterDispatch: + def __init__(self, initialdata, default_getter: Callable): + self.default_getter = default_getter + self.data = initialdata + + def get_fn_for_type(self, type_): + return self.data.get(type_, self.default_getter) + + def get_typed_value(self, type_, name): + get_fn = self.get_fn_for_type(type_) + return get_fn(name) + + +def _parse_cfg_file(filespec: Union[Path, str]): + cfg = configparser.ConfigParser() + try: + filepath = make_path(filespec, check_exists=True) + except FileNotFoundError as e: + raise MissingConfig(f"No config file found at {filespec}") from e + else: + with open(filepath, encoding="utf-8") as f: + cfg.read_file(f) + return cfg + + +def _build_getter(cfg_obj, cfg_section, method, converter=None): + def caller(option, **kwargs): + try: + rv = getattr(cfg_obj, method)(cfg_section, option, **kwargs) + except configparser.NoSectionError as nse: + raise MissingConfigSection( + f"No config section named {cfg_section}" + ) from nse + except configparser.NoOptionError as noe: + raise MissingConfigItem(f"No config item for {option}") from noe + except ValueError as ve: + # ConfigParser.getboolean, .getint, .getfloat raise ValueError + # on bad types + raise ConfigValueTypeError( + f"Wrong value type for {option}" + ) from ve + else: + if converter: + try: + rv = converter(rv) + except Exception as e: + raise ConfigValueTypeError( + f"Wrong value type for {option}" + ) from e + return rv + + return caller + + +def _build_getter_dispatch(cfg_obj, cfg_section, converters=None): + converters = converters or {} + + default_getter = _build_getter(cfg_obj, cfg_section, "get") + + # support ConfigParser builtins + getters = { + int: _build_getter(cfg_obj, cfg_section, "getint"), + bool: _build_getter(cfg_obj, cfg_section, "getboolean"), + float: _build_getter(cfg_obj, cfg_section, "getfloat"), + str: default_getter, + } + + # use ConfigParser.get and convert value + getters.update( + { + type_: _build_getter( + cfg_obj, cfg_section, "get", converter=converter_fn + ) + for type_, converter_fn in converters.items() + } + ) + + return _GetterDispatch(getters, default_getter) + + +@dataclass +class ReadsCfg: + section_header: ClassVar[str] + converters: ClassVar[Optional[dict]] = None + + @classmethod + def from_cfg_file(cls, filespec: Union[Path, str]): + cfg = _parse_cfg_file(filespec) + dispatch = _build_getter_dispatch( + cfg, cls.section_header, converters=cls.converters + ) + kwargs = { + field.name: dispatch.get_typed_value(field.type, field.name) + for field in dataclasses.fields(cls) + } + return cls(**kwargs) diff --git a/python_embeded/Lib/site-packages/mako/testing/assertions.py b/python_embeded/Lib/site-packages/mako/testing/assertions.py new file mode 100644 index 0000000000000000000000000000000000000000..22221cd20c4a65054ad0f6fec17640255671a81d --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/assertions.py @@ -0,0 +1,166 @@ +import contextlib +import re +import sys + + +def eq_(a, b, msg=None): + """Assert a == b, with repr messaging on failure.""" + assert a == b, msg or "%r != %r" % (a, b) + + +def ne_(a, b, msg=None): + """Assert a != b, with repr messaging on failure.""" + assert a != b, msg or "%r == %r" % (a, b) + + +def in_(a, b, msg=None): + """Assert a in b, with repr messaging on failure.""" + assert a in b, msg or "%r not in %r" % (a, b) + + +def not_in(a, b, msg=None): + """Assert a in not b, with repr messaging on failure.""" + assert a not in b, msg or "%r is in %r" % (a, b) + + +def _assert_proper_exception_context(exception): + """assert that any exception we're catching does not have a __context__ + without a __cause__, and that __suppress_context__ is never set. + + Python 3 will report nested as exceptions as "during the handling of + error X, error Y occurred". That's not what we want to do. We want + these exceptions in a cause chain. + + """ + + if ( + exception.__context__ is not exception.__cause__ + and not exception.__suppress_context__ + ): + assert False, ( + "Exception %r was correctly raised but did not set a cause, " + "within context %r as its cause." + % (exception, exception.__context__) + ) + + +def _assert_proper_cause_cls(exception, cause_cls): + """assert that any exception we're catching does not have a __context__ + without a __cause__, and that __suppress_context__ is never set. + + Python 3 will report nested as exceptions as "during the handling of + error X, error Y occurred". That's not what we want to do. We want + these exceptions in a cause chain. + + """ + assert isinstance(exception.__cause__, cause_cls), ( + "Exception %r was correctly raised but has cause %r, which does not " + "have the expected cause type %r." + % (exception, exception.__cause__, cause_cls) + ) + + +def assert_raises(except_cls, callable_, *args, **kw): + return _assert_raises(except_cls, callable_, args, kw) + + +def assert_raises_with_proper_context(except_cls, callable_, *args, **kw): + return _assert_raises(except_cls, callable_, args, kw, check_context=True) + + +def assert_raises_with_given_cause( + except_cls, cause_cls, callable_, *args, **kw +): + return _assert_raises(except_cls, callable_, args, kw, cause_cls=cause_cls) + + +def assert_raises_message(except_cls, msg, callable_, *args, **kwargs): + return _assert_raises(except_cls, callable_, args, kwargs, msg=msg) + + +def assert_raises_message_with_proper_context( + except_cls, msg, callable_, *args, **kwargs +): + return _assert_raises( + except_cls, callable_, args, kwargs, msg=msg, check_context=True + ) + + +def assert_raises_message_with_given_cause( + except_cls, msg, cause_cls, callable_, *args, **kwargs +): + return _assert_raises( + except_cls, callable_, args, kwargs, msg=msg, cause_cls=cause_cls + ) + + +def _assert_raises( + except_cls, + callable_, + args, + kwargs, + msg=None, + check_context=False, + cause_cls=None, +): + with _expect_raises(except_cls, msg, check_context, cause_cls) as ec: + callable_(*args, **kwargs) + return ec.error + + +class _ErrorContainer: + error = None + + +@contextlib.contextmanager +def _expect_raises(except_cls, msg=None, check_context=False, cause_cls=None): + ec = _ErrorContainer() + if check_context: + are_we_already_in_a_traceback = sys.exc_info()[0] + try: + yield ec + success = False + except except_cls as err: + ec.error = err + success = True + if msg is not None: + # I'm often pdbing here, and "err" above isn't + # in scope, so assign the string explicitly + error_as_string = str(err) + assert re.search(msg, error_as_string, re.UNICODE), "%r !~ %s" % ( + msg, + error_as_string, + ) + if cause_cls is not None: + _assert_proper_cause_cls(err, cause_cls) + if check_context and not are_we_already_in_a_traceback: + _assert_proper_exception_context(err) + print(str(err).encode("utf-8")) + + # it's generally a good idea to not carry traceback objects outside + # of the except: block, but in this case especially we seem to have + # hit some bug in either python 3.10.0b2 or greenlet or both which + # this seems to fix: + # https://github.com/python-greenlet/greenlet/issues/242 + del ec + + # assert outside the block so it works for AssertionError too ! + assert success, "Callable did not raise an exception" + + +def expect_raises(except_cls, check_context=False): + return _expect_raises(except_cls, check_context=check_context) + + +def expect_raises_message(except_cls, msg, check_context=False): + return _expect_raises(except_cls, msg=msg, check_context=check_context) + + +def expect_raises_with_proper_context(except_cls, check_context=True): + return _expect_raises(except_cls, check_context=check_context) + + +def expect_raises_message_with_proper_context( + except_cls, msg, check_context=True +): + return _expect_raises(except_cls, msg=msg, check_context=check_context) diff --git a/python_embeded/Lib/site-packages/mako/testing/config.py b/python_embeded/Lib/site-packages/mako/testing/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b77d0c08084b0a9b1b5e7395e1bd54895ba689e6 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/config.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass +from pathlib import Path + +from ._config import ReadsCfg +from .helpers import make_path + + +@dataclass +class Config(ReadsCfg): + module_base: Path + template_base: Path + + section_header = "mako_testing" + converters = {Path: make_path} + + +config = Config.from_cfg_file("./setup.cfg") diff --git a/python_embeded/Lib/site-packages/mako/testing/exclusions.py b/python_embeded/Lib/site-packages/mako/testing/exclusions.py new file mode 100644 index 0000000000000000000000000000000000000000..37b2d14a395f5c27ed608955860471d597e2ae3d --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/exclusions.py @@ -0,0 +1,80 @@ +import pytest + +from mako.ext.beaker_cache import has_beaker +from mako.util import update_wrapper + + +try: + import babel.messages.extract as babel +except ImportError: + babel = None + + +try: + import lingua +except ImportError: + lingua = None + + +try: + import dogpile.cache # noqa +except ImportError: + has_dogpile_cache = False +else: + has_dogpile_cache = True + + +requires_beaker = pytest.mark.skipif( + not has_beaker, reason="Beaker is required for these tests." +) + + +requires_babel = pytest.mark.skipif( + babel is None, reason="babel not installed: skipping babelplugin test" +) + + +requires_lingua = pytest.mark.skipif( + lingua is None, reason="lingua not installed: skipping linguaplugin test" +) + + +requires_dogpile_cache = pytest.mark.skipif( + not has_dogpile_cache, + reason="dogpile.cache is required to run these tests", +) + + +def _pygments_version(): + try: + import pygments + + version = pygments.__version__ + except: + version = "0" + return version + + +requires_pygments_14 = pytest.mark.skipif( + _pygments_version() < "1.4", reason="Requires pygments 1.4 or greater" +) + + +# def requires_pygments_14(fn): + +# return skip_if( +# lambda: version < "1.4", "Requires pygments 1.4 or greater" +# )(fn) + + +def requires_no_pygments_exceptions(fn): + def go(*arg, **kw): + from mako import exceptions + + exceptions._install_fallback() + try: + return fn(*arg, **kw) + finally: + exceptions._install_highlighting() + + return update_wrapper(go, fn) diff --git a/python_embeded/Lib/site-packages/mako/testing/fixtures.py b/python_embeded/Lib/site-packages/mako/testing/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..01e996171d16be446ee849ceafafaf2cf699f256 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/fixtures.py @@ -0,0 +1,119 @@ +import os + +from mako.cache import CacheImpl +from mako.cache import register_plugin +from mako.template import Template +from .assertions import eq_ +from .config import config + + +class TemplateTest: + def _file_template(self, filename, **kw): + filepath = self._file_path(filename) + return Template( + uri=filename, + filename=filepath, + module_directory=config.module_base, + **kw, + ) + + def _file_path(self, filename): + name, ext = os.path.splitext(filename) + py3k_path = os.path.join(config.template_base, name + "_py3k" + ext) + if os.path.exists(py3k_path): + return py3k_path + + return os.path.join(config.template_base, filename) + + def _do_file_test( + self, + filename, + expected, + filters=None, + unicode_=True, + template_args=None, + **kw, + ): + t1 = self._file_template(filename, **kw) + self._do_test( + t1, + expected, + filters=filters, + unicode_=unicode_, + template_args=template_args, + ) + + def _do_memory_test( + self, + source, + expected, + filters=None, + unicode_=True, + template_args=None, + **kw, + ): + t1 = Template(text=source, **kw) + self._do_test( + t1, + expected, + filters=filters, + unicode_=unicode_, + template_args=template_args, + ) + + def _do_test( + self, + template, + expected, + filters=None, + template_args=None, + unicode_=True, + ): + if template_args is None: + template_args = {} + if unicode_: + output = template.render_unicode(**template_args) + else: + output = template.render(**template_args) + + if filters: + output = filters(output) + eq_(output, expected) + + def indicates_unbound_local_error(self, rendered_output, unbound_var): + var = f"'{unbound_var}'" + error_msgs = ( + # < 3.11 + f"local variable {var} referenced before assignment", + # >= 3.11 + f"cannot access local variable {var} where it is not associated", + ) + return any((msg in rendered_output) for msg in error_msgs) + + +class PlainCacheImpl(CacheImpl): + """Simple memory cache impl so that tests which + use caching can run without beaker.""" + + def __init__(self, cache): + self.cache = cache + self.data = {} + + def get_or_create(self, key, creation_function, **kw): + if key in self.data: + return self.data[key] + else: + self.data[key] = data = creation_function(**kw) + return data + + def put(self, key, value, **kw): + self.data[key] = value + + def get(self, key, **kw): + return self.data[key] + + def invalidate(self, key, **kw): + del self.data[key] + + +register_plugin("plain", __name__, "PlainCacheImpl") diff --git a/python_embeded/Lib/site-packages/mako/testing/helpers.py b/python_embeded/Lib/site-packages/mako/testing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae9d38d3d590d51cfe4486dab31589207a287d3 --- /dev/null +++ b/python_embeded/Lib/site-packages/mako/testing/helpers.py @@ -0,0 +1,71 @@ +import contextlib +import pathlib +from pathlib import Path +import re +import time +from typing import Union +from unittest import mock + + +def flatten_result(result): + return re.sub(r"[\s\r\n]+", " ", result).strip() + + +def result_lines(result): + return [ + x.strip() + for x in re.split(r"\r?\n", re.sub(r" +", " ", result)) + if x.strip() != "" + ] + + +def result_raw_lines(result): + return [x for x in re.split(r"\r?\n", result) if x.strip() != ""] + + +def make_path( + filespec: Union[Path, str], + make_absolute: bool = True, + check_exists: bool = False, +) -> Path: + path = Path(filespec) + if make_absolute: + path = path.resolve(strict=check_exists) + if check_exists and (not path.exists()): + raise FileNotFoundError(f"No file or directory at {filespec}") + return path + + +def _unlink_path(path, missing_ok=False): + # Replicate 3.8+ functionality in 3.7 + cm = contextlib.nullcontext() + if missing_ok: + cm = contextlib.suppress(FileNotFoundError) + + with cm: + path.unlink() + + +def replace_file_with_dir(pathspec): + path = pathlib.Path(pathspec) + _unlink_path(path, missing_ok=True) + path.mkdir(exist_ok=True) + return path + + +def file_with_template_code(filespec): + with open(filespec, "w") as f: + f.write( + """ +i am an artificial template just for you +""" + ) + return filespec + + +@contextlib.contextmanager +def rewind_compile_time(hours=1): + rewound = time.time() - (hours * 3_600) + with mock.patch("mako.codegen.time") as codegen_time: + codegen_time.time.return_value = rewound + yield diff --git a/python_embeded/Lib/site-packages/markdown_it/cli/__init__.py b/python_embeded/Lib/site-packages/markdown_it/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/markdown_it/cli/parse.py b/python_embeded/Lib/site-packages/markdown_it/cli/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..890d5de3e4bbe1c52d131fcafc5973d815ea9204 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/cli/parse.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +""" +CLI interface to markdown-it-py + +Parse one or more markdown files, convert each to HTML, and print to stdout. +""" +from __future__ import annotations + +import argparse +from collections.abc import Iterable, Sequence +import sys + +from markdown_it import __version__ +from markdown_it.main import MarkdownIt + +version_str = "markdown-it-py [version {}]".format(__version__) + + +def main(args: Sequence[str] | None = None) -> int: + namespace = parse_args(args) + if namespace.filenames: + convert(namespace.filenames) + else: + interactive() + return 0 + + +def convert(filenames: Iterable[str]) -> None: + for filename in filenames: + convert_file(filename) + + +def convert_file(filename: str) -> None: + """ + Parse a Markdown file and dump the output to stdout. + """ + try: + with open(filename, "r", encoding="utf8", errors="ignore") as fin: + rendered = MarkdownIt().render(fin.read()) + print(rendered, end="") + except OSError: + sys.stderr.write(f'Cannot open file "{filename}".\n') + sys.exit(1) + + +def interactive() -> None: + """ + Parse user input, dump to stdout, rinse and repeat. + Python REPL style. + """ + print_heading() + contents = [] + more = False + while True: + try: + prompt, more = ("... ", True) if more else (">>> ", True) + contents.append(input(prompt) + "\n") + except EOFError: + print("\n" + MarkdownIt().render("\n".join(contents)), end="") + more = False + contents = [] + except KeyboardInterrupt: + print("\nExiting.") + break + + +def parse_args(args: Sequence[str] | None) -> argparse.Namespace: + """Parse input CLI arguments.""" + parser = argparse.ArgumentParser( + description="Parse one or more markdown files, " + "convert each to HTML, and print to stdout", + # NOTE: Remember to update README.md w/ the output of `markdown-it -h` + epilog=( + f""" +Interactive: + + $ markdown-it + markdown-it-py [version {__version__}] (interactive) + Type Ctrl-D to complete input, or Ctrl-C to exit. + >>> # Example + ... > markdown *input* + ... +

Example

+
+

markdown input

+
+ +Batch: + + $ markdown-it README.md README.footer.md > index.html +""" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument("-v", "--version", action="version", version=version_str) + parser.add_argument( + "filenames", nargs="*", help="specify an optional list of files to convert" + ) + return parser.parse_args(args) + + +def print_heading() -> None: + print("{} (interactive)".format(version_str)) + print("Type Ctrl-D to complete input, or Ctrl-C to exit.") + + +if __name__ == "__main__": + exit_code = main(sys.argv[1:]) + sys.exit(exit_code) diff --git a/python_embeded/Lib/site-packages/markdown_it/common/__init__.py b/python_embeded/Lib/site-packages/markdown_it/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/markdown_it/common/entities.py b/python_embeded/Lib/site-packages/markdown_it/common/entities.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb2d343c2338de4232378bf98d6c034fbe808c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/common/entities.py @@ -0,0 +1,4 @@ +"""HTML5 entities map: { name -> characters }.""" +import html.entities + +entities = {name.rstrip(";"): chars for name, chars in html.entities.html5.items()} diff --git a/python_embeded/Lib/site-packages/markdown_it/common/html_blocks.py b/python_embeded/Lib/site-packages/markdown_it/common/html_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..8b199af336ede85a04b222ac4eeffd1c0ad6100c --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/common/html_blocks.py @@ -0,0 +1,68 @@ +"""List of valid html blocks names, according to commonmark spec +http://jgm.github.io/CommonMark/spec.html#html-blocks +""" + +block_names = [ + "address", + "article", + "aside", + "base", + "basefont", + "blockquote", + "body", + "caption", + "center", + "col", + "colgroup", + "dd", + "details", + "dialog", + "dir", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hr", + "html", + "iframe", + "legend", + "li", + "link", + "main", + "menu", + "menuitem", + "nav", + "noframes", + "ol", + "optgroup", + "option", + "p", + "param", + "section", + "source", + "summary", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "title", + "tr", + "track", + "ul", +] diff --git a/python_embeded/Lib/site-packages/markdown_it/common/html_re.py b/python_embeded/Lib/site-packages/markdown_it/common/html_re.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c336d23816db1376d0c779fc3de718181e4c9f --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/common/html_re.py @@ -0,0 +1,40 @@ +"""Regexps to match html elements +""" + +import re + +attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*" + +unquoted = "[^\"'=<>`\\x00-\\x20]+" +single_quoted = "'[^']*'" +double_quoted = '"[^"]*"' + +attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")" + +attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)" + +open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>" + +close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>" +comment = "|" +processing = "<[?][\\s\\S]*?[?]>" +declaration = "]*>" +cdata = "" + +HTML_TAG_RE = re.compile( + "^(?:" + + open_tag + + "|" + + close_tag + + "|" + + comment + + "|" + + processing + + "|" + + declaration + + "|" + + cdata + + ")" +) +HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")" +HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR) diff --git a/python_embeded/Lib/site-packages/markdown_it/common/normalize_url.py b/python_embeded/Lib/site-packages/markdown_it/common/normalize_url.py new file mode 100644 index 0000000000000000000000000000000000000000..92720b31621b0f6b4ac853179d886cb58e4e2f36 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/common/normalize_url.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable +from contextlib import suppress +import re +from urllib.parse import quote, unquote, urlparse, urlunparse # noqa: F401 + +import mdurl + +from .. import _punycode + +RECODE_HOSTNAME_FOR = ("http:", "https:", "mailto:") + + +def normalizeLink(url: str) -> str: + """Normalize destination URLs in links + + :: + + [label]: destination 'title' + ^^^^^^^^^^^ + """ + parsed = mdurl.parse(url, slashes_denote_host=True) + + # Encode hostnames in urls like: + # `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + # + # We don't encode unknown schemas, because it's likely that we encode + # something we shouldn't (e.g. `skype:name` treated as `skype:host`) + # + if parsed.hostname and ( + not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR + ): + with suppress(Exception): + parsed = parsed._replace(hostname=_punycode.to_ascii(parsed.hostname)) + + return mdurl.encode(mdurl.format(parsed)) + + +def normalizeLinkText(url: str) -> str: + """Normalize autolink content + + :: + + + ~~~~~~~~~~~ + """ + parsed = mdurl.parse(url, slashes_denote_host=True) + + # Encode hostnames in urls like: + # `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + # + # We don't encode unknown schemas, because it's likely that we encode + # something we shouldn't (e.g. `skype:name` treated as `skype:host`) + # + if parsed.hostname and ( + not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR + ): + with suppress(Exception): + parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname)) + + # add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 + return mdurl.decode(mdurl.format(parsed), mdurl.DECODE_DEFAULT_CHARS + "%") + + +BAD_PROTO_RE = re.compile(r"^(vbscript|javascript|file|data):") +GOOD_DATA_RE = re.compile(r"^data:image\/(gif|png|jpeg|webp);") + + +def validateLink(url: str, validator: Callable[[str], bool] | None = None) -> bool: + """Validate URL link is allowed in output. + + This validator can prohibit more than really needed to prevent XSS. + It's a tradeoff to keep code simple and to be secure by default. + + Note: url should be normalized at this point, and existing entities decoded. + """ + if validator is not None: + return validator(url) + url = url.strip().lower() + return bool(GOOD_DATA_RE.search(url)) if BAD_PROTO_RE.search(url) else True diff --git a/python_embeded/Lib/site-packages/markdown_it/common/utils.py b/python_embeded/Lib/site-packages/markdown_it/common/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0d11e3e3eec312779e4c98fd2e6e492b9f7bd24c --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/common/utils.py @@ -0,0 +1,318 @@ +"""Utilities for parsing source text +""" +from __future__ import annotations + +import re +from typing import Match, TypeVar + +from .entities import entities + + +def charCodeAt(src: str, pos: int) -> int | None: + """ + Returns the Unicode value of the character at the specified location. + + @param - index The zero-based index of the desired character. + If there is no character at the specified index, NaN is returned. + + This was added for compatibility with python + """ + try: + return ord(src[pos]) + except IndexError: + return None + + +def charStrAt(src: str, pos: int) -> str | None: + """ + Returns the Unicode value of the character at the specified location. + + @param - index The zero-based index of the desired character. + If there is no character at the specified index, NaN is returned. + + This was added for compatibility with python + """ + try: + return src[pos] + except IndexError: + return None + + +_ItemTV = TypeVar("_ItemTV") + + +def arrayReplaceAt( + src: list[_ItemTV], pos: int, newElements: list[_ItemTV] +) -> list[_ItemTV]: + """ + Remove element from array and put another array at those position. + Useful for some operations with tokens + """ + return src[:pos] + newElements + src[pos + 1 :] + + +def isValidEntityCode(c: int) -> bool: + # broken sequence + if c >= 0xD800 and c <= 0xDFFF: + return False + # never used + if c >= 0xFDD0 and c <= 0xFDEF: + return False + if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE): + return False + # control codes + if c >= 0x00 and c <= 0x08: + return False + if c == 0x0B: + return False + if c >= 0x0E and c <= 0x1F: + return False + if c >= 0x7F and c <= 0x9F: + return False + # out of range + if c > 0x10FFFF: + return False + return True + + +def fromCodePoint(c: int) -> str: + """Convert ordinal to unicode. + + Note, in the original Javascript two string characters were required, + for codepoints larger than `0xFFFF`. + But Python 3 can represent any unicode codepoint in one character. + """ + return chr(c) + + +# UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])') +# ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE) +UNESCAPE_ALL_RE = re.compile( + r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});", + re.IGNORECASE, +) +DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})") +DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE) + + +def replaceEntityPattern(match: str, name: str) -> str: + """Convert HTML entity patterns, + see https://spec.commonmark.org/0.30/#entity-references + """ + if name in entities: + return entities[name] + + code: None | int = None + if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name): + code = int(pat.group(1), 10) + elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name): + code = int(pat.group(1), 16) + + if code is not None and isValidEntityCode(code): + return fromCodePoint(code) + + return match + + +def unescapeAll(string: str) -> str: + def replacer_func(match: Match[str]) -> str: + escaped = match.group(1) + if escaped: + return escaped + entity = match.group(2) + return replaceEntityPattern(match.group(), entity) + + if "\\" not in string and "&" not in string: + return string + return UNESCAPE_ALL_RE.sub(replacer_func, string) + + +ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-""" +ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])") + + +def stripEscape(string: str) -> str: + """Strip escape \\ characters""" + return ESCAPE_CHAR.sub(r"\1", string) + + +def escapeHtml(raw: str) -> str: + """Replace special characters "&", "<", ">" and '"' to HTML-safe sequences.""" + # like html.escape, but without escaping single quotes + raw = raw.replace("&", "&") # Must be done first! + raw = raw.replace("<", "<") + raw = raw.replace(">", ">") + raw = raw.replace('"', """) + return raw + + +# ////////////////////////////////////////////////////////////////////////////// + +REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]") + + +def escapeRE(string: str) -> str: + string = REGEXP_ESCAPE_RE.sub("\\$&", string) + return string + + +# ////////////////////////////////////////////////////////////////////////////// + + +def isSpace(code: int | None) -> bool: + """Check if character code is a whitespace.""" + return code in (0x09, 0x20) + + +def isStrSpace(ch: str | None) -> bool: + """Check if character is a whitespace.""" + return ch in ("\t", " ") + + +MD_WHITESPACE = { + 0x09, # \t + 0x0A, # \n + 0x0B, # \v + 0x0C, # \f + 0x0D, # \r + 0x20, # space + 0xA0, + 0x1680, + 0x202F, + 0x205F, + 0x3000, +} + + +def isWhiteSpace(code: int) -> bool: + r"""Zs (unicode class) || [\t\f\v\r\n]""" + if code >= 0x2000 and code <= 0x200A: + return True + return code in MD_WHITESPACE + + +# ////////////////////////////////////////////////////////////////////////////// + +UNICODE_PUNCT_RE = re.compile( + r"[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]" # noqa: E501 +) + + +# Currently without astral characters support. +def isPunctChar(ch: str) -> bool: + """Check if character is a punctuation character.""" + return UNICODE_PUNCT_RE.search(ch) is not None + + +MD_ASCII_PUNCT = { + 0x21, # /* ! */ + 0x22, # /* " */ + 0x23, # /* # */ + 0x24, # /* $ */ + 0x25, # /* % */ + 0x26, # /* & */ + 0x27, # /* ' */ + 0x28, # /* ( */ + 0x29, # /* ) */ + 0x2A, # /* * */ + 0x2B, # /* + */ + 0x2C, # /* , */ + 0x2D, # /* - */ + 0x2E, # /* . */ + 0x2F, # /* / */ + 0x3A, # /* : */ + 0x3B, # /* ; */ + 0x3C, # /* < */ + 0x3D, # /* = */ + 0x3E, # /* > */ + 0x3F, # /* ? */ + 0x40, # /* @ */ + 0x5B, # /* [ */ + 0x5C, # /* \ */ + 0x5D, # /* ] */ + 0x5E, # /* ^ */ + 0x5F, # /* _ */ + 0x60, # /* ` */ + 0x7B, # /* { */ + 0x7C, # /* | */ + 0x7D, # /* } */ + 0x7E, # /* ~ */ +} + + +def isMdAsciiPunct(ch: int) -> bool: + """Markdown ASCII punctuation characters. + + :: + + !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~ + + See http://spec.commonmark.org/0.15/#ascii-punctuation-character + + Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. + + """ # noqa: E501 + return ch in MD_ASCII_PUNCT + + +def normalizeReference(string: str) -> str: + """Helper to unify [reference labels].""" + # Trim and collapse whitespace + # + string = re.sub(r"\s+", " ", string.strip()) + + # In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug + # fixed in v12 (couldn't find any details). + # + # So treat this one as a special case + # (remove this when node v10 is no longer supported). + # + # if ('ẞ'.toLowerCase() === 'Ṿ') { + # str = str.replace(/ẞ/g, 'ß') + # } + + # .toLowerCase().toUpperCase() should get rid of all differences + # between letter variants. + # + # Simple .toLowerCase() doesn't normalize 125 code points correctly, + # and .toUpperCase doesn't normalize 6 of them (list of exceptions: + # İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently + # uppercased versions). + # + # Here's an example showing how it happens. Lets take greek letter omega: + # uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) + # + # Unicode entries: + # 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8 + # 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 + # 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 + # 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8 + # + # Case-insensitive comparison should treat all of them as equivalent. + # + # But .toLowerCase() doesn't change ϑ (it's already lowercase), + # and .toUpperCase() doesn't change ϴ (already uppercase). + # + # Applying first lower then upper case normalizes any character: + # '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' + # + # Note: this is equivalent to unicode case folding; unicode normalization + # is a different step that is not required here. + # + # Final result should be uppercased, because it's later stored in an object + # (this avoid a conflict with Object.prototype members, + # most notably, `__proto__`) + # + return string.lower().upper() + + +LINK_OPEN_RE = re.compile(r"^\s]", flags=re.IGNORECASE) +LINK_CLOSE_RE = re.compile(r"^", flags=re.IGNORECASE) + + +def isLinkOpen(string: str) -> bool: + return bool(LINK_OPEN_RE.search(string)) + + +def isLinkClose(string: str) -> bool: + return bool(LINK_CLOSE_RE.search(string)) diff --git a/python_embeded/Lib/site-packages/markdown_it/helpers/__init__.py b/python_embeded/Lib/site-packages/markdown_it/helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3dbbdd1d480ecc5ace6529f9005d40d5985529ae --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/helpers/__init__.py @@ -0,0 +1,6 @@ +"""Functions for parsing Links +""" +__all__ = ("parseLinkLabel", "parseLinkDestination", "parseLinkTitle") +from .parse_link_destination import parseLinkDestination +from .parse_link_label import parseLinkLabel +from .parse_link_title import parseLinkTitle diff --git a/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_destination.py b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_destination.py new file mode 100644 index 0000000000000000000000000000000000000000..f42b2244db531bab0606607820ab165a161ce255 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_destination.py @@ -0,0 +1,86 @@ +""" +Parse link destination +""" + +from ..common.utils import charCodeAt, unescapeAll + + +class _Result: + __slots__ = ("ok", "pos", "lines", "str") + + def __init__(self) -> None: + self.ok = False + self.pos = 0 + self.lines = 0 + self.str = "" + + +def parseLinkDestination(string: str, pos: int, maximum: int) -> _Result: + lines = 0 + start = pos + result = _Result() + + if charCodeAt(string, pos) == 0x3C: # /* < */ + pos += 1 + while pos < maximum: + code = charCodeAt(string, pos) + if code == 0x0A: # /* \n */) + return result + if code == 0x3C: # / * < * / + return result + if code == 0x3E: # /* > */) { + result.pos = pos + 1 + result.str = unescapeAll(string[start + 1 : pos]) + result.ok = True + return result + + if code == 0x5C and pos + 1 < maximum: # \ + pos += 2 + continue + + pos += 1 + + # no closing '>' + return result + + # this should be ... } else { ... branch + + level = 0 + while pos < maximum: + code = charCodeAt(string, pos) + + if code is None or code == 0x20: + break + + # ascii control characters + if code < 0x20 or code == 0x7F: + break + + if code == 0x5C and pos + 1 < maximum: + if charCodeAt(string, pos + 1) == 0x20: + break + pos += 2 + continue + + if code == 0x28: # /* ( */) + level += 1 + if level > 32: + return result + + if code == 0x29: # /* ) */) + if level == 0: + break + level -= 1 + + pos += 1 + + if start == pos: + return result + if level != 0: + return result + + result.str = unescapeAll(string[start:pos]) + result.lines = lines + result.pos = pos + result.ok = True + return result diff --git a/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_label.py b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_label.py new file mode 100644 index 0000000000000000000000000000000000000000..01c653c56be8a10a6018e8b18ad64af2542ed1ac --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_label.py @@ -0,0 +1,43 @@ +""" +Parse link label + +this function assumes that first character ("[") already matches +returns the end of the label + +""" +from markdown_it.rules_inline import StateInline + + +def parseLinkLabel(state: StateInline, start: int, disableNested: bool = False) -> int: + labelEnd = -1 + oldPos = state.pos + found = False + + state.pos = start + 1 + level = 1 + + while state.pos < state.posMax: + marker = state.src[state.pos] + if marker == "]": + level -= 1 + if level == 0: + found = True + break + + prevPos = state.pos + state.md.inline.skipToken(state) + if marker == "[": + if prevPos == state.pos - 1: + # increase level if we find text `[`, + # which is not a part of any token + level += 1 + elif disableNested: + state.pos = oldPos + return -1 + if found: + labelEnd = state.pos + + # restore old state + state.pos = oldPos + + return labelEnd diff --git a/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_title.py b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_title.py new file mode 100644 index 0000000000000000000000000000000000000000..8f589336f60ea16a7fdf73c023cad2e5092d58e3 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/helpers/parse_link_title.py @@ -0,0 +1,60 @@ +"""Parse link title +""" +from ..common.utils import charCodeAt, unescapeAll + + +class _Result: + __slots__ = ("ok", "pos", "lines", "str") + + def __init__(self) -> None: + self.ok = False + self.pos = 0 + self.lines = 0 + self.str = "" + + def __str__(self) -> str: + return self.str + + +def parseLinkTitle(string: str, pos: int, maximum: int) -> _Result: + lines = 0 + start = pos + result = _Result() + + if pos >= maximum: + return result + + marker = charCodeAt(string, pos) + + # /* " */ /* ' */ /* ( */ + if marker != 0x22 and marker != 0x27 and marker != 0x28: + return result + + pos += 1 + + # if opening marker is "(", switch it to closing marker ")" + if marker == 0x28: + marker = 0x29 + + while pos < maximum: + code = charCodeAt(string, pos) + if code == marker: + title = string[start + 1 : pos] + title = unescapeAll(title) + result.pos = pos + 1 + result.lines = lines + result.str = title + result.ok = True + return result + elif code == 0x28 and marker == 0x29: # /* ( */ /* ) */ + return result + elif code == 0x0A: + lines += 1 + elif code == 0x5C and pos + 1 < maximum: # /* \ */ + pos += 1 + if charCodeAt(string, pos) == 0x0A: + lines += 1 + + pos += 1 + + return result diff --git a/python_embeded/Lib/site-packages/markdown_it/presets/__init__.py b/python_embeded/Lib/site-packages/markdown_it/presets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6796a2d29eb524c5f35df79055d0969fca02ba --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/presets/__init__.py @@ -0,0 +1,28 @@ +__all__ = ("commonmark", "default", "zero", "js_default", "gfm_like") + +from . import commonmark, default, zero +from ..utils import PresetType + +js_default = default + + +class gfm_like: # noqa: N801 + """GitHub Flavoured Markdown (GFM) like. + + This adds the linkify, table and strikethrough components to CommmonMark. + + Note, it lacks task-list items and raw HTML filtering, + to meet the the full GFM specification + (see https://github.github.com/gfm/#autolinks-extension-). + """ + + @staticmethod + def make() -> PresetType: + config = commonmark.make() + config["components"]["core"]["rules"].append("linkify") + config["components"]["block"]["rules"].append("table") + config["components"]["inline"]["rules"].extend(["strikethrough", "linkify"]) + config["components"]["inline"]["rules2"].append("strikethrough") + config["options"]["linkify"] = True + config["options"]["html"] = True + return config diff --git a/python_embeded/Lib/site-packages/markdown_it/presets/commonmark.py b/python_embeded/Lib/site-packages/markdown_it/presets/commonmark.py new file mode 100644 index 0000000000000000000000000000000000000000..3990d4344aeb9e07449acf8aa749cb27b0a0e66c --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/presets/commonmark.py @@ -0,0 +1,74 @@ +"""Commonmark default options. + +This differs to presets.default, +primarily in that it allows HTML and does not enable components: + +- block: table +- inline: strikethrough +""" +from ..utils import PresetType + + +def make() -> PresetType: + return { + "options": { + "maxNesting": 20, # Internal protection, recursion limit + "html": True, # Enable HTML tags in source, + # this is just a shorthand for .enable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": True, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with PresetType: + return { + "options": { + "maxNesting": 100, # Internal protection, recursion limit + "html": False, # Enable HTML tags in source + # this is just a shorthand for .disable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules: + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": False, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with PresetType: + return { + "options": { + "maxNesting": 20, # Internal protection, recursion limit + "html": False, # Enable HTML tags in source + # this is just a shorthand for .disable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules: + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": False, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with bool: + LOGGER.debug( + "entering blockquote: %s, %s, %s, %s", state, startLine, endLine, silent + ) + + oldLineMax = state.lineMax + pos = state.bMarks[startLine] + state.tShift[startLine] + max = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + # check the block quote marker + try: + if state.src[pos] != ">": + return False + except IndexError: + return False + pos += 1 + + # we know that it's going to be a valid blockquote, + # so no point trying to find the end of it in silent mode + if silent: + return True + + # set offset past spaces and ">" + initial = offset = state.sCount[startLine] + 1 + + try: + second_char: str | None = state.src[pos] + except IndexError: + second_char = None + + # skip one optional space after '>' + if second_char == " ": + # ' > test ' + # ^ -- position start of line here: + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + spaceAfterMarker = True + elif second_char == "\t": + spaceAfterMarker = True + + if (state.bsCount[startLine] + offset) % 4 == 3: + # ' >\t test ' + # ^ -- position start of line here (tab has width==1) + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + else: + # ' >\t test ' + # ^ -- position start of line here + shift bsCount slightly + # to make extra space appear + adjustTab = True + + else: + spaceAfterMarker = False + + oldBMarks = [state.bMarks[startLine]] + state.bMarks[startLine] = pos + + while pos < max: + ch = state.src[pos] + + if isStrSpace(ch): + if ch == "\t": + offset += ( + 4 + - (offset + state.bsCount[startLine] + (1 if adjustTab else 0)) % 4 + ) + else: + offset += 1 + + else: + break + + pos += 1 + + oldBSCount = [state.bsCount[startLine]] + state.bsCount[startLine] = ( + state.sCount[startLine] + 1 + (1 if spaceAfterMarker else 0) + ) + + lastLineEmpty = pos >= max + + oldSCount = [state.sCount[startLine]] + state.sCount[startLine] = offset - initial + + oldTShift = [state.tShift[startLine]] + state.tShift[startLine] = pos - state.bMarks[startLine] + + terminatorRules = state.md.block.ruler.getRules("blockquote") + + oldParentType = state.parentType + state.parentType = "blockquote" + + # Search the end of the block + # + # Block ends with either: + # 1. an empty line outside: + # ``` + # > test + # + # ``` + # 2. an empty line inside: + # ``` + # > + # test + # ``` + # 3. another tag: + # ``` + # > test + # - - - + # ``` + + # for (nextLine = startLine + 1; nextLine < endLine; nextLine++) { + nextLine = startLine + 1 + while nextLine < endLine: + # check if it's outdented, i.e. it's inside list item and indented + # less than said list item: + # + # ``` + # 1. anything + # > current blockquote + # 2. checking this line + # ``` + isOutdented = state.sCount[nextLine] < state.blkIndent + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + max = state.eMarks[nextLine] + + if pos >= max: + # Case 1: line is not inside the blockquote, and this line is empty. + break + + evaluatesTrue = state.src[pos] == ">" and not isOutdented + pos += 1 + if evaluatesTrue: + # This line is inside the blockquote. + + # set offset past spaces and ">" + initial = offset = state.sCount[nextLine] + 1 + + try: + next_char: str | None = state.src[pos] + except IndexError: + next_char = None + + # skip one optional space after '>' + if next_char == " ": + # ' > test ' + # ^ -- position start of line here: + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + spaceAfterMarker = True + elif next_char == "\t": + spaceAfterMarker = True + + if (state.bsCount[nextLine] + offset) % 4 == 3: + # ' >\t test ' + # ^ -- position start of line here (tab has width==1) + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + else: + # ' >\t test ' + # ^ -- position start of line here + shift bsCount slightly + # to make extra space appear + adjustTab = True + + else: + spaceAfterMarker = False + + oldBMarks.append(state.bMarks[nextLine]) + state.bMarks[nextLine] = pos + + while pos < max: + ch = state.src[pos] + + if isStrSpace(ch): + if ch == "\t": + offset += ( + 4 + - ( + offset + + state.bsCount[nextLine] + + (1 if adjustTab else 0) + ) + % 4 + ) + else: + offset += 1 + else: + break + + pos += 1 + + lastLineEmpty = pos >= max + + oldBSCount.append(state.bsCount[nextLine]) + state.bsCount[nextLine] = ( + state.sCount[nextLine] + 1 + (1 if spaceAfterMarker else 0) + ) + + oldSCount.append(state.sCount[nextLine]) + state.sCount[nextLine] = offset - initial + + oldTShift.append(state.tShift[nextLine]) + state.tShift[nextLine] = pos - state.bMarks[nextLine] + + nextLine += 1 + continue + + # Case 2: line is not inside the blockquote, and the last line was empty. + if lastLineEmpty: + break + + # Case 3: another tag found. + terminate = False + + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + # Quirk to enforce "hard termination mode" for paragraphs; + # normally if you call `tokenize(state, startLine, nextLine)`, + # paragraphs will look below nextLine for paragraph continuation, + # but if blockquote is terminated by another tag, they shouldn't + state.lineMax = nextLine + + if state.blkIndent != 0: + # state.blkIndent was non-zero, we now set it to zero, + # so we need to re-calculate all offsets to appear as + # if indent wasn't changed + oldBMarks.append(state.bMarks[nextLine]) + oldBSCount.append(state.bsCount[nextLine]) + oldTShift.append(state.tShift[nextLine]) + oldSCount.append(state.sCount[nextLine]) + state.sCount[nextLine] -= state.blkIndent + + break + + oldBMarks.append(state.bMarks[nextLine]) + oldBSCount.append(state.bsCount[nextLine]) + oldTShift.append(state.tShift[nextLine]) + oldSCount.append(state.sCount[nextLine]) + + # A negative indentation means that this is a paragraph continuation + # + state.sCount[nextLine] = -1 + + nextLine += 1 + + oldIndent = state.blkIndent + state.blkIndent = 0 + + token = state.push("blockquote_open", "blockquote", 1) + token.markup = ">" + token.map = lines = [startLine, 0] + + state.md.block.tokenize(state, startLine, nextLine) + + token = state.push("blockquote_close", "blockquote", -1) + token.markup = ">" + + state.lineMax = oldLineMax + state.parentType = oldParentType + lines[1] = state.line + + # Restore original tShift; this might not be necessary since the parser + # has already been here, but just to make sure we can do that. + for i, item in enumerate(oldTShift): + state.bMarks[i + startLine] = oldBMarks[i] + state.tShift[i + startLine] = item + state.sCount[i + startLine] = oldSCount[i] + state.bsCount[i + startLine] = oldBSCount[i] + + state.blkIndent = oldIndent + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/code.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/code.py new file mode 100644 index 0000000000000000000000000000000000000000..89db9cec4e0fda2798446940397a965a2083f1a3 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/code.py @@ -0,0 +1,35 @@ +"""Code block (4 spaces padded).""" +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent) + + if not state.is_code_block(startLine): + return False + + last = nextLine = startLine + 1 + + while nextLine < endLine: + if state.isEmpty(nextLine): + nextLine += 1 + continue + + if state.is_code_block(nextLine): + nextLine += 1 + last = nextLine + continue + + break + + state.line = last + + token = state.push("code_block", "code", 0) + token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n" + token.map = [startLine, state.line] + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/fence.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/fence.py new file mode 100644 index 0000000000000000000000000000000000000000..263f1b8de8dcdd0dd736eeafab2d9da34ec2c205 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/fence.py @@ -0,0 +1,101 @@ +# fences (``` lang, ~~~ lang) +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def fence(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering fence: %s, %s, %s, %s", state, startLine, endLine, silent) + + haveEndMarker = False + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + if pos + 3 > maximum: + return False + + marker = state.src[pos] + + if marker not in ("~", "`"): + return False + + # scan marker length + mem = pos + pos = state.skipCharsStr(pos, marker) + + length = pos - mem + + if length < 3: + return False + + markup = state.src[mem:pos] + params = state.src[pos:maximum] + + if marker == "`" and marker in params: + return False + + # Since start is found, we can report success here in validation mode + if silent: + return True + + # search end of block + nextLine = startLine + + while True: + nextLine += 1 + if nextLine >= endLine: + # unclosed block should be autoclosed by end of document. + # also block seems to be autoclosed by end of parent + break + + pos = mem = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + if pos < maximum and state.sCount[nextLine] < state.blkIndent: + # non-empty line with negative indent should stop the list: + # - ``` + # test + break + + try: + if state.src[pos] != marker: + continue + except IndexError: + break + + if state.is_code_block(nextLine): + continue + + pos = state.skipCharsStr(pos, marker) + + # closing code fence must be at least as long as the opening one + if pos - mem < length: + continue + + # make sure tail has spaces only + pos = state.skipSpaces(pos) + + if pos < maximum: + continue + + haveEndMarker = True + # found! + break + + # If a fence has heading spaces, they should be removed from its inner block + length = state.sCount[startLine] + + state.line = nextLine + (1 if haveEndMarker else 0) + + token = state.push("fence", "code", 0) + token.info = params + token.content = state.getLines(startLine + 1, nextLine, length, True) + token.markup = markup + token.map = [startLine, state.line] + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/heading.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/heading.py new file mode 100644 index 0000000000000000000000000000000000000000..850ffb504d1b1aa0198672573ec61ff3ab3d0ed7 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/heading.py @@ -0,0 +1,68 @@ +""" Atex heading (#, ##, ...) """ +from __future__ import annotations + +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering heading: %s, %s, %s, %s", state, startLine, endLine, silent) + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + ch: str | None = state.src[pos] + + if ch != "#" or pos >= maximum: + return False + + # count heading level + level = 1 + pos += 1 + try: + ch = state.src[pos] + except IndexError: + ch = None + while ch == "#" and pos < maximum and level <= 6: + level += 1 + pos += 1 + try: + ch = state.src[pos] + except IndexError: + ch = None + + if level > 6 or (pos < maximum and not isStrSpace(ch)): + return False + + if silent: + return True + + # Let's cut tails like ' ### ' from the end of string + + maximum = state.skipSpacesBack(maximum, pos) + tmp = state.skipCharsStrBack(maximum, "#", pos) + if tmp > pos and isStrSpace(state.src[tmp - 1]): + maximum = tmp + + state.line = startLine + 1 + + token = state.push("heading_open", "h" + str(level), 1) + token.markup = "########"[:level] + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = state.src[pos:maximum].strip() + token.map = [startLine, state.line] + token.children = [] + + token = state.push("heading_close", "h" + str(level), -1) + token.markup = "########"[:level] + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/hr.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/hr.py new file mode 100644 index 0000000000000000000000000000000000000000..16df05f2ab2e9e171b4f3f5612bba62aab78b2a3 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/hr.py @@ -0,0 +1,55 @@ +"""Horizontal rule + +At least 3 of these characters on a line * - _ +""" +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent) + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + try: + marker = state.src[pos] + except IndexError: + return False + pos += 1 + + # Check hr marker + if marker not in ("*", "-", "_"): + return False + + # markers can be mixed with spaces, but there should be at least 3 of them + + cnt = 1 + while pos < maximum: + ch = state.src[pos] + pos += 1 + if ch != marker and not isStrSpace(ch): + return False + if ch == marker: + cnt += 1 + + if cnt < 3: + return False + + if silent: + return True + + state.line = startLine + 1 + + token = state.push("hr", "hr", 0) + token.map = [startLine, state.line] + token.markup = marker * (cnt + 1) + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/html_block.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/html_block.py new file mode 100644 index 0000000000000000000000000000000000000000..3d43f6ee1deb527a42f4d99da40bd052d9b02886 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/html_block.py @@ -0,0 +1,90 @@ +# HTML block +from __future__ import annotations + +import logging +import re + +from ..common.html_blocks import block_names +from ..common.html_re import HTML_OPEN_CLOSE_TAG_STR +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + +# An array of opening and corresponding closing sequences for html tags, +# last argument defines whether it can terminate a paragraph or not +HTML_SEQUENCES: list[tuple[re.Pattern[str], re.Pattern[str], bool]] = [ + ( + re.compile(r"^<(script|pre|style|textarea)(?=(\s|>|$))", re.IGNORECASE), + re.compile(r"<\/(script|pre|style|textarea)>", re.IGNORECASE), + True, + ), + (re.compile(r"^"), True), + (re.compile(r"^<\?"), re.compile(r"\?>"), True), + (re.compile(r"^"), True), + (re.compile(r"^"), True), + ( + re.compile("^|$))", re.IGNORECASE), + re.compile(r"^$"), + True, + ), + (re.compile(HTML_OPEN_CLOSE_TAG_STR + "\\s*$"), re.compile(r"^$"), False), +] + + +def html_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering html_block: %s, %s, %s, %s", state, startLine, endLine, silent + ) + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + if not state.md.options.get("html", None): + return False + + if state.src[pos] != "<": + return False + + lineText = state.src[pos:maximum] + + html_seq = None + for HTML_SEQUENCE in HTML_SEQUENCES: + if HTML_SEQUENCE[0].search(lineText): + html_seq = HTML_SEQUENCE + break + + if not html_seq: + return False + + if silent: + # true if this sequence can be a terminator, false otherwise + return html_seq[2] + + nextLine = startLine + 1 + + # If we are here - we detected HTML block. + # Let's roll down till block end. + if not html_seq[1].search(lineText): + while nextLine < endLine: + if state.sCount[nextLine] < state.blkIndent: + break + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + lineText = state.src[pos:maximum] + + if html_seq[1].search(lineText): + if len(lineText) != 0: + nextLine += 1 + break + nextLine += 1 + + state.line = nextLine + + token = state.push("html_block", "", 0) + token.map = [startLine, nextLine] + token.content = state.getLines(startLine, nextLine, state.blkIndent, True) + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/lheading.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/lheading.py new file mode 100644 index 0000000000000000000000000000000000000000..3522207abb680510decdd6c54d0be81401128ad7 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/lheading.py @@ -0,0 +1,86 @@ +# lheading (---, ==) +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent) + + level = None + nextLine = startLine + 1 + ruler = state.md.block.ruler + terminatorRules = ruler.getRules("paragraph") + + if state.is_code_block(startLine): + return False + + oldParentType = state.parentType + state.parentType = "paragraph" # use paragraph to match terminatorRules + + # jump line-by-line until empty one or EOF + while nextLine < endLine and not state.isEmpty(nextLine): + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.sCount[nextLine] - state.blkIndent > 3: + nextLine += 1 + continue + + # Check for underline in setext header + if state.sCount[nextLine] >= state.blkIndent: + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + if pos < maximum: + marker = state.src[pos] + + if marker in ("-", "="): + pos = state.skipCharsStr(pos, marker) + pos = state.skipSpaces(pos) + + # /* = */ + if pos >= maximum: + level = 1 if marker == "=" else 2 + break + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + nextLine += 1 + continue + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + if terminate: + break + + nextLine += 1 + + if not level: + # Didn't find valid underline + return False + + content = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + + state.line = nextLine + 1 + + token = state.push("heading_open", "h" + str(level), 1) + token.markup = marker + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = content + token.map = [startLine, state.line - 1] + token.children = [] + + token = state.push("heading_close", "h" + str(level), -1) + token.markup = marker + + state.parentType = oldParentType + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/list.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/list.py new file mode 100644 index 0000000000000000000000000000000000000000..d8070d747035dd6b43f11c4bd88d05533b22bc5b --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/list.py @@ -0,0 +1,345 @@ +# Lists +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +# Search `[-+*][\n ]`, returns next pos after marker on success +# or -1 on fail. +def skipBulletListMarker(state: StateBlock, startLine: int) -> int: + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + try: + marker = state.src[pos] + except IndexError: + return -1 + pos += 1 + + if marker not in ("*", "-", "+"): + return -1 + + if pos < maximum: + ch = state.src[pos] + + if not isStrSpace(ch): + # " -test " - is not a list item + return -1 + + return pos + + +# Search `\d+[.)][\n ]`, returns next pos after marker on success +# or -1 on fail. +def skipOrderedListMarker(state: StateBlock, startLine: int) -> int: + start = state.bMarks[startLine] + state.tShift[startLine] + pos = start + maximum = state.eMarks[startLine] + + # List marker should have at least 2 chars (digit + dot) + if pos + 1 >= maximum: + return -1 + + ch = state.src[pos] + pos += 1 + + ch_ord = ord(ch) + # /* 0 */ /* 9 */ + if ch_ord < 0x30 or ch_ord > 0x39: + return -1 + + while True: + # EOL -> fail + if pos >= maximum: + return -1 + + ch = state.src[pos] + pos += 1 + + # /* 0 */ /* 9 */ + ch_ord = ord(ch) + if ch_ord >= 0x30 and ch_ord <= 0x39: + # List marker should have no more than 9 digits + # (prevents integer overflow in browsers) + if pos - start >= 10: + return -1 + + continue + + # found valid marker + if ch in (")", "."): + break + + return -1 + + if pos < maximum: + ch = state.src[pos] + + if not isStrSpace(ch): + # " 1.test " - is not a list item + return -1 + + return pos + + +def markTightParagraphs(state: StateBlock, idx: int) -> None: + level = state.level + 2 + + i = idx + 2 + length = len(state.tokens) - 2 + while i < length: + if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open": + state.tokens[i + 2].hidden = True + state.tokens[i].hidden = True + i += 2 + i += 1 + + +def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent) + + isTerminatingParagraph = False + tight = True + + if state.is_code_block(startLine): + return False + + # Special case: + # - item 1 + # - item 2 + # - item 3 + # - item 4 + # - this one is a paragraph continuation + if ( + state.listIndent >= 0 + and state.sCount[startLine] - state.listIndent >= 4 + and state.sCount[startLine] < state.blkIndent + ): + return False + + # limit conditions when list can interrupt + # a paragraph (validation mode only) + # Next list item should still terminate previous list item + # + # This code can fail if plugins use blkIndent as well as lists, + # but I hope the spec gets fixed long before that happens. + # + if ( + silent + and state.parentType == "paragraph" + and state.sCount[startLine] >= state.blkIndent + ): + isTerminatingParagraph = True + + # Detect list type and position after marker + posAfterMarker = skipOrderedListMarker(state, startLine) + if posAfterMarker >= 0: + isOrdered = True + start = state.bMarks[startLine] + state.tShift[startLine] + markerValue = int(state.src[start : posAfterMarker - 1]) + + # If we're starting a new ordered list right after + # a paragraph, it should start with 1. + if isTerminatingParagraph and markerValue != 1: + return False + else: + posAfterMarker = skipBulletListMarker(state, startLine) + if posAfterMarker >= 0: + isOrdered = False + else: + return False + + # If we're starting a new unordered list right after + # a paragraph, first line should not be empty. + if ( + isTerminatingParagraph + and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine] + ): + return False + + # We should terminate list on style change. Remember first one to compare. + markerChar = state.src[posAfterMarker - 1] + + # For validation mode we can terminate immediately + if silent: + return True + + # Start list + listTokIdx = len(state.tokens) + + if isOrdered: + token = state.push("ordered_list_open", "ol", 1) + if markerValue != 1: + token.attrs = {"start": markerValue} + + else: + token = state.push("bullet_list_open", "ul", 1) + + token.map = listLines = [startLine, 0] + token.markup = markerChar + + # + # Iterate list items + # + + nextLine = startLine + prevEmptyEnd = False + terminatorRules = state.md.block.ruler.getRules("list") + + oldParentType = state.parentType + state.parentType = "list" + + while nextLine < endLine: + pos = posAfterMarker + maximum = state.eMarks[nextLine] + + initial = offset = ( + state.sCount[nextLine] + + posAfterMarker + - (state.bMarks[startLine] + state.tShift[startLine]) + ) + + while pos < maximum: + ch = state.src[pos] + + if ch == "\t": + offset += 4 - (offset + state.bsCount[nextLine]) % 4 + elif ch == " ": + offset += 1 + else: + break + + pos += 1 + + contentStart = pos + + # trimming space in "- \n 3" case, indent is 1 here + indentAfterMarker = 1 if contentStart >= maximum else offset - initial + + # If we have more than 4 spaces, the indent is 1 + # (the rest is just indented code block) + if indentAfterMarker > 4: + indentAfterMarker = 1 + + # " - test" + # ^^^^^ - calculating total length of this thing + indent = initial + indentAfterMarker + + # Run subparser & write tokens + token = state.push("list_item_open", "li", 1) + token.markup = markerChar + token.map = itemLines = [startLine, 0] + if isOrdered: + token.info = state.src[start : posAfterMarker - 1] + + # change current state, then restore it after parser subcall + oldTight = state.tight + oldTShift = state.tShift[startLine] + oldSCount = state.sCount[startLine] + + # - example list + # ^ listIndent position will be here + # ^ blkIndent position will be here + # + oldListIndent = state.listIndent + state.listIndent = state.blkIndent + state.blkIndent = indent + + state.tight = True + state.tShift[startLine] = contentStart - state.bMarks[startLine] + state.sCount[startLine] = offset + + if contentStart >= maximum and state.isEmpty(startLine + 1): + # workaround for this case + # (list item is empty, list terminates before "foo"): + # ~~~~~~~~ + # - + # + # foo + # ~~~~~~~~ + state.line = min(state.line + 2, endLine) + else: + # NOTE in list.js this was: + # state.md.block.tokenize(state, startLine, endLine, True) + # but tokeniz does not take the final parameter + state.md.block.tokenize(state, startLine, endLine) + + # If any of list item is tight, mark list as tight + if (not state.tight) or prevEmptyEnd: + tight = False + + # Item become loose if finish with empty line, + # but we should filter last element, because it means list finish + prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1) + + state.blkIndent = state.listIndent + state.listIndent = oldListIndent + state.tShift[startLine] = oldTShift + state.sCount[startLine] = oldSCount + state.tight = oldTight + + token = state.push("list_item_close", "li", -1) + token.markup = markerChar + + nextLine = startLine = state.line + itemLines[1] = nextLine + + if nextLine >= endLine: + break + + contentStart = state.bMarks[startLine] + + # + # Try to check if list is terminated or continued. + # + if state.sCount[nextLine] < state.blkIndent: + break + + if state.is_code_block(startLine): + break + + # fail if terminating block found + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + + # fail if list has another type + if isOrdered: + posAfterMarker = skipOrderedListMarker(state, nextLine) + if posAfterMarker < 0: + break + start = state.bMarks[nextLine] + state.tShift[nextLine] + else: + posAfterMarker = skipBulletListMarker(state, nextLine) + if posAfterMarker < 0: + break + + if markerChar != state.src[posAfterMarker - 1]: + break + + # Finalize list + if isOrdered: + token = state.push("ordered_list_close", "ol", -1) + else: + token = state.push("bullet_list_close", "ul", -1) + + token.markup = markerChar + + listLines[1] = nextLine + state.line = nextLine + + state.parentType = oldParentType + + # mark paragraphs tight if needed + if tight: + markTightParagraphs(state, listTokIdx) + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/paragraph.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/paragraph.py new file mode 100644 index 0000000000000000000000000000000000000000..5388a4b1468defccb5ed4d7d68f3e5ac1a747178 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/paragraph.py @@ -0,0 +1,65 @@ +"""Paragraph.""" +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent + ) + + nextLine = startLine + 1 + ruler = state.md.block.ruler + terminatorRules = ruler.getRules("paragraph") + endLine = state.lineMax + + oldParentType = state.parentType + state.parentType = "paragraph" + + # jump line-by-line until empty one or EOF + while nextLine < endLine: + if state.isEmpty(nextLine): + break + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.sCount[nextLine] - state.blkIndent > 3: + nextLine += 1 + continue + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + nextLine += 1 + continue + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + + nextLine += 1 + + content = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + + state.line = nextLine + + token = state.push("paragraph_open", "p", 1) + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = content + token.map = [startLine, state.line] + token.children = [] + + token = state.push("paragraph_close", "p", -1) + + state.parentType = oldParentType + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/reference.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..b77944b2ee8133727da934c3c7dbe800f2fc28ce --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/reference.py @@ -0,0 +1,215 @@ +import logging + +from ..common.utils import charCodeAt, isSpace, normalizeReference +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def reference(state: StateBlock, startLine: int, _endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering reference: %s, %s, %s, %s", state, startLine, _endLine, silent + ) + + lines = 0 + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + nextLine = startLine + 1 + + if state.is_code_block(startLine): + return False + + if state.src[pos] != "[": + return False + + # Simple check to quickly interrupt scan on [link](url) at the start of line. + # Can be useful on practice: https:#github.com/markdown-it/markdown-it/issues/54 + while pos < maximum: + # /* ] */ /* \ */ /* : */ + if state.src[pos] == "]" and state.src[pos - 1] != "\\": + if pos + 1 == maximum: + return False + if state.src[pos + 1] != ":": + return False + break + pos += 1 + + endLine = state.lineMax + + # jump line-by-line until empty one or EOF + terminatorRules = state.md.block.ruler.getRules("reference") + + oldParentType = state.parentType + state.parentType = "reference" + + while nextLine < endLine and not state.isEmpty(nextLine): + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.sCount[nextLine] - state.blkIndent > 3: + nextLine += 1 + continue + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + nextLine += 1 + continue + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + + nextLine += 1 + + string = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + maximum = len(string) + + labelEnd = None + pos = 1 + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x5B: # /* [ */ + return False + elif ch == 0x5D: # /* ] */ + labelEnd = pos + break + elif ch == 0x0A: # /* \n */ + lines += 1 + elif ch == 0x5C: # /* \ */ + pos += 1 + if pos < maximum and charCodeAt(string, pos) == 0x0A: + lines += 1 + pos += 1 + + if ( + labelEnd is None or labelEnd < 0 or charCodeAt(string, labelEnd + 1) != 0x3A + ): # /* : */ + return False + + # [label]: destination 'title' + # ^^^ skip optional whitespace here + pos = labelEnd + 2 + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x0A: + lines += 1 + elif isSpace(ch): + pass + else: + break + pos += 1 + + # [label]: destination 'title' + # ^^^^^^^^^^^ parse this + res = state.md.helpers.parseLinkDestination(string, pos, maximum) + if not res.ok: + return False + + href = state.md.normalizeLink(res.str) + if not state.md.validateLink(href): + return False + + pos = res.pos + lines += res.lines + + # save cursor state, we could require to rollback later + destEndPos = pos + destEndLineNo = lines + + # [label]: destination 'title' + # ^^^ skipping those spaces + start = pos + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x0A: + lines += 1 + elif isSpace(ch): + pass + else: + break + pos += 1 + + # [label]: destination 'title' + # ^^^^^^^ parse this + res = state.md.helpers.parseLinkTitle(string, pos, maximum) + if pos < maximum and start != pos and res.ok: + title = res.str + pos = res.pos + lines += res.lines + else: + title = "" + pos = destEndPos + lines = destEndLineNo + + # skip trailing spaces until the rest of the line + while pos < maximum: + ch = charCodeAt(string, pos) + if not isSpace(ch): + break + pos += 1 + + if pos < maximum and charCodeAt(string, pos) != 0x0A and title: + # garbage at the end of the line after title, + # but it could still be a valid reference if we roll back + title = "" + pos = destEndPos + lines = destEndLineNo + while pos < maximum: + ch = charCodeAt(string, pos) + if not isSpace(ch): + break + pos += 1 + + if pos < maximum and charCodeAt(string, pos) != 0x0A: + # garbage at the end of the line + return False + + label = normalizeReference(string[1:labelEnd]) + if not label: + # CommonMark 0.20 disallows empty labels + return False + + # Reference can not terminate anything. This check is for safety only. + if silent: + return True + + if "references" not in state.env: + state.env["references"] = {} + + state.line = startLine + lines + 1 + + # note, this is not part of markdown-it JS, but is useful for renderers + if state.md.options.get("inline_definitions", False): + token = state.push("definition", "", 0) + token.meta = { + "id": label, + "title": title, + "url": href, + "label": string[1:labelEnd], + } + token.map = [startLine, state.line] + + if label not in state.env["references"]: + state.env["references"][label] = { + "title": title, + "href": href, + "map": [startLine, state.line], + } + else: + state.env.setdefault("duplicate_refs", []).append( + { + "title": title, + "href": href, + "label": label, + "map": [startLine, state.line], + } + ) + + state.parentType = oldParentType + + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/state_block.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/state_block.py new file mode 100644 index 0000000000000000000000000000000000000000..445ad265a01e3f1dededf9f72848686a2b5ee901 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/state_block.py @@ -0,0 +1,261 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from ..common.utils import isStrSpace +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it.main import MarkdownIt + + +class StateBlock(StateBase): + def __init__( + self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token] + ) -> None: + self.src = src + + # link to parser instance + self.md = md + + self.env = env + + # + # Internal state variables + # + + self.tokens = tokens + + self.bMarks: list[int] = [] # line begin offsets for fast jumps + self.eMarks: list[int] = [] # line end offsets for fast jumps + # offsets of the first non-space characters (tabs not expanded) + self.tShift: list[int] = [] + self.sCount: list[int] = [] # indents for each line (tabs expanded) + + # An amount of virtual spaces (tabs expanded) between beginning + # of each line (bMarks) and real beginning of that line. + # + # It exists only as a hack because blockquotes override bMarks + # losing information in the process. + # + # It's used only when expanding tabs, you can think about it as + # an initial tab length, e.g. bsCount=21 applied to string `\t123` + # means first tab should be expanded to 4-21%4 === 3 spaces. + # + self.bsCount: list[int] = [] + + # block parser variables + self.blkIndent = 0 # required block content indent (for example, if we are + # inside a list, it would be positioned after list marker) + self.line = 0 # line index in src + self.lineMax = 0 # lines count + self.tight = False # loose/tight mode for lists + self.ddIndent = -1 # indent of the current dd block (-1 if there isn't any) + self.listIndent = -1 # indent of the current list block (-1 if there isn't any) + + # can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' + # used in lists to determine if they interrupt a paragraph + self.parentType = "root" + + self.level = 0 + + # renderer + self.result = "" + + # Create caches + # Generate markers. + indent_found = False + + start = pos = indent = offset = 0 + length = len(self.src) + + for pos, character in enumerate(self.src): + if not indent_found: + if isStrSpace(character): + indent += 1 + + if character == "\t": + offset += 4 - offset % 4 + else: + offset += 1 + continue + else: + indent_found = True + + if character == "\n" or pos == length - 1: + if character != "\n": + pos += 1 + self.bMarks.append(start) + self.eMarks.append(pos) + self.tShift.append(indent) + self.sCount.append(offset) + self.bsCount.append(0) + + indent_found = False + indent = 0 + offset = 0 + start = pos + 1 + + # Push fake entry to simplify cache bounds checks + self.bMarks.append(length) + self.eMarks.append(length) + self.tShift.append(0) + self.sCount.append(0) + self.bsCount.append(0) + + self.lineMax = len(self.bMarks) - 1 # don't count last fake line + + # pre-check if code blocks are enabled, to speed up is_code_block method + self._code_enabled = "code" in self.md["block"].ruler.get_active_rules() + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(line={self.line},level={self.level},tokens={len(self.tokens)})" + ) + + def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token: + """Push new token to "stream".""" + token = Token(ttype, tag, nesting) + token.block = True + if nesting < 0: + self.level -= 1 # closing tag + token.level = self.level + if nesting > 0: + self.level += 1 # opening tag + self.tokens.append(token) + return token + + def isEmpty(self, line: int) -> bool: + """.""" + return (self.bMarks[line] + self.tShift[line]) >= self.eMarks[line] + + def skipEmptyLines(self, from_pos: int) -> int: + """.""" + while from_pos < self.lineMax: + try: + if (self.bMarks[from_pos] + self.tShift[from_pos]) < self.eMarks[ + from_pos + ]: + break + except IndexError: + pass + from_pos += 1 + return from_pos + + def skipSpaces(self, pos: int) -> int: + """Skip spaces from given position.""" + while True: + try: + current = self.src[pos] + except IndexError: + break + if not isStrSpace(current): + break + pos += 1 + return pos + + def skipSpacesBack(self, pos: int, minimum: int) -> int: + """Skip spaces from given position in reverse.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if not isStrSpace(self.src[pos]): + return pos + 1 + return pos + + def skipChars(self, pos: int, code: int) -> int: + """Skip character code from given position.""" + while True: + try: + current = self.srcCharCode[pos] + except IndexError: + break + if current != code: + break + pos += 1 + return pos + + def skipCharsStr(self, pos: int, ch: str) -> int: + """Skip character string from given position.""" + while True: + try: + current = self.src[pos] + except IndexError: + break + if current != ch: + break + pos += 1 + return pos + + def skipCharsBack(self, pos: int, code: int, minimum: int) -> int: + """Skip character code reverse from given position - 1.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if code != self.srcCharCode[pos]: + return pos + 1 + return pos + + def skipCharsStrBack(self, pos: int, ch: str, minimum: int) -> int: + """Skip character string reverse from given position - 1.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if ch != self.src[pos]: + return pos + 1 + return pos + + def getLines(self, begin: int, end: int, indent: int, keepLastLF: bool) -> str: + """Cut lines range from source.""" + line = begin + if begin >= end: + return "" + + queue = [""] * (end - begin) + + i = 1 + while line < end: + lineIndent = 0 + lineStart = first = self.bMarks[line] + last = ( + self.eMarks[line] + 1 + if line + 1 < end or keepLastLF + else self.eMarks[line] + ) + + while (first < last) and (lineIndent < indent): + ch = self.src[first] + if isStrSpace(ch): + if ch == "\t": + lineIndent += 4 - (lineIndent + self.bsCount[line]) % 4 + else: + lineIndent += 1 + elif first - lineStart < self.tShift[line]: + lineIndent += 1 + else: + break + first += 1 + + if lineIndent > indent: + # partially expanding tabs in code blocks, e.g '\t\tfoobar' + # with indent=2 becomes ' \tfoobar' + queue[i - 1] = (" " * (lineIndent - indent)) + self.src[first:last] + else: + queue[i - 1] = self.src[first:last] + + line += 1 + i += 1 + + return "".join(queue) + + def is_code_block(self, line: int) -> bool: + """Check if line is a code block, + i.e. the code block rule is enabled and text is indented by more than 3 spaces. + """ + return self._code_enabled and (self.sCount[line] - self.blkIndent) >= 4 diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_block/table.py b/python_embeded/Lib/site-packages/markdown_it/rules_block/table.py new file mode 100644 index 0000000000000000000000000000000000000000..4b666c1d5d9ede544b27c38d7ffb5d850edac70b --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_block/table.py @@ -0,0 +1,236 @@ +# GFM table, https://github.github.com/gfm/#tables-extension- +from __future__ import annotations + +import re + +from ..common.utils import charStrAt, isStrSpace +from .state_block import StateBlock + +headerLineRe = re.compile(r"^:?-+:?$") +enclosingPipesRe = re.compile(r"^\||\|$") + + +def getLine(state: StateBlock, line: int) -> str: + pos = state.bMarks[line] + state.tShift[line] + maximum = state.eMarks[line] + + # return state.src.substr(pos, max - pos) + return state.src[pos:maximum] + + +def escapedSplit(string: str) -> list[str]: + result: list[str] = [] + pos = 0 + max = len(string) + isEscaped = False + lastPos = 0 + current = "" + ch = charStrAt(string, pos) + + while pos < max: + if ch == "|": + if not isEscaped: + # pipe separating cells, '|' + result.append(current + string[lastPos:pos]) + current = "" + lastPos = pos + 1 + else: + # escaped pipe, '\|' + current += string[lastPos : pos - 1] + lastPos = pos + + isEscaped = ch == "\\" + pos += 1 + + ch = charStrAt(string, pos) + + result.append(current + string[lastPos:]) + + return result + + +def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + tbodyLines = None + + # should have at least two lines + if startLine + 2 > endLine: + return False + + nextLine = startLine + 1 + + if state.sCount[nextLine] < state.blkIndent: + return False + + if state.is_code_block(nextLine): + return False + + # first character of the second line should be '|', '-', ':', + # and no other characters are allowed but spaces; + # basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + if pos >= state.eMarks[nextLine]: + return False + first_ch = state.src[pos] + pos += 1 + if first_ch not in ("|", "-", ":"): + return False + + if pos >= state.eMarks[nextLine]: + return False + second_ch = state.src[pos] + pos += 1 + if second_ch not in ("|", "-", ":") and not isStrSpace(second_ch): + return False + + # if first character is '-', then second character must not be a space + # (due to parsing ambiguity with list) + if first_ch == "-" and isStrSpace(second_ch): + return False + + while pos < state.eMarks[nextLine]: + ch = state.src[pos] + + if ch not in ("|", "-", ":") and not isStrSpace(ch): + return False + + pos += 1 + + lineText = getLine(state, startLine + 1) + + columns = lineText.split("|") + aligns = [] + for i in range(len(columns)): + t = columns[i].strip() + if not t: + # allow empty columns before and after table, but not in between columns; + # e.g. allow ` |---| `, disallow ` ---||--- ` + if i == 0 or i == len(columns) - 1: + continue + else: + return False + + if not headerLineRe.search(t): + return False + if charStrAt(t, len(t) - 1) == ":": + aligns.append("center" if charStrAt(t, 0) == ":" else "right") + elif charStrAt(t, 0) == ":": + aligns.append("left") + else: + aligns.append("") + + lineText = getLine(state, startLine).strip() + if "|" not in lineText: + return False + if state.is_code_block(startLine): + return False + columns = escapedSplit(lineText) + if columns and columns[0] == "": + columns.pop(0) + if columns and columns[-1] == "": + columns.pop() + + # header row will define an amount of columns in the entire table, + # and align row should be exactly the same (the rest of the rows can differ) + columnCount = len(columns) + if columnCount == 0 or columnCount != len(aligns): + return False + + if silent: + return True + + oldParentType = state.parentType + state.parentType = "table" + + # use 'blockquote' lists for termination because it's + # the most similar to tables + terminatorRules = state.md.block.ruler.getRules("blockquote") + + token = state.push("table_open", "table", 1) + token.map = tableLines = [startLine, 0] + + token = state.push("thead_open", "thead", 1) + token.map = [startLine, startLine + 1] + + token = state.push("tr_open", "tr", 1) + token.map = [startLine, startLine + 1] + + for i in range(len(columns)): + token = state.push("th_open", "th", 1) + if aligns[i]: + token.attrs = {"style": "text-align:" + aligns[i]} + + token = state.push("inline", "", 0) + # note in markdown-it this map was removed in v12.0.0 however, we keep it, + # since it is helpful to propagate to children tokens + token.map = [startLine, startLine + 1] + token.content = columns[i].strip() + token.children = [] + + token = state.push("th_close", "th", -1) + + token = state.push("tr_close", "tr", -1) + token = state.push("thead_close", "thead", -1) + + nextLine = startLine + 2 + while nextLine < endLine: + if state.sCount[nextLine] < state.blkIndent: + break + + terminate = False + for i in range(len(terminatorRules)): + if terminatorRules[i](state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + lineText = getLine(state, nextLine).strip() + if not lineText: + break + if state.is_code_block(nextLine): + break + columns = escapedSplit(lineText) + if columns and columns[0] == "": + columns.pop(0) + if columns and columns[-1] == "": + columns.pop() + + if nextLine == startLine + 2: + token = state.push("tbody_open", "tbody", 1) + token.map = tbodyLines = [startLine + 2, 0] + + token = state.push("tr_open", "tr", 1) + token.map = [nextLine, nextLine + 1] + + for i in range(columnCount): + token = state.push("td_open", "td", 1) + if aligns[i]: + token.attrs = {"style": "text-align:" + aligns[i]} + + token = state.push("inline", "", 0) + # note in markdown-it this map was removed in v12.0.0 however, we keep it, + # since it is helpful to propagate to children tokens + token.map = [nextLine, nextLine + 1] + try: + token.content = columns[i].strip() if columns[i] else "" + except IndexError: + token.content = "" + token.children = [] + + token = state.push("td_close", "td", -1) + + token = state.push("tr_close", "tr", -1) + + nextLine += 1 + + if tbodyLines: + token = state.push("tbody_close", "tbody", -1) + tbodyLines[1] = nextLine + + token = state.push("table_close", "table", -1) + + tableLines[1] = nextLine + state.parentType = oldParentType + state.line = nextLine + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/__init__.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c5368c2b694231000626a03594ebad75fe8c71 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/__init__.py @@ -0,0 +1,19 @@ +__all__ = ( + "StateCore", + "normalize", + "block", + "inline", + "replace", + "smartquotes", + "linkify", + "text_join", +) + +from .block import block +from .inline import inline +from .linkify import linkify +from .normalize import normalize +from .replacements import replace +from .smartquotes import smartquotes +from .state_core import StateCore +from .text_join import text_join diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/block.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/block.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c3bb8d7ae18880fd638690fb5b09beb78b103c --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/block.py @@ -0,0 +1,13 @@ +from ..token import Token +from .state_core import StateCore + + +def block(state: StateCore) -> None: + if state.inlineMode: + token = Token("inline", "", 0) + token.content = state.src + token.map = [0, 1] + token.children = [] + state.tokens.append(token) + else: + state.md.block.parse(state.src, state.md, state.env, state.tokens) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/inline.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/inline.py new file mode 100644 index 0000000000000000000000000000000000000000..c3fd0b5e25dda5d8a5a644cc9e460d0f92ae2d1d --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/inline.py @@ -0,0 +1,10 @@ +from .state_core import StateCore + + +def inline(state: StateCore) -> None: + """Parse inlines""" + for token in state.tokens: + if token.type == "inline": + if token.children is None: + token.children = [] + state.md.inline.parse(token.content, state.md, state.env, token.children) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/linkify.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/linkify.py new file mode 100644 index 0000000000000000000000000000000000000000..efbc9d4c9b1cbada1c936401b3421d73fbff5b64 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/linkify.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import re +from typing import Protocol + +from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen +from ..token import Token +from .state_core import StateCore + +HTTP_RE = re.compile(r"^http://") +MAILTO_RE = re.compile(r"^mailto:") +TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE) + + +def linkify(state: StateCore) -> None: + """Rule for identifying plain-text links.""" + if not state.md.options.linkify: + return + + if not state.md.linkify: + raise ModuleNotFoundError("Linkify enabled but not installed.") + + for inline_token in state.tokens: + if inline_token.type != "inline" or not state.md.linkify.pretest( + inline_token.content + ): + continue + + tokens = inline_token.children + + htmlLinkLevel = 0 + + # We scan from the end, to keep position when new tags added. + # Use reversed logic in links start/end match + assert tokens is not None + i = len(tokens) + while i >= 1: + i -= 1 + assert isinstance(tokens, list) + currentToken = tokens[i] + + # Skip content of markdown links + if currentToken.type == "link_close": + i -= 1 + while ( + tokens[i].level != currentToken.level + and tokens[i].type != "link_open" + ): + i -= 1 + continue + + # Skip content of html tag links + if currentToken.type == "html_inline": + if isLinkOpen(currentToken.content) and htmlLinkLevel > 0: + htmlLinkLevel -= 1 + if isLinkClose(currentToken.content): + htmlLinkLevel += 1 + if htmlLinkLevel > 0: + continue + + if currentToken.type == "text" and state.md.linkify.test( + currentToken.content + ): + text = currentToken.content + links: list[_LinkType] = state.md.linkify.match(text) or [] + + # Now split string to nodes + nodes = [] + level = currentToken.level + lastPos = 0 + + # forbid escape sequence at the start of the string, + # this avoids http\://example.com/ from being linkified as + # http://example.com/ + if ( + links + and links[0].index == 0 + and i > 0 + and tokens[i - 1].type == "text_special" + ): + links = links[1:] + + for link in links: + url = link.url + fullUrl = state.md.normalizeLink(url) + if not state.md.validateLink(fullUrl): + continue + + urlText = link.text + + # Linkifier might send raw hostnames like "example.com", where url + # starts with domain name. So we prepend http:// in those cases, + # and remove it afterwards. + if not link.schema: + urlText = HTTP_RE.sub( + "", state.md.normalizeLinkText("http://" + urlText) + ) + elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText): + urlText = MAILTO_RE.sub( + "", state.md.normalizeLinkText("mailto:" + urlText) + ) + else: + urlText = state.md.normalizeLinkText(urlText) + + pos = link.index + + if pos > lastPos: + token = Token("text", "", 0) + token.content = text[lastPos:pos] + token.level = level + nodes.append(token) + + token = Token("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.level = level + level += 1 + token.markup = "linkify" + token.info = "auto" + nodes.append(token) + + token = Token("text", "", 0) + token.content = urlText + token.level = level + nodes.append(token) + + token = Token("link_close", "a", -1) + level -= 1 + token.level = level + token.markup = "linkify" + token.info = "auto" + nodes.append(token) + + lastPos = link.last_index + + if lastPos < len(text): + token = Token("text", "", 0) + token.content = text[lastPos:] + token.level = level + nodes.append(token) + + inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes) + + +class _LinkType(Protocol): + url: str + text: str + index: int + last_index: int + schema: str | None diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/normalize.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f8d0d5729b2497b5f4b611b0451dfe92872506 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/normalize.py @@ -0,0 +1,18 @@ +"""Normalize input string.""" +import re + +from .state_core import StateCore + +# https://spec.commonmark.org/0.29/#line-ending +NEWLINES_RE = re.compile(r"\r\n?|\n") +NULL_RE = re.compile(r"\0") + + +def normalize(state: StateCore) -> None: + # Normalize newlines + string = NEWLINES_RE.sub("\n", state.src) + + # Replace NULL characters + string = NULL_RE.sub("\uFFFD", string) + + state.src = string diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/replacements.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/replacements.py new file mode 100644 index 0000000000000000000000000000000000000000..14912e17ac8eed885a2fd07c74141804f3f9fa72 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/replacements.py @@ -0,0 +1,126 @@ +"""Simple typographic replacements + +* ``(c)``, ``(C)`` → © +* ``(tm)``, ``(TM)`` → ™ +* ``(r)``, ``(R)`` → ® +* ``+-`` → ± +* ``...`` → … +* ``?....`` → ?.. +* ``!....`` → !.. +* ``????????`` → ??? +* ``!!!!!`` → !!! +* ``,,,`` → , +* ``--`` → &ndash +* ``---`` → &mdash +""" +from __future__ import annotations + +import logging +import re + +from ..token import Token +from .state_core import StateCore + +LOGGER = logging.getLogger(__name__) + +# TODO: +# - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ +# - multiplication 2 x 4 -> 2 × 4 + +RARE_RE = re.compile(r"\+-|\.\.|\?\?\?\?|!!!!|,,|--") + +# Workaround for phantomjs - need regex without /g flag, +# or root check will fail every second time +# SCOPED_ABBR_TEST_RE = r"\((c|tm|r)\)" + +SCOPED_ABBR_RE = re.compile(r"\((c|tm|r)\)", flags=re.IGNORECASE) + +PLUS_MINUS_RE = re.compile(r"\+-") + +ELLIPSIS_RE = re.compile(r"\.{2,}") + +ELLIPSIS_QUESTION_EXCLAMATION_RE = re.compile(r"([?!])…") + +QUESTION_EXCLAMATION_RE = re.compile(r"([?!]){4,}") + +COMMA_RE = re.compile(r",{2,}") + +EM_DASH_RE = re.compile(r"(^|[^-])---(?=[^-]|$)", flags=re.MULTILINE) + +EN_DASH_RE = re.compile(r"(^|\s)--(?=\s|$)", flags=re.MULTILINE) + +EN_DASH_INDENT_RE = re.compile(r"(^|[^-\s])--(?=[^-\s]|$)", flags=re.MULTILINE) + + +SCOPED_ABBR = {"c": "©", "r": "®", "tm": "™"} + + +def replaceFn(match: re.Match[str]) -> str: + return SCOPED_ABBR[match.group(1).lower()] + + +def replace_scoped(inlineTokens: list[Token]) -> None: + inside_autolink = 0 + + for token in inlineTokens: + if token.type == "text" and not inside_autolink: + token.content = SCOPED_ABBR_RE.sub(replaceFn, token.content) + + if token.type == "link_open" and token.info == "auto": + inside_autolink -= 1 + + if token.type == "link_close" and token.info == "auto": + inside_autolink += 1 + + +def replace_rare(inlineTokens: list[Token]) -> None: + inside_autolink = 0 + + for token in inlineTokens: + if ( + token.type == "text" + and (not inside_autolink) + and RARE_RE.search(token.content) + ): + # +- -> ± + token.content = PLUS_MINUS_RE.sub("±", token.content) + + # .., ..., ....... -> … + token.content = ELLIPSIS_RE.sub("…", token.content) + + # but ?..... & !..... -> ?.. & !.. + token.content = ELLIPSIS_QUESTION_EXCLAMATION_RE.sub("\\1..", token.content) + token.content = QUESTION_EXCLAMATION_RE.sub("\\1\\1\\1", token.content) + + # ,, ,,, ,,,, -> , + token.content = COMMA_RE.sub(",", token.content) + + # em-dash + token.content = EM_DASH_RE.sub("\\1\u2014", token.content) + + # en-dash + token.content = EN_DASH_RE.sub("\\1\u2013", token.content) + token.content = EN_DASH_INDENT_RE.sub("\\1\u2013", token.content) + + if token.type == "link_open" and token.info == "auto": + inside_autolink -= 1 + + if token.type == "link_close" and token.info == "auto": + inside_autolink += 1 + + +def replace(state: StateCore) -> None: + if not state.md.options.typographer: + return + + for token in state.tokens: + if token.type != "inline": + continue + if token.children is None: + continue + + if SCOPED_ABBR_RE.search(token.content): + replace_scoped(token.children) + + if RARE_RE.search(token.content): + replace_rare(token.children) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/smartquotes.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/smartquotes.py new file mode 100644 index 0000000000000000000000000000000000000000..c98fbd71e7d2e644ca7c6ac95827962342326059 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/smartquotes.py @@ -0,0 +1,202 @@ +"""Convert straight quotation marks to typographic ones +""" +from __future__ import annotations + +import re +from typing import Any + +from ..common.utils import charCodeAt, isMdAsciiPunct, isPunctChar, isWhiteSpace +from ..token import Token +from .state_core import StateCore + +QUOTE_TEST_RE = re.compile(r"['\"]") +QUOTE_RE = re.compile(r"['\"]") +APOSTROPHE = "\u2019" # ’ + + +def replaceAt(string: str, index: int, ch: str) -> str: + # When the index is negative, the behavior is different from the js version. + # But basically, the index will not be negative. + assert index >= 0 + return string[:index] + ch + string[index + 1 :] + + +def process_inlines(tokens: list[Token], state: StateCore) -> None: + stack: list[dict[str, Any]] = [] + + for i, token in enumerate(tokens): + thisLevel = token.level + + j = 0 + for j in range(len(stack))[::-1]: + if stack[j]["level"] <= thisLevel: + break + else: + # When the loop is terminated without a "break". + # Subtract 1 to get the same index as the js version. + j -= 1 + + stack = stack[: j + 1] + + if token.type != "text": + continue + + text = token.content + pos = 0 + maximum = len(text) + + while pos < maximum: + goto_outer = False + lastIndex = pos + t = QUOTE_RE.search(text[lastIndex:]) + if not t: + break + + canOpen = canClose = True + pos = t.start(0) + lastIndex + 1 + isSingle = t.group(0) == "'" + + # Find previous character, + # default to space if it's the beginning of the line + lastChar: None | int = 0x20 + + if t.start(0) + lastIndex - 1 >= 0: + lastChar = charCodeAt(text, t.start(0) + lastIndex - 1) + else: + for j in range(i)[::-1]: + if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak": + break + # should skip all tokens except 'text', 'html_inline' or 'code_inline' + if not tokens[j].content: + continue + + lastChar = charCodeAt(tokens[j].content, len(tokens[j].content) - 1) + break + + # Find next character, + # default to space if it's the end of the line + nextChar: None | int = 0x20 + + if pos < maximum: + nextChar = charCodeAt(text, pos) + else: + for j in range(i + 1, len(tokens)): + # nextChar defaults to 0x20 + if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak": + break + # should skip all tokens except 'text', 'html_inline' or 'code_inline' + if not tokens[j].content: + continue + + nextChar = charCodeAt(tokens[j].content, 0) + break + + isLastPunctChar = lastChar is not None and ( + isMdAsciiPunct(lastChar) or isPunctChar(chr(lastChar)) + ) + isNextPunctChar = nextChar is not None and ( + isMdAsciiPunct(nextChar) or isPunctChar(chr(nextChar)) + ) + + isLastWhiteSpace = lastChar is not None and isWhiteSpace(lastChar) + isNextWhiteSpace = nextChar is not None and isWhiteSpace(nextChar) + + if isNextWhiteSpace: # noqa: SIM114 + canOpen = False + elif isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar): + canOpen = False + + if isLastWhiteSpace: # noqa: SIM114 + canClose = False + elif isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar): + canClose = False + + if nextChar == 0x22 and t.group(0) == '"': # 0x22: " # noqa: SIM102 + if ( + lastChar is not None and lastChar >= 0x30 and lastChar <= 0x39 + ): # 0x30: 0, 0x39: 9 + # special case: 1"" - count first quote as an inch + canClose = canOpen = False + + if canOpen and canClose: + # Replace quotes in the middle of punctuation sequence, but not + # in the middle of the words, i.e.: + # + # 1. foo " bar " baz - not replaced + # 2. foo-"-bar-"-baz - replaced + # 3. foo"bar"baz - not replaced + canOpen = isLastPunctChar + canClose = isNextPunctChar + + if not canOpen and not canClose: + # middle of word + if isSingle: + token.content = replaceAt( + token.content, t.start(0) + lastIndex, APOSTROPHE + ) + continue + + if canClose: + # this could be a closing quote, rewind the stack to get a match + for j in range(len(stack))[::-1]: + item = stack[j] + if stack[j]["level"] < thisLevel: + break + if item["single"] == isSingle and stack[j]["level"] == thisLevel: + item = stack[j] + + if isSingle: + openQuote = state.md.options.quotes[2] + closeQuote = state.md.options.quotes[3] + else: + openQuote = state.md.options.quotes[0] + closeQuote = state.md.options.quotes[1] + + # replace token.content *before* tokens[item.token].content, + # because, if they are pointing at the same token, replaceAt + # could mess up indices when quote length != 1 + token.content = replaceAt( + token.content, t.start(0) + lastIndex, closeQuote + ) + tokens[item["token"]].content = replaceAt( + tokens[item["token"]].content, item["pos"], openQuote + ) + + pos += len(closeQuote) - 1 + if item["token"] == i: + pos += len(openQuote) - 1 + + text = token.content + maximum = len(text) + + stack = stack[:j] + goto_outer = True + break + if goto_outer: + goto_outer = False + continue + + if canOpen: + stack.append( + { + "token": i, + "pos": t.start(0) + lastIndex, + "single": isSingle, + "level": thisLevel, + } + ) + elif canClose and isSingle: + token.content = replaceAt( + token.content, t.start(0) + lastIndex, APOSTROPHE + ) + + +def smartquotes(state: StateCore) -> None: + if not state.md.options.typographer: + return + + for token in state.tokens: + if token.type != "inline" or not QUOTE_RE.search(token.content): + continue + if token.children is not None: + process_inlines(token.children, state) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/state_core.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/state_core.py new file mode 100644 index 0000000000000000000000000000000000000000..a938041d992fdf7ae3f2843a2e0f9ef298c45790 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/state_core.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +class StateCore(StateBase): + def __init__( + self, + src: str, + md: MarkdownIt, + env: EnvType, + tokens: list[Token] | None = None, + ) -> None: + self.src = src + self.md = md # link to parser instance + self.env = env + self.tokens: list[Token] = tokens or [] + self.inlineMode = False diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_core/text_join.py b/python_embeded/Lib/site-packages/markdown_it/rules_core/text_join.py new file mode 100644 index 0000000000000000000000000000000000000000..d54ccbbc376e7c50cf95227a36a11000b9d80496 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_core/text_join.py @@ -0,0 +1,34 @@ +"""Join raw text tokens with the rest of the text + +This is set as a separate rule to provide an opportunity for plugins +to run text replacements after text join, but before escape join. + +For example, `\\:)` shouldn't be replaced with an emoji. +""" +from __future__ import annotations + +from ..token import Token +from .state_core import StateCore + + +def text_join(state: StateCore) -> None: + """Join raw text for escape sequences (`text_special`) tokens with the rest of the text""" + + for inline_token in state.tokens[:]: + if inline_token.type != "inline": + continue + + # convert text_special to text and join all adjacent text nodes + new_tokens: list[Token] = [] + for child_token in inline_token.children or []: + if child_token.type == "text_special": + child_token.type = "text" + if ( + child_token.type == "text" + and new_tokens + and new_tokens[-1].type == "text" + ): + new_tokens[-1].content += child_token.content + else: + new_tokens.append(child_token) + inline_token.children = new_tokens diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/__init__.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8026ec3a7afd6f35140bb074780da05c6e86af --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/__init__.py @@ -0,0 +1,31 @@ +__all__ = ( + "StateInline", + "text", + "fragments_join", + "link_pairs", + "linkify", + "escape", + "newline", + "backtick", + "emphasis", + "image", + "link", + "autolink", + "entity", + "html_inline", + "strikethrough", +) +from . import emphasis, strikethrough +from .autolink import autolink +from .backticks import backtick +from .balance_pairs import link_pairs +from .entity import entity +from .escape import escape +from .fragments_join import fragments_join +from .html_inline import html_inline +from .image import image +from .link import link +from .linkify import linkify +from .newline import newline +from .state_inline import StateInline +from .text import text diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/autolink.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/autolink.py new file mode 100644 index 0000000000000000000000000000000000000000..295d963f39254e6ddfe9dc36af2bfa5e534c0827 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/autolink.py @@ -0,0 +1,77 @@ +# Process autolinks '' +import re + +from .state_inline import StateInline + +EMAIL_RE = re.compile( + r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$" # noqa: E501 +) +AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$") + + +def autolink(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "<": + return False + + start = state.pos + maximum = state.posMax + + while True: + pos += 1 + if pos >= maximum: + return False + + ch = state.src[pos] + + if ch == "<": + return False + if ch == ">": + break + + url = state.src[start + 1 : pos] + + if AUTOLINK_RE.search(url) is not None: + fullUrl = state.md.normalizeLink(url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + if EMAIL_RE.search(url) is not None: + fullUrl = state.md.normalizeLink("mailto:" + url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + return False diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/backticks.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/backticks.py new file mode 100644 index 0000000000000000000000000000000000000000..fc60d6b15cdfa7012a05bcf1ccbb06f44d870dfd --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/backticks.py @@ -0,0 +1,72 @@ +# Parse backticks +import re + +from .state_inline import StateInline + +regex = re.compile("^ (.+) $") + + +def backtick(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "`": + return False + + start = pos + pos += 1 + maximum = state.posMax + + # scan marker length + while pos < maximum and (state.src[pos] == "`"): + pos += 1 + + marker = state.src[start:pos] + openerLength = len(marker) + + if state.backticksScanned and state.backticks.get(openerLength, 0) <= start: + if not silent: + state.pending += marker + state.pos += openerLength + return True + + matchStart = matchEnd = pos + + # Nothing found in the cache, scan until the end of the line (or until marker is found) + while True: + try: + matchStart = state.src.index("`", matchEnd) + except ValueError: + break + matchEnd = matchStart + 1 + + # scan marker length + while matchEnd < maximum and (state.src[matchEnd] == "`"): + matchEnd += 1 + + closerLength = matchEnd - matchStart + + if closerLength == openerLength: + # Found matching closer length. + if not silent: + token = state.push("code_inline", "code", 0) + token.markup = marker + token.content = state.src[pos:matchStart].replace("\n", " ") + if ( + token.content.startswith(" ") + and token.content.endswith(" ") + and len(token.content.strip()) > 0 + ): + token.content = token.content[1:-1] + state.pos = matchEnd + return True + + # Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart + + # Scanned through the end, didn't find anything + state.backticksScanned = True + + if not silent: + state.pending += marker + state.pos += openerLength + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb2101c7e1614dde2323d3a8a42b388f354789e --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py @@ -0,0 +1,137 @@ +"""Balance paired characters (*, _, etc) in inline tokens.""" +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None: + """For each opening emphasis-like marker find a matching closing one.""" + if not delimiters: + return + + openersBottom = {} + maximum = len(delimiters) + + # headerIdx is the first delimiter of the current (where closer is) delimiter run + headerIdx = 0 + lastTokenIdx = -2 # needs any value lower than -1 + jumps: list[int] = [] + closerIdx = 0 + while closerIdx < maximum: + closer = delimiters[closerIdx] + + jumps.append(0) + + # markers belong to same delimiter run if: + # - they have adjacent tokens + # - AND markers are the same + # + if ( + delimiters[headerIdx].marker != closer.marker + or lastTokenIdx != closer.token - 1 + ): + headerIdx = closerIdx + lastTokenIdx = closer.token + + # Length is only used for emphasis-specific "rule of 3", + # if it's not defined (in strikethrough or 3rd party plugins), + # we can default it to 0 to disable those checks. + # + closer.length = closer.length or 0 + + if not closer.close: + closerIdx += 1 + continue + + # Previously calculated lower bounds (previous fails) + # for each marker, each delimiter length modulo 3, + # and for whether this closer can be an opener; + # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + if closer.marker not in openersBottom: + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1] + + minOpenerIdx = openersBottom[closer.marker][ + (3 if closer.open else 0) + (closer.length % 3) + ] + + openerIdx = headerIdx - jumps[headerIdx] - 1 + + newMinOpenerIdx = openerIdx + + while openerIdx > minOpenerIdx: + opener = delimiters[openerIdx] + + if opener.marker != closer.marker: + openerIdx -= jumps[openerIdx] + 1 + continue + + if opener.open and opener.end < 0: + isOddMatch = False + + # from spec: + # + # If one of the delimiters can both open and close emphasis, then the + # sum of the lengths of the delimiter runs containing the opening and + # closing delimiters must not be a multiple of 3 unless both lengths + # are multiples of 3. + # + if ( + (opener.close or closer.open) + and ((opener.length + closer.length) % 3 == 0) + and (opener.length % 3 != 0 or closer.length % 3 != 0) + ): + isOddMatch = True + + if not isOddMatch: + # If previous delimiter cannot be an opener, we can safely skip + # the entire sequence in future checks. This is required to make + # sure algorithm has linear complexity (see *_*_*_*_*_... case). + # + if openerIdx > 0 and not delimiters[openerIdx - 1].open: + lastJump = jumps[openerIdx - 1] + 1 + else: + lastJump = 0 + + jumps[closerIdx] = closerIdx - openerIdx + lastJump + jumps[openerIdx] = lastJump + + closer.open = False + opener.end = closerIdx + opener.close = False + newMinOpenerIdx = -1 + + # treat next token as start of run, + # it optimizes skips in **<...>**a**<...>** pathological case + lastTokenIdx = -2 + + break + + openerIdx -= jumps[openerIdx] + 1 + + if newMinOpenerIdx != -1: + # If match for this delimiter run failed, we want to set lower bound for + # future lookups. This is required to make sure algorithm has linear + # complexity. + # + # See details here: + # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442 + # + openersBottom[closer.marker][ + (3 if closer.open else 0) + ((closer.length or 0) % 3) + ] = newMinOpenerIdx + + closerIdx += 1 + + +def link_pairs(state: StateInline) -> None: + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + + processDelimiters(state, state.delimiters) + + curr = 0 + while curr < maximum: + curr_meta = tokens_meta[curr] + if curr_meta and "delimiters" in curr_meta: + processDelimiters(state, curr_meta["delimiters"]) + curr += 1 diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/emphasis.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/emphasis.py new file mode 100644 index 0000000000000000000000000000000000000000..9a98f9e216c94db0217e986270aaaa72fcc99f7f --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/emphasis.py @@ -0,0 +1,102 @@ +# Process *this* and _that_ +# +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool) -> bool: + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + marker = state.src[start] + + if silent: + return False + + if marker not in ("_", "*"): + return False + + scanned = state.scanDelims(state.pos, marker == "*") + + for _ in range(scanned.length): + token = state.push("text", "", 0) + token.content = marker + state.delimiters.append( + Delimiter( + marker=ord(marker), + length=scanned.length, + token=len(state.tokens) - 1, + end=-1, + open=scanned.can_open, + close=scanned.can_close, + ) + ) + + state.pos += scanned.length + + return True + + +def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None: + i = len(delimiters) - 1 + while i >= 0: + startDelim = delimiters[i] + + # /* _ */ /* * */ + if startDelim.marker != 0x5F and startDelim.marker != 0x2A: + i -= 1 + continue + + # Process only opening markers + if startDelim.end == -1: + i -= 1 + continue + + endDelim = delimiters[startDelim.end] + + # If the previous delimiter has the same marker and is adjacent to this one, + # merge those into one strong delimiter. + # + # `whatever` -> `whatever` + # + isStrong = ( + i > 0 + and delimiters[i - 1].end == startDelim.end + 1 + # check that first two markers match and adjacent + and delimiters[i - 1].marker == startDelim.marker + and delimiters[i - 1].token == startDelim.token - 1 + # check that last two markers are adjacent (we can safely assume they match) + and delimiters[startDelim.end + 1].token == endDelim.token + 1 + ) + + ch = chr(startDelim.marker) + + token = state.tokens[startDelim.token] + token.type = "strong_open" if isStrong else "em_open" + token.tag = "strong" if isStrong else "em" + token.nesting = 1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "strong_close" if isStrong else "em_close" + token.tag = "strong" if isStrong else "em" + token.nesting = -1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + if isStrong: + state.tokens[delimiters[i - 1].token].content = "" + state.tokens[delimiters[startDelim.end + 1].token].content = "" + i -= 1 + + i -= 1 + + +def postProcess(state: StateInline) -> None: + """Walk through delimiter list and replace text tokens with tags.""" + _postProcess(state, state.delimiters) + + for token in state.tokens_meta: + if token and "delimiters" in token: + _postProcess(state, token["delimiters"]) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/entity.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/entity.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9d39650e5bc533e694d3d6699677068d22c69f --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/entity.py @@ -0,0 +1,53 @@ +# Process html entity - {, ¯, ", ... +import re + +from ..common.entities import entities +from ..common.utils import fromCodePoint, isValidEntityCode +from .state_inline import StateInline + +DIGITAL_RE = re.compile(r"^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE) +NAMED_RE = re.compile(r"^&([a-z][a-z0-9]{1,31});", re.IGNORECASE) + + +def entity(state: StateInline, silent: bool) -> bool: + pos = state.pos + maximum = state.posMax + + if state.src[pos] != "&": + return False + + if pos + 1 >= maximum: + return False + + if state.src[pos + 1] == "#": + if match := DIGITAL_RE.search(state.src[pos:]): + if not silent: + match1 = match.group(1) + code = ( + int(match1[1:], 16) if match1[0].lower() == "x" else int(match1, 10) + ) + + token = state.push("text_special", "", 0) + token.content = ( + fromCodePoint(code) + if isValidEntityCode(code) + else fromCodePoint(0xFFFD) + ) + token.markup = match.group(0) + token.info = "entity" + + state.pos += len(match.group(0)) + return True + + else: + if (match := NAMED_RE.search(state.src[pos:])) and match.group(1) in entities: + if not silent: + token = state.push("text_special", "", 0) + token.content = entities[match.group(1)] + token.markup = match.group(0) + token.info = "entity" + + state.pos += len(match.group(0)) + return True + + return False diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/escape.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/escape.py new file mode 100644 index 0000000000000000000000000000000000000000..9f68b5dfad17fdcfe164ab4a8ef0761051b46efb --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/escape.py @@ -0,0 +1,92 @@ +""" +Process escaped chars and hardbreaks +""" +from ..common.utils import isStrSpace +from .state_inline import StateInline + + +def escape(state: StateInline, silent: bool) -> bool: + """Process escaped chars and hardbreaks.""" + pos = state.pos + maximum = state.posMax + + if state.src[pos] != "\\": + return False + + pos += 1 + + # '\' at the end of the inline block + if pos >= maximum: + return False + + ch1 = state.src[pos] + ch1_ord = ord(ch1) + if ch1 == "\n": + if not silent: + state.push("hardbreak", "br", 0) + pos += 1 + # skip leading whitespaces from next line + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch): + break + pos += 1 + + state.pos = pos + return True + + escapedStr = state.src[pos] + + if ch1_ord >= 0xD800 and ch1_ord <= 0xDBFF and pos + 1 < maximum: + ch2 = state.src[pos + 1] + ch2_ord = ord(ch2) + if ch2_ord >= 0xDC00 and ch2_ord <= 0xDFFF: + escapedStr += ch2 + pos += 1 + + origStr = "\\" + escapedStr + + if not silent: + token = state.push("text_special", "", 0) + token.content = escapedStr if ch1 in _ESCAPED else origStr + token.markup = origStr + token.info = "escape" + + state.pos = pos + 1 + return True + + +_ESCAPED = { + "!", + '"', + "#", + "$", + "%", + "&", + "'", + "(", + ")", + "*", + "+", + ",", + "-", + ".", + "/", + ":", + ";", + "<", + "=", + ">", + "?", + "@", + "[", + "\\", + "]", + "^", + "_", + "`", + "{", + "|", + "}", + "~", +} diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/fragments_join.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/fragments_join.py new file mode 100644 index 0000000000000000000000000000000000000000..f795c1364b8ac098b7a17f34cd31d7070280cf36 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/fragments_join.py @@ -0,0 +1,43 @@ +from .state_inline import StateInline + + +def fragments_join(state: StateInline) -> None: + """ + Clean up tokens after emphasis and strikethrough postprocessing: + merge adjacent text nodes into one and re-calculate all token levels + + This is necessary because initially emphasis delimiter markers (``*, _, ~``) + are treated as their own separate text tokens. Then emphasis rule either + leaves them as text (needed to merge with adjacent text) or turns them + into opening/closing tags (which messes up levels inside). + """ + level = 0 + maximum = len(state.tokens) + + curr = last = 0 + while curr < maximum: + # re-calculate levels after emphasis/strikethrough turns some text nodes + # into opening/closing tags + if state.tokens[curr].nesting < 0: + level -= 1 # closing tag + state.tokens[curr].level = level + if state.tokens[curr].nesting > 0: + level += 1 # opening tag + + if ( + state.tokens[curr].type == "text" + and curr + 1 < maximum + and state.tokens[curr + 1].type == "text" + ): + # collapse two adjacent text nodes + state.tokens[curr + 1].content = ( + state.tokens[curr].content + state.tokens[curr + 1].content + ) + else: + if curr != last: + state.tokens[last] = state.tokens[curr] + last += 1 + curr += 1 + + if curr != last: + del state.tokens[last:] diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/html_inline.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/html_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..9065e1d034da76270f7d3f1ba528132c8d57d341 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/html_inline.py @@ -0,0 +1,43 @@ +# Process html tags +from ..common.html_re import HTML_TAG_RE +from ..common.utils import isLinkClose, isLinkOpen +from .state_inline import StateInline + + +def isLetter(ch: int) -> bool: + lc = ch | 0x20 # to lower case + # /* a */ and /* z */ + return (lc >= 0x61) and (lc <= 0x7A) + + +def html_inline(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if not state.md.options.get("html", None): + return False + + # Check start + maximum = state.posMax + if state.src[pos] != "<" or pos + 2 >= maximum: + return False + + # Quick fail on second char + ch = state.src[pos + 1] + if ch not in ("!", "?", "/") and not isLetter(ord(ch)): # /* / */ + return False + + match = HTML_TAG_RE.search(state.src[pos:]) + if not match: + return False + + if not silent: + token = state.push("html_inline", "", 0) + token.content = state.src[pos : pos + len(match.group(0))] + + if isLinkOpen(token.content): + state.linkLevel += 1 + if isLinkClose(token.content): + state.linkLevel -= 1 + + state.pos += len(match.group(0)) + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/image.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/image.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a32a9f5880f3977c81f6b94d18751f93fa8561 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/image.py @@ -0,0 +1,148 @@ +# Process ![image]( "title") +from __future__ import annotations + +from ..common.utils import isStrSpace, normalizeReference +from ..token import Token +from .state_inline import StateInline + + +def image(state: StateInline, silent: bool) -> bool: + label = None + href = "" + oldPos = state.pos + max = state.posMax + + if state.src[state.pos] != "!": + return False + + if state.pos + 1 < state.posMax and state.src[state.pos + 1] != "[": + return False + + labelStart = state.pos + 2 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, False) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + + if pos < max and state.src[pos] == "(": + # + # Inline link + # + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= max: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax) + if pos < max and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + else: + title = "" + + if pos >= max or state.src[pos] != ")": + state.pos = oldPos + return False + + pos += 1 + + else: + # + # Link reference + # + if "references" not in state.env: + return False + + # /* [ */ + if pos < max and state.src[pos] == "[": + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = state.env["references"].get(label, None) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + content = state.src[labelStart:labelEnd] + + tokens: list[Token] = [] + state.md.inline.parse(content, state.md, state.env, tokens) + + token = state.push("image", "img", 0) + token.attrs = {"src": href, "alt": ""} + token.children = tokens or None + token.content = content + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.pos = pos + state.posMax = max + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/link.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/link.py new file mode 100644 index 0000000000000000000000000000000000000000..78cf9122f3b4ad740769cb7edd3e4cc49af46e00 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/link.py @@ -0,0 +1,151 @@ +# Process [link]( "stuff") + +from ..common.utils import isStrSpace, normalizeReference +from .state_inline import StateInline + + +def link(state: StateInline, silent: bool) -> bool: + href = "" + title = "" + label = None + oldPos = state.pos + maximum = state.posMax + start = state.pos + parseReference = True + + if state.src[state.pos] != "[": + return False + + labelStart = state.pos + 1 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, True) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + + if pos < maximum and state.src[pos] == "(": + # + # Inline link + # + + # might have found a valid shortcut link, disable reference parsing + parseReference = False + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= maximum: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax) + if pos < maximum and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= maximum or state.src[pos] != ")": + # parsing a valid shortcut link failed, fallback to reference + parseReference = True + + pos += 1 + + if parseReference: + # + # Link reference + # + if "references" not in state.env: + return False + + if pos < maximum and state.src[pos] == "[": + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = ( + state.env["references"][label] if label in state.env["references"] else None + ) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + state.pos = labelStart + state.posMax = labelEnd + + token = state.push("link_open", "a", 1) + token.attrs = {"href": href} + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.linkLevel += 1 + state.md.inline.tokenize(state) + state.linkLevel -= 1 + + token = state.push("link_close", "a", -1) + + state.pos = pos + state.posMax = maximum + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/linkify.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/linkify.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a181537d78867f8dfdf552b70f83be09bb2dd5 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/linkify.py @@ -0,0 +1,61 @@ +"""Process links like https://example.org/""" +import re + +from .state_inline import StateInline + +# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) +SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE) + + +def linkify(state: StateInline, silent: bool) -> bool: + """Rule for identifying plain-text links.""" + if not state.md.options.linkify: + return False + if state.linkLevel > 0: + return False + if not state.md.linkify: + raise ModuleNotFoundError("Linkify enabled but not installed.") + + pos = state.pos + maximum = state.posMax + + if ( + (pos + 3) > maximum + or state.src[pos] != ":" + or state.src[pos + 1] != "/" + or state.src[pos + 2] != "/" + ): + return False + + if not (match := SCHEME_RE.match(state.pending)): + return False + + proto = match.group(1) + if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])): + return False + url: str = link.url + + # disallow '*' at the end of the link (conflicts with emphasis) + url = url.rstrip("*") + + full_url = state.md.normalizeLink(url) + if not state.md.validateLink(full_url): + return False + + if not silent: + state.pending = state.pending[: -len(proto)] + + token = state.push("link_open", "a", 1) + token.attrs = {"href": full_url} + token.markup = "linkify" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "linkify" + token.info = "auto" + + state.pos += len(url) - len(proto) + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/newline.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/newline.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8f1db02da07b023aa9fdb08ee7af326f773da8 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/newline.py @@ -0,0 +1,43 @@ +"""Proceess '\n'.""" +from ..common.utils import charStrAt, isStrSpace +from .state_inline import StateInline + + +def newline(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "\n": + return False + + pmax = len(state.pending) - 1 + maximum = state.posMax + + # ' \n' -> hardbreak + # Lookup in pending chars is bad practice! Don't copy to other rules! + # Pending string is stored in concat mode, indexed lookups will cause + # conversion to flat mode. + if not silent: + if pmax >= 0 and charStrAt(state.pending, pmax) == " ": + if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ": + # Find whitespaces tail of pending chars. + ws = pmax - 1 + while ws >= 1 and charStrAt(state.pending, ws - 1) == " ": + ws -= 1 + state.pending = state.pending[:ws] + + state.push("hardbreak", "br", 0) + else: + state.pending = state.pending[:-1] + state.push("softbreak", "br", 0) + + else: + state.push("softbreak", "br", 0) + + pos += 1 + + # skip heading spaces for next line + while pos < maximum and isStrSpace(state.src[pos]): + pos += 1 + + state.pos = pos + return True diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/state_inline.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/state_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c491c4b7c9ae4117d60f447fdbf3c742f66f48 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/state_inline.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +from collections import namedtuple +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +from .._compat import DATACLASS_KWARGS +from ..common.utils import isMdAsciiPunct, isPunctChar, isWhiteSpace +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +@dataclass(**DATACLASS_KWARGS) +class Delimiter: + # Char code of the starting marker (number). + marker: int + + # Total length of these series of delimiters. + length: int + + # A position of the token this delimiter corresponds to. + token: int + + # If this delimiter is matched as a valid opener, `end` will be + # equal to its position, otherwise it's `-1`. + end: int + + # Boolean flags that determine if this delimiter could open or close + # an emphasis. + open: bool + close: bool + + level: bool | None = None + + +Scanned = namedtuple("Scanned", ["can_open", "can_close", "length"]) + + +class StateInline(StateBase): + def __init__( + self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token] + ) -> None: + self.src = src + self.env = env + self.md = md + self.tokens = outTokens + self.tokens_meta: list[dict[str, Any] | None] = [None] * len(outTokens) + + self.pos = 0 + self.posMax = len(self.src) + self.level = 0 + self.pending = "" + self.pendingLevel = 0 + + # Stores { start: end } pairs. Useful for backtrack + # optimization of pairs parse (emphasis, strikes). + self.cache: dict[int, int] = {} + + # List of emphasis-like delimiters for current tag + self.delimiters: list[Delimiter] = [] + + # Stack of delimiter lists for upper level tags + self._prev_delimiters: list[list[Delimiter]] = [] + + # backticklength => last seen position + self.backticks: dict[int, int] = {} + self.backticksScanned = False + + # Counter used to disable inline linkify-it execution + # inside and markdown links + self.linkLevel = 0 + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(pos=[{self.pos} of {self.posMax}], token={len(self.tokens)})" + ) + + def pushPending(self) -> Token: + token = Token("text", "", 0) + token.content = self.pending + token.level = self.pendingLevel + self.tokens.append(token) + self.pending = "" + return token + + def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token: + """Push new token to "stream". + If pending text exists - flush it as text token + """ + if self.pending: + self.pushPending() + + token = Token(ttype, tag, nesting) + token_meta = None + + if nesting < 0: + # closing tag + self.level -= 1 + self.delimiters = self._prev_delimiters.pop() + + token.level = self.level + + if nesting > 0: + # opening tag + self.level += 1 + self._prev_delimiters.append(self.delimiters) + self.delimiters = [] + token_meta = {"delimiters": self.delimiters} + + self.pendingLevel = self.level + self.tokens.append(token) + self.tokens_meta.append(token_meta) + return token + + def scanDelims(self, start: int, canSplitWord: bool) -> Scanned: + """ + Scan a sequence of emphasis-like markers, and determine whether + it can start an emphasis sequence or end an emphasis sequence. + + - start - position to scan from (it should point at a valid marker); + - canSplitWord - determine if these markers can be found inside a word + + """ + pos = start + maximum = self.posMax + marker = self.src[start] + + # treat beginning of the line as a whitespace + lastChar = self.src[start - 1] if start > 0 else " " + + while pos < maximum and self.src[pos] == marker: + pos += 1 + + count = pos - start + + # treat end of the line as a whitespace + nextChar = self.src[pos] if pos < maximum else " " + + isLastPunctChar = isMdAsciiPunct(ord(lastChar)) or isPunctChar(lastChar) + isNextPunctChar = isMdAsciiPunct(ord(nextChar)) or isPunctChar(nextChar) + + isLastWhiteSpace = isWhiteSpace(ord(lastChar)) + isNextWhiteSpace = isWhiteSpace(ord(nextChar)) + + left_flanking = not ( + isNextWhiteSpace + or (isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar)) + ) + right_flanking = not ( + isLastWhiteSpace + or (isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar)) + ) + + if not canSplitWord: + can_open = left_flanking and ((not right_flanking) or isLastPunctChar) + can_close = right_flanking and ((not left_flanking) or isNextPunctChar) + else: + can_open = left_flanking + can_close = right_flanking + + return Scanned(can_open, can_close, count) diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/strikethrough.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/strikethrough.py new file mode 100644 index 0000000000000000000000000000000000000000..ec816281d49b23d0774bf91db6600d996aaf8b06 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/strikethrough.py @@ -0,0 +1,127 @@ +# ~~strike through~~ +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool) -> bool: + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + ch = state.src[start] + + if silent: + return False + + if ch != "~": + return False + + scanned = state.scanDelims(state.pos, True) + length = scanned.length + + if length < 2: + return False + + if length % 2: + token = state.push("text", "", 0) + token.content = ch + length -= 1 + + i = 0 + while i < length: + token = state.push("text", "", 0) + token.content = ch + ch + state.delimiters.append( + Delimiter( + marker=ord(ch), + length=0, # disable "rule of 3" length checks meant for emphasis + token=len(state.tokens) - 1, + end=-1, + open=scanned.can_open, + close=scanned.can_close, + ) + ) + + i += 2 + + state.pos += scanned.length + + return True + + +def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None: + loneMarkers = [] + maximum = len(delimiters) + + i = 0 + while i < maximum: + startDelim = delimiters[i] + + if startDelim.marker != 0x7E: # /* ~ */ + i += 1 + continue + + if startDelim.end == -1: + i += 1 + continue + + endDelim = delimiters[startDelim.end] + + token = state.tokens[startDelim.token] + token.type = "s_open" + token.tag = "s" + token.nesting = 1 + token.markup = "~~" + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "s_close" + token.tag = "s" + token.nesting = -1 + token.markup = "~~" + token.content = "" + + if ( + state.tokens[endDelim.token - 1].type == "text" + and state.tokens[endDelim.token - 1].content == "~" + ): + loneMarkers.append(endDelim.token - 1) + + i += 1 + + # If a marker sequence has an odd number of characters, it's split + # like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the + # start of the sequence. + # + # So, we have to move all those markers after subsequent s_close tags. + # + while loneMarkers: + i = loneMarkers.pop() + j = i + 1 + + while (j < len(state.tokens)) and (state.tokens[j].type == "s_close"): + j += 1 + + j -= 1 + + if i != j: + token = state.tokens[j] + state.tokens[j] = state.tokens[i] + state.tokens[i] = token + + +def postProcess(state: StateInline) -> None: + """Walk through delimiter list and replace text tokens with tags.""" + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + _postProcess(state, state.delimiters) + + curr = 0 + while curr < maximum: + try: + curr_meta = tokens_meta[curr] + except IndexError: + pass + else: + if curr_meta and "delimiters" in curr_meta: + _postProcess(state, curr_meta["delimiters"]) + curr += 1 diff --git a/python_embeded/Lib/site-packages/markdown_it/rules_inline/text.py b/python_embeded/Lib/site-packages/markdown_it/rules_inline/text.py new file mode 100644 index 0000000000000000000000000000000000000000..f306b2e4cecde67aa3d363d3844e8b40a70a48b1 --- /dev/null +++ b/python_embeded/Lib/site-packages/markdown_it/rules_inline/text.py @@ -0,0 +1,53 @@ +# Skip text characters for text token, place those to pending buffer +# and increment current pos +from .state_inline import StateInline + +# Rule to skip pure text +# '{}$%@~+=:' reserved for extensions + +# !!!! Don't confuse with "Markdown ASCII Punctuation" chars +# http://spec.commonmark.org/0.15/#ascii-punctuation-character + + +_TerminatorChars = { + "\n", + "!", + "#", + "$", + "%", + "&", + "*", + "+", + "-", + ":", + "<", + "=", + ">", + "@", + "[", + "\\", + "]", + "^", + "_", + "`", + "{", + "}", + "~", +} + + +def text(state: StateInline, silent: bool) -> bool: + pos = state.pos + posMax = state.posMax + while (pos < posMax) and state.src[pos] not in _TerminatorChars: + pos += 1 + + if pos == state.pos: + return False + + if not silent: + state.pending += state.src[state.pos : pos] + + state.pos = pos + + return True diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/__init__.py b/python_embeded/Lib/site-packages/matplotlib/axes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc31f17aae693cd914528513f52776167d7d8d2 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/__init__.py @@ -0,0 +1,18 @@ +from . import _base +from ._axes import Axes + +# Backcompat. +Subplot = Axes + + +class _SubplotBaseMeta(type): + def __instancecheck__(self, obj): + return (isinstance(obj, _base._AxesBase) + and obj.get_subplotspec() is not None) + + +class SubplotBase(metaclass=_SubplotBaseMeta): + pass + + +def subplot_class_factory(cls): return cls diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/__init__.pyi b/python_embeded/Lib/site-packages/matplotlib/axes/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7df38b8bde9edc06720e08f41c245ab8d61fc091 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/__init__.pyi @@ -0,0 +1,16 @@ +from typing import TypeVar + +from ._axes import Axes as Axes + + +_T = TypeVar("_T") + +# Backcompat. +Subplot = Axes + +class _SubplotBaseMeta(type): + def __instancecheck__(self, obj) -> bool: ... + +class SubplotBase(metaclass=_SubplotBaseMeta): ... + +def subplot_class_factory(cls: type[_T]) -> type[_T]: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_axes.py b/python_embeded/Lib/site-packages/matplotlib/axes/_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..91dcf5a58acfa50b55c821e5cef785ef6b97de05 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_axes.py @@ -0,0 +1,8868 @@ +import functools +import itertools +import logging +import math +from numbers import Integral, Number, Real + +import re +import numpy as np + +import matplotlib as mpl +import matplotlib.category # Register category unit converter as side effect. +import matplotlib.cbook as cbook +import matplotlib.collections as mcoll +import matplotlib.colorizer as mcolorizer +import matplotlib.colors as mcolors +import matplotlib.contour as mcontour +import matplotlib.dates # noqa: F401, Register date unit converter as side effect. +import matplotlib.image as mimage +import matplotlib.inset as minset +import matplotlib.legend as mlegend +import matplotlib.lines as mlines +import matplotlib.markers as mmarkers +import matplotlib.mlab as mlab +import matplotlib.patches as mpatches +import matplotlib.path as mpath +import matplotlib.quiver as mquiver +import matplotlib.stackplot as mstack +import matplotlib.streamplot as mstream +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +import matplotlib.tri as mtri +import matplotlib.units as munits +from matplotlib import _api, _docstring, _preprocess_data +from matplotlib.axes._base import ( + _AxesBase, _TransformedBoundsLocator, _process_plot_format) +from matplotlib.axes._secondary_axes import SecondaryAxis +from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer +from matplotlib.transforms import _ScaledRotation + +_log = logging.getLogger(__name__) + + +# The axes module contains all the wrappers to plotting functions. +# All the other methods should go in the _AxesBase class. + + +def _make_axes_method(func): + """ + Patch the qualname for functions that are directly added to Axes. + + Some Axes functionality is defined in functions in other submodules. + These are simply added as attributes to Axes. As a result, their + ``__qualname__`` is e.g. only "table" and not "Axes.table". This + function fixes that. + + Note that the function itself is patched, so that + ``matplotlib.table.table.__qualname__` will also show "Axes.table". + However, since these functions are not intended to be standalone, + this is bearable. + """ + func.__qualname__ = f"Axes.{func.__name__}" + return func + + +@_docstring.interpd +class Axes(_AxesBase): + """ + An Axes object encapsulates all the elements of an individual (sub-)plot in + a figure. + + It contains most of the (sub-)plot elements: `~.axis.Axis`, + `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc., + and sets the coordinate system. + + Like all visible elements in a figure, Axes is an `.Artist` subclass. + + The `Axes` instance supports callbacks through a callbacks attribute which + is a `~.cbook.CallbackRegistry` instance. The events you can connect to + are 'xlim_changed' and 'ylim_changed' and the callback will be called with + func(*ax*) where *ax* is the `Axes` instance. + + .. note:: + + As a user, you do not instantiate Axes directly, but use Axes creation + methods instead; e.g. from `.pyplot` or `.Figure`: + `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` or `.Figure.add_axes`. + + """ + ### Labelling, legend and texts + + def get_title(self, loc="center"): + """ + Get an Axes title. + + Get one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + loc : {'center', 'left', 'right'}, str, default: 'center' + Which title to return. + + Returns + ------- + str + The title text string. + + """ + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + return title.get_text() + + def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, + **kwargs): + """ + Set a title for the Axes. + + Set one of the three available Axes titles. The available titles + are positioned above the Axes in the center, flush with the left + edge, and flush with the right edge. + + Parameters + ---------- + label : str + Text to use for the title + + fontdict : dict + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_title(..., **fontdict)``. + + A dictionary controlling the appearance of the title text, + the default *fontdict* is:: + + {'fontsize': rcParams['axes.titlesize'], + 'fontweight': rcParams['axes.titleweight'], + 'color': rcParams['axes.titlecolor'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc} + + loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation` + Which title to set. + + y : float, default: :rc:`axes.titley` + Vertical Axes location for the title (1.0 is the top). If + None (the default) and :rc:`axes.titley` is also None, y is + determined automatically to avoid decorators on the Axes. + + pad : float, default: :rc:`axes.titlepad` + The offset of the title from the top of the Axes, in points. + + Returns + ------- + `.Text` + The matplotlib text instance representing the title + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + Other keyword arguments are text properties, see `.Text` for a list + of valid text properties. + """ + if loc is None: + loc = mpl.rcParams['axes.titlelocation'] + + if y is None: + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + else: + self._autotitlepos = False + kwargs['y'] = y + + titles = {'left': self._left_title, + 'center': self.title, + 'right': self._right_title} + title = _api.check_getitem(titles, loc=loc.lower()) + default = { + 'fontsize': mpl.rcParams['axes.titlesize'], + 'fontweight': mpl.rcParams['axes.titleweight'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc.lower()} + titlecolor = mpl.rcParams['axes.titlecolor'] + if not cbook._str_lower_equal(titlecolor, 'auto'): + default["color"] = titlecolor + if pad is None: + pad = mpl.rcParams['axes.titlepad'] + self._set_title_offset_trans(float(pad)) + title.set_text(label) + title.update(default) + if fontdict is not None: + title.update(fontdict) + title._internal_update(kwargs) + return title + + def get_legend_handles_labels(self, legend_handler_map=None): + """ + Return handles and labels for legend + + ``ax.legend()`` is equivalent to :: + + h, l = ax.get_legend_handles_labels() + ax.legend(h, l) + """ + # pass through to legend. + handles, labels = mlegend._get_legend_handles_labels( + [self], legend_handler_map) + return handles, labels + + @_docstring.interpd + def legend(self, *args, **kwargs): + """ + Place a legend on the Axes. + + Call signatures:: + + legend() + legend(handles, labels) + legend(handles=handles) + legend(labels) + + The call signatures correspond to the following different ways to use + this method: + + **1. Automatic detection of elements to be shown in the legend** + + The elements to be added to the legend are automatically determined, + when you do not pass in any extra arguments. + + In this case, the labels are taken from the artist. You can specify + them either at artist creation or by calling the + :meth:`~.Artist.set_label` method on the artist:: + + ax.plot([1, 2, 3], label='Inline label') + ax.legend() + + or:: + + line, = ax.plot([1, 2, 3]) + line.set_label('Label via method') + ax.legend() + + .. note:: + Specific artists can be excluded from the automatic legend element + selection by using a label starting with an underscore, "_". + A string starting with an underscore is the default label for all + artists, so calling `.Axes.legend` without any arguments and + without setting the labels manually will result in a ``UserWarning`` + and an empty legend being drawn. + + + **2. Explicitly listing the artists and labels in the legend** + + For full control of which artists have a legend entry, it is possible + to pass an iterable of legend artists followed by an iterable of + legend labels respectively:: + + ax.legend([line1, line2, line3], ['label1', 'label2', 'label3']) + + + **3. Explicitly listing the artists in the legend** + + This is similar to 2, but the labels are taken from the artists' + label properties. Example:: + + line1, = ax.plot([1, 2, 3], label='label1') + line2, = ax.plot([1, 2, 3], label='label2') + ax.legend(handles=[line1, line2]) + + + **4. Labeling existing plot elements** + + .. admonition:: Discouraged + + This call signature is discouraged, because the relation between + plot elements and labels is only implicit by their order and can + easily be mixed up. + + To make a legend for all artists on an Axes, call this function with + an iterable of strings, one for each legend item. For example:: + + ax.plot([1, 2, 3]) + ax.plot([5, 6, 7]) + ax.legend(['First line', 'Second line']) + + + Parameters + ---------- + handles : list of (`.Artist` or tuple of `.Artist`), optional + A list of Artists (lines, patches) to be added to the legend. + Use this together with *labels*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + The length of handles and labels should be the same in this + case. If they are not, they are truncated to the smaller length. + + If an entry contains a tuple, then the legend handler for all Artists in the + tuple will be placed alongside a single label. + + labels : list of str, optional + A list of labels to show next to the artists. + Use this together with *handles*, if you need full control on what + is shown in the legend and the automatic mechanism described above + is not sufficient. + + Returns + ------- + `~matplotlib.legend.Legend` + + Other Parameters + ---------------- + %(_legend_kw_axes)s + + See Also + -------- + .Figure.legend + + Notes + ----- + Some artists are not supported by this function. See + :ref:`legend_guide` for details. + + Examples + -------- + .. plot:: gallery/text_labels_and_annotations/legend.py + """ + handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs) + self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) + self.legend_._remove_method = self._remove_legend + return self.legend_ + + def _remove_legend(self, legend): + self.legend_ = None + + def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs): + """ + Add a child inset Axes to this existing Axes. + + + Parameters + ---------- + bounds : [x0, y0, width, height] + Lower-left corner of inset Axes, and its width and height. + + transform : `.Transform` + Defaults to `ax.transAxes`, i.e. the units of *rect* are in + Axes-relative coordinates. + + projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ +'polar', 'rectilinear', str}, optional + The projection type of the inset `~.axes.Axes`. *str* is the name + of a custom projection, see `~matplotlib.projections`. The default + None results in a 'rectilinear' projection. + + polar : bool, default: False + If True, equivalent to projection='polar'. + + axes_class : subclass type of `~.axes.Axes`, optional + The `.axes.Axes` subclass that is instantiated. This parameter + is incompatible with *projection* and *polar*. See + :ref:`axisartist_users-guide-index` for examples. + + zorder : number + Defaults to 5 (same as `.Axes.legend`). Adjust higher or lower + to change whether it is above or below data plotted on the + parent Axes. + + **kwargs + Other keyword arguments are passed on to the inset Axes class. + + Returns + ------- + ax + The created `~.axes.Axes` instance. + + Examples + -------- + This example makes two inset Axes, the first is in Axes-relative + coordinates, and the second in data-coordinates:: + + fig, ax = plt.subplots() + ax.plot(range(10)) + axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15]) + axin2 = ax.inset_axes( + [5, 7, 2.3, 2.3], transform=ax.transData) + + """ + if transform is None: + transform = self.transAxes + kwargs.setdefault('label', 'inset_axes') + + # This puts the rectangle into figure-relative coordinates. + inset_locator = _TransformedBoundsLocator(bounds, transform) + bounds = inset_locator(self, None).bounds + fig = self.get_figure(root=False) + projection_class, pkw = fig._process_projection_requirements(**kwargs) + inset_ax = projection_class(fig, bounds, zorder=zorder, **pkw) + + # this locator lets the axes move if in data coordinates. + # it gets called in `ax.apply_aspect() (of all places) + inset_ax.set_axes_locator(inset_locator) + + self.add_child_axes(inset_ax) + + return inset_ax + + @_docstring.interpd + def indicate_inset(self, bounds=None, inset_ax=None, *, transform=None, + facecolor='none', edgecolor='0.5', alpha=0.5, + zorder=None, **kwargs): + """ + Add an inset indicator to the Axes. This is a rectangle on the plot + at the position indicated by *bounds* that optionally has lines that + connect the rectangle to an inset Axes (`.Axes.inset_axes`). + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + bounds : [x0, y0, width, height], optional + Lower-left corner of rectangle to be marked, and its width + and height. If not set, the bounds will be calculated from the + data limits of *inset_ax*, which must be supplied. + + inset_ax : `.Axes`, optional + An optional inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + transform : `.Transform` + Transform for the rectangle coordinates. Defaults to + ``ax.transAxes``, i.e. the units of *rect* are in Axes-relative + coordinates. + + facecolor : :mpltype:`color`, default: 'none' + Facecolor of the rectangle. + + edgecolor : :mpltype:`color`, default: '0.5' + Color of the rectangle and color of the connecting lines. + + alpha : float or None, default: 0.5 + Transparency of the rectangle and connector lines. If not + ``None``, this overrides any alpha value included in the + *facecolor* and *edgecolor* parameters. + + zorder : float, default: 4.99 + Drawing order of the rectangle and connector lines. The default, + 4.99, is just below the default level of inset Axes. + + **kwargs + Other keyword arguments are passed on to the `.Rectangle` patch: + + %(Rectangle:kwdoc)s + + Returns + ------- + inset_indicator : `.inset.InsetIndicator` + An artist which contains + + inset_indicator.rectangle : `.Rectangle` + The indicator frame. + + inset_indicator.connectors : 4-tuple of `.patches.ConnectionPatch` + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + + .. versionchanged:: 3.10 + Previously the rectangle and connectors tuple were returned. + """ + # to make the Axes connectors work, we need to apply the aspect to + # the parent Axes. + self.apply_aspect() + + if transform is None: + transform = self.transData + kwargs.setdefault('label', '_indicate_inset') + + indicator_patch = minset.InsetIndicator( + bounds, inset_ax=inset_ax, + facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, + zorder=zorder, transform=transform, **kwargs) + self.add_artist(indicator_patch) + + return indicator_patch + + def indicate_inset_zoom(self, inset_ax, **kwargs): + """ + Add an inset indicator rectangle to the Axes based on the axis + limits for an *inset_ax* and draw connectors between *inset_ax* + and the rectangle. + + Warnings + -------- + This method is experimental as of 3.0, and the API may change. + + Parameters + ---------- + inset_ax : `.Axes` + Inset Axes to draw connecting lines to. Two lines are + drawn connecting the indicator box to the inset Axes on corners + chosen so as to not overlap with the indicator box. + + **kwargs + Other keyword arguments are passed on to `.Axes.indicate_inset` + + Returns + ------- + inset_indicator : `.inset.InsetIndicator` + An artist which contains + + inset_indicator.rectangle : `.Rectangle` + The indicator frame. + + inset_indicator.connectors : 4-tuple of `.patches.ConnectionPatch` + The four connector lines connecting to (lower_left, upper_left, + lower_right upper_right) corners of *inset_ax*. Two lines are + set with visibility to *False*, but the user can set the + visibility to True if the automatic choice is not deemed correct. + + .. versionchanged:: 3.10 + Previously the rectangle and connectors tuple were returned. + """ + + return self.indicate_inset(None, inset_ax, **kwargs) + + @_docstring.interpd + def secondary_xaxis(self, location, functions=None, *, transform=None, **kwargs): + """ + Add a second x-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the xaxis. + + %(_secax_docstring)s + + Examples + -------- + The main axis shows frequency, and the secondary axis shows period. + + .. plot:: + + fig, ax = plt.subplots() + ax.loglog(range(1, 360, 5), range(1, 360, 5)) + ax.set_xlabel('frequency [Hz]') + + def invert(x): + # 1/x with special treatment of x == 0 + x = np.array(x).astype(float) + near_zero = np.isclose(x, 0) + x[near_zero] = np.inf + x[~near_zero] = 1 / x[~near_zero] + return x + + # the inverse of 1/x is itself + secax = ax.secondary_xaxis('top', functions=(invert, invert)) + secax.set_xlabel('Period [s]') + plt.show() + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at y=0 + secax = ax.secondary_xaxis(0, transform=ax.transData) + """ + if not (location in ['top', 'bottom'] or isinstance(location, Real)): + raise ValueError('secondary_xaxis location must be either ' + 'a float or "top"/"bottom"') + + secondary_ax = SecondaryAxis(self, 'x', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.interpd + def secondary_yaxis(self, location, functions=None, *, transform=None, **kwargs): + """ + Add a second y-axis to this `~.axes.Axes`. + + For example if we want to have a second scale for the data plotted on + the yaxis. + + %(_secax_docstring)s + + Examples + -------- + Add a secondary Axes that converts from radians to degrees + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(1, 360, 5), range(1, 360, 5)) + ax.set_ylabel('degrees') + secax = ax.secondary_yaxis('right', functions=(np.deg2rad, + np.rad2deg)) + secax.set_ylabel('radians') + + To add a secondary axis relative to your data, you can pass a transform + to the new axis. + + .. plot:: + + fig, ax = plt.subplots() + ax.plot(range(0, 5), range(-1, 4)) + + # Pass 'ax.transData' as a transform to place the axis + # relative to your data at x=3 + secax = ax.secondary_yaxis(3, transform=ax.transData) + """ + if not (location in ['left', 'right'] or isinstance(location, Real)): + raise ValueError('secondary_yaxis location must be either ' + 'a float or "left"/"right"') + + secondary_ax = SecondaryAxis(self, 'y', location, functions, + transform, **kwargs) + self.add_child_axes(secondary_ax) + return secondary_ax + + @_docstring.interpd + def text(self, x, y, s, fontdict=None, **kwargs): + """ + Add text to the Axes. + + Add the text *s* to the Axes at location *x*, *y* in data coordinates, + with a default ``horizontalalignment`` on the ``left`` and + ``verticalalignment`` at the ``baseline``. See + :doc:`/gallery/text_labels_and_annotations/text_alignment`. + + Parameters + ---------- + x, y : float + The position to place the text. By default, this is in data + coordinates. The coordinate system can be changed using the + *transform* parameter. + + s : str + The text. + + fontdict : dict, default: None + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``text(..., **fontdict)``. + + A dictionary to override the default text properties. If fontdict + is None, the defaults are determined by `.rcParams`. + + Returns + ------- + `.Text` + The created `.Text` instance. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties. + Other miscellaneous text parameters. + + %(Text:kwdoc)s + + Examples + -------- + Individual keyword arguments can be used to override any given + parameter:: + + >>> text(x, y, s, fontsize=12) + + The default transform specifies that text is in data coords, + alternatively, you can specify text in axis coords ((0, 0) is + lower-left and (1, 1) is upper-right). The example below places + text in the center of the Axes:: + + >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', + ... verticalalignment='center', transform=ax.transAxes) + + You can put a rectangular box around the text instance (e.g., to + set a background color) by using the keyword *bbox*. *bbox* is + a dictionary of `~matplotlib.patches.Rectangle` + properties. For example:: + + >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5)) + """ + effective_kwargs = { + 'verticalalignment': 'baseline', + 'horizontalalignment': 'left', + 'transform': self.transData, + 'clip_on': False, + **(fontdict if fontdict is not None else {}), + **kwargs, + } + t = mtext.Text(x, y, text=s, **effective_kwargs) + if t.get_clip_path() is None: + t.set_clip_path(self.patch) + self._add_text(t) + return t + + @_docstring.interpd + def annotate(self, text, xy, xytext=None, xycoords='data', textcoords=None, + arrowprops=None, annotation_clip=None, **kwargs): + # Signature must match Annotation. This is verified in + # test_annotate_signature(). + a = mtext.Annotation(text, xy, xytext=xytext, xycoords=xycoords, + textcoords=textcoords, arrowprops=arrowprops, + annotation_clip=annotation_clip, **kwargs) + a.set_transform(mtransforms.IdentityTransform()) + if kwargs.get('clip_on', False) and a.get_clip_path() is None: + a.set_clip_path(self.patch) + self._add_text(a) + return a + annotate.__doc__ = mtext.Annotation.__init__.__doc__ + #### Lines and spans + + @_docstring.interpd + def axhline(self, y=0, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal line spanning the whole or fraction of the Axes. + + Note: If you want to set x-limits in data coordinates, use + `~.Axes.hlines` instead. + + Parameters + ---------- + y : float, default: 0 + y position in :ref:`data coordinates `. + + xmin : float, default: 0 + The start x-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the far left of the plot, + 1 the far right of the plot. + + xmax : float, default: 1 + The end x-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the far left of the plot, + 1 the far right of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + A `.Line2D` specified via two points ``(xmin, y)``, ``(xmax, y)``. + Its transform is set such that *x* is in + :ref:`axes coordinates ` and *y* is in + :ref:`data coordinates `. + + This is still a generic line and the horizontal character is only + realized through using identical *y* values for both points. Thus, + if you want to change the *y* value later, you have to provide two + values ``line.set_ydata([3, 3])``. + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + hlines : Add horizontal lines in data coordinates. + axhspan : Add a horizontal span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red hline at 'y' = 0 that spans the xrange:: + + >>> axhline(linewidth=4, color='r') + + * draw a default hline at 'y' = 1 that spans the xrange:: + + >>> axhline(y=1) + + * draw a default hline at 'y' = .5 that spans the middle half of + the xrange:: + + >>> axhline(y=.5, xmin=0.25, xmax=0.75) + """ + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axhline generates its own transform.") + ymin, ymax = self.get_ybound() + + # Strip away the units for comparison with non-unitized bounds. + yy, = self._process_unit_info([("y", y)], kwargs) + scaley = (yy < ymin) or (yy > ymax) + + trans = self.get_yaxis_transform(which='grid') + l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scaley: + self._request_autoscale_view("y") + return l + + @_docstring.interpd + def axvline(self, x=0, ymin=0, ymax=1, **kwargs): + """ + Add a vertical line spanning the whole or fraction of the Axes. + + Note: If you want to set y-limits in data coordinates, use + `~.Axes.vlines` instead. + + Parameters + ---------- + x : float, default: 0 + x position in :ref:`data coordinates `. + + ymin : float, default: 0 + The start y-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + ymax : float, default: 1 + The end y-position in :ref:`axes coordinates `. + Should be between 0 and 1, 0 being the bottom of the plot, 1 the + top of the plot. + + Returns + ------- + `~matplotlib.lines.Line2D` + A `.Line2D` specified via two points ``(x, ymin)``, ``(x, ymax)``. + Its transform is set such that *x* is in + :ref:`data coordinates ` and *y* is in + :ref:`axes coordinates `. + + This is still a generic line and the vertical character is only + realized through using identical *x* values for both points. Thus, + if you want to change the *x* value later, you have to provide two + values ``line.set_xdata([3, 3])``. + + Other Parameters + ---------------- + **kwargs + Valid keyword arguments are `.Line2D` properties, except for + 'transform': + + %(Line2D:kwdoc)s + + See Also + -------- + vlines : Add vertical lines in data coordinates. + axvspan : Add a vertical span (rectangle) across the axis. + axline : Add a line with an arbitrary slope. + + Examples + -------- + * draw a thick red vline at *x* = 0 that spans the yrange:: + + >>> axvline(linewidth=4, color='r') + + * draw a default vline at *x* = 1 that spans the yrange:: + + >>> axvline(x=1) + + * draw a default vline at *x* = .5 that spans the middle half of + the yrange:: + + >>> axvline(x=.5, ymin=0.25, ymax=0.75) + """ + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + if "transform" in kwargs: + raise ValueError("'transform' is not allowed as a keyword " + "argument; axvline generates its own transform.") + xmin, xmax = self.get_xbound() + + # Strip away the units for comparison with non-unitized bounds. + xx, = self._process_unit_info([("x", x)], kwargs) + scalex = (xx < xmin) or (xx > xmax) + + trans = self.get_xaxis_transform(which='grid') + l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs) + self.add_line(l) + l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + if scalex: + self._request_autoscale_view("x") + return l + + @staticmethod + def _check_no_units(vals, names): + # Helper method to check that vals are not unitized + for val, name in zip(vals, names): + if not munits._is_natively_supported(val): + raise ValueError(f"{name} must be a single scalar value, " + f"but got {val}") + + @_docstring.interpd + def axline(self, xy1, xy2=None, *, slope=None, **kwargs): + """ + Add an infinitely long straight line. + + The line can be defined either by two points *xy1* and *xy2*, or + by one point *xy1* and a *slope*. + + This draws a straight line "on the screen", regardless of the x and y + scales, and is thus also suitable for drawing exponential decays in + semilog plots, power laws in loglog plots, etc. However, *slope* + should only be used with linear scales; It has no clear meaning for + all other scales, and thus the behavior is undefined. Please specify + the line using the points *xy1*, *xy2* for non-linear scales. + + The *transform* keyword argument only applies to the points *xy1*, + *xy2*. The *slope* (if given) is always in data coordinates. This can + be used e.g. with ``ax.transAxes`` for drawing grid lines with a fixed + slope. + + Parameters + ---------- + xy1, xy2 : (float, float) + Points for the line to pass through. + Either *xy2* or *slope* has to be given. + slope : float, optional + The slope of the line. Either *xy2* or *slope* has to be given. + + Returns + ------- + `.AxLine` + + Other Parameters + ---------------- + **kwargs + Valid kwargs are `.Line2D` properties + + %(Line2D:kwdoc)s + + See Also + -------- + axhline : for horizontal lines + axvline : for vertical lines + + Examples + -------- + Draw a thick red line passing through (0, 0) and (1, 1):: + + >>> axline((0, 0), (1, 1), linewidth=4, color='r') + """ + if slope is not None and (self.get_xscale() != 'linear' or + self.get_yscale() != 'linear'): + raise TypeError("'slope' cannot be used with non-linear scales") + + datalim = [xy1] if xy2 is None else [xy1, xy2] + if "transform" in kwargs: + # if a transform is passed (i.e. line points not in data space), + # data limits should not be adjusted. + datalim = [] + + line = mlines.AxLine(xy1, xy2, slope, **kwargs) + # Like add_line, but correctly handling data limits. + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + if not line.get_label(): + line.set_label(f"_child{len(self._children)}") + self._children.append(line) + line._remove_method = self._children.remove + self.update_datalim(datalim) + + self._request_autoscale_view() + return line + + @_docstring.interpd + def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs): + """ + Add a horizontal span (rectangle) across the Axes. + + The rectangle spans from *ymin* to *ymax* vertically, and, by default, + the whole x-axis horizontally. The x-span can be set using *xmin* + (default: 0) and *xmax* (default: 1) which are in axis units; e.g. + ``xmin = 0.5`` always refers to the middle of the x-axis regardless of + the limits set by `~.Axes.set_xlim`. + + Parameters + ---------- + ymin : float + Lower y-coordinate of the span, in data units. + ymax : float + Upper y-coordinate of the span, in data units. + xmin : float, default: 0 + Lower x-coordinate of the span, in x-axis (0-1) units. + xmax : float, default: 1 + Upper x-coordinate of the span, in x-axis (0-1) units. + + Returns + ------- + `~matplotlib.patches.Rectangle` + Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axvspan : Add a vertical span across the Axes. + """ + # Strip units away. + self._check_no_units([xmin, xmax], ['xmin', 'xmax']) + (ymin, ymax), = self._process_unit_info([("y", [ymin, ymax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_yaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the x limits even though it shouldn't do so for an + # yaxis_transformed patch, so undo that update. + ix = self.dataLim.intervalx.copy() + mx = self.dataLim.minposx + self.add_patch(p) + self.dataLim.intervalx = ix + self.dataLim.minposx = mx + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("y") + return p + + @_docstring.interpd + def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): + """ + Add a vertical span (rectangle) across the Axes. + + The rectangle spans from *xmin* to *xmax* horizontally, and, by + default, the whole y-axis vertically. The y-span can be set using + *ymin* (default: 0) and *ymax* (default: 1) which are in axis units; + e.g. ``ymin = 0.5`` always refers to the middle of the y-axis + regardless of the limits set by `~.Axes.set_ylim`. + + Parameters + ---------- + xmin : float + Lower x-coordinate of the span, in data units. + xmax : float + Upper x-coordinate of the span, in data units. + ymin : float, default: 0 + Lower y-coordinate of the span, in y-axis units (0-1). + ymax : float, default: 1 + Upper y-coordinate of the span, in y-axis units (0-1). + + Returns + ------- + `~matplotlib.patches.Rectangle` + Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax). + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + axhspan : Add a horizontal span across the Axes. + + Examples + -------- + Draw a vertical, green, translucent rectangle from x = 1.25 to + x = 1.55 that spans the yrange of the Axes. + + >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) + + """ + # Strip units away. + self._check_no_units([ymin, ymax], ['ymin', 'ymax']) + (xmin, xmax), = self._process_unit_info([("x", [xmin, xmax])], kwargs) + + p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) + p.set_transform(self.get_xaxis_transform(which="grid")) + # For Rectangles and non-separable transforms, add_patch can be buggy + # and update the y limits even though it shouldn't do so for an + # xaxis_transformed patch, so undo that update. + iy = self.dataLim.intervaly.copy() + my = self.dataLim.minposy + self.add_patch(p) + self.dataLim.intervaly = iy + self.dataLim.minposy = my + p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS + self._request_autoscale_view("x") + return p + + @_api.make_keyword_only("3.10", "label") + @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], + label_namer="y") + def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot horizontal lines at each *y* from *xmin* to *xmax*. + + Parameters + ---------- + y : float or array-like + y-indexes where to plot the lines. + + xmin, xmax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color , default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + vlines : vertical lines + axhline : horizontal line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + xmin, xmax, y = self._process_unit_info( + [("x", xmin), ("x", xmax), ("y", y)], kwargs) + + if not np.iterable(y): + y = [y] + if not np.iterable(xmin): + xmin = [xmin] + if not np.iterable(xmax): + xmax = [xmax] + + # Create and combine masked_arrays from input + y, xmin, xmax = cbook._combine_masks(y, xmin, xmax) + y = np.ravel(y) + xmin = np.ravel(xmin) + xmax = np.ravel(xmax) + + masked_verts = np.ma.empty((len(y), 2, 2)) + masked_verts[:, 0, 0] = xmin + masked_verts[:, 0, 1] = y + masked_verts[:, 1, 0] = xmax + masked_verts[:, 1, 1] = y + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(y) > 0: + # Extreme values of xmin/xmax/y. Using masked_verts here handles + # the case of y being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_api.make_keyword_only("3.10", "label") + @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], + label_namer="x") + def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', + label='', **kwargs): + """ + Plot vertical lines at each *x* from *ymin* to *ymax*. + + Parameters + ---------- + x : float or array-like + x-indexes where to plot the lines. + + ymin, ymax : float or array-like + Respective beginning and end of each line. If scalars are + provided, all lines will have the same length. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + + linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid' + + label : str, default: '' + + Returns + ------- + `~matplotlib.collections.LineCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.LineCollection` properties. + + See Also + -------- + hlines : horizontal lines + axvline : vertical line across the Axes + """ + + # We do the conversion first since not all unitized data is uniform + x, ymin, ymax = self._process_unit_info( + [("x", x), ("y", ymin), ("y", ymax)], kwargs) + + if not np.iterable(x): + x = [x] + if not np.iterable(ymin): + ymin = [ymin] + if not np.iterable(ymax): + ymax = [ymax] + + # Create and combine masked_arrays from input + x, ymin, ymax = cbook._combine_masks(x, ymin, ymax) + x = np.ravel(x) + ymin = np.ravel(ymin) + ymax = np.ravel(ymax) + + masked_verts = np.ma.empty((len(x), 2, 2)) + masked_verts[:, 0, 0] = x + masked_verts[:, 0, 1] = ymin + masked_verts[:, 1, 0] = x + masked_verts[:, 1, 1] = ymax + + lines = mcoll.LineCollection(masked_verts, colors=colors, + linestyles=linestyles, label=label) + self.add_collection(lines, autolim=False) + lines._internal_update(kwargs) + + if len(x) > 0: + # Extreme values of x/ymin/ymax. Using masked_verts here handles + # the case of x being a masked *object* array (as can be generated + # e.g. by errorbar()), which would make nanmin/nanmax stumble. + updatex = True + updatey = True + if self.name == "rectilinear": + datalim = lines.get_datalim(self.transData) + t = lines.get_transform() + updatex, updatey = t.contains_branch_seperately(self.transData) + minx = np.nanmin(datalim.xmin) + maxx = np.nanmax(datalim.xmax) + miny = np.nanmin(datalim.ymin) + maxy = np.nanmax(datalim.ymax) + else: + minx = np.nanmin(masked_verts[..., 0]) + maxx = np.nanmax(masked_verts[..., 0]) + miny = np.nanmin(masked_verts[..., 1]) + maxy = np.nanmax(masked_verts[..., 1]) + + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners, updatex, updatey) + self._request_autoscale_view() + return lines + + @_api.make_keyword_only("3.10", "orientation") + @_preprocess_data(replace_names=["positions", "lineoffsets", + "linelengths", "linewidths", + "colors", "linestyles"]) + @_docstring.interpd + def eventplot(self, positions, orientation='horizontal', lineoffsets=1, + linelengths=1, linewidths=None, colors=None, alpha=None, + linestyles='solid', **kwargs): + """ + Plot identical parallel lines at the given positions. + + This type of plot is commonly used in neuroscience for representing + neural events, where it is usually called a spike raster, dot raster, + or raster plot. + + However, it is useful in any situation where you wish to show the + timing or position of multiple sets of discrete events, such as the + arrival times of people to a business on each day of the month or the + date of hurricanes each year of the last century. + + Parameters + ---------- + positions : array-like or list of array-like + A 1D array-like defines the positions of one sequence of events. + + Multiple groups of events may be passed as a list of array-likes. + Each group can be styled independently by passing lists of values + to *lineoffsets*, *linelengths*, *linewidths*, *colors* and + *linestyles*. + + Note that *positions* can be a 2D array, but in practice different + event groups usually have different counts so that one will use a + list of different-length arrays rather than a 2D array. + + orientation : {'horizontal', 'vertical'}, default: 'horizontal' + The direction of the event sequence: + + - 'horizontal': the events are arranged horizontally. + The indicator lines are vertical. + - 'vertical': the events are arranged vertically. + The indicator lines are horizontal. + + lineoffsets : float or array-like, default: 1 + The offset of the center of the lines from the origin, in the + direction orthogonal to *orientation*. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linelengths : float or array-like, default: 1 + The total height of the lines (i.e. the lines stretches from + ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The line width(s) of the event lines, in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + The color(s) of the event lines. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + alpha : float or array-like, default: 1 + The alpha blending value(s), between 0 (transparent) and 1 + (opaque). + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + linestyles : str or tuple or list of such values, default: 'solid' + Default is 'solid'. Valid strings are ['solid', 'dashed', + 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples + should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + + If *positions* is 2D, this can be a sequence with length matching + the length of *positions*. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Other keyword arguments are line collection properties. See + `.LineCollection` for a list of the valid properties. + + Returns + ------- + list of `.EventCollection` + The `.EventCollection` that were added. + + Notes + ----- + For *linelengths*, *linewidths*, *colors*, *alpha* and *linestyles*, if + only a single value is given, that value is applied to all lines. If an + array-like is given, it must have the same length as *positions*, and + each value will be applied to the corresponding row of the array. + + Examples + -------- + .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py + """ + + lineoffsets, linelengths = self._process_unit_info( + [("y", lineoffsets), ("y", linelengths)], kwargs) + + # fix positions, noting that it can be a list of lists: + if not np.iterable(positions): + positions = [positions] + elif any(np.iterable(position) for position in positions): + positions = [np.asanyarray(position) for position in positions] + else: + positions = [np.asanyarray(positions)] + + poss = [] + for position in positions: + poss += self._process_unit_info([("x", position)], kwargs) + positions = poss + + # prevent 'singular' keys from **kwargs dict from overriding the effect + # of 'plural' keyword arguments (e.g. 'color' overriding 'colors') + colors = cbook._local_over_kwdict(colors, kwargs, 'color') + linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth') + linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle') + + if not np.iterable(lineoffsets): + lineoffsets = [lineoffsets] + if not np.iterable(linelengths): + linelengths = [linelengths] + if not np.iterable(linewidths): + linewidths = [linewidths] + if not np.iterable(colors): + colors = [colors] + if not np.iterable(alpha): + alpha = [alpha] + if hasattr(linestyles, 'lower') or not np.iterable(linestyles): + linestyles = [linestyles] + + lineoffsets = np.asarray(lineoffsets) + linelengths = np.asarray(linelengths) + linewidths = np.asarray(linewidths) + + if len(lineoffsets) == 0: + raise ValueError('lineoffsets cannot be empty') + if len(linelengths) == 0: + raise ValueError('linelengths cannot be empty') + if len(linestyles) == 0: + raise ValueError('linestyles cannot be empty') + if len(linewidths) == 0: + raise ValueError('linewidths cannot be empty') + if len(alpha) == 0: + raise ValueError('alpha cannot be empty') + if len(colors) == 0: + colors = [None] + try: + # Early conversion of the colors into RGBA values to take care + # of cases like colors='0.5' or colors='C1'. (Issue #8193) + colors = mcolors.to_rgba_array(colors) + except ValueError: + # Will fail if any element of *colors* is None. But as long + # as len(colors) == 1 or len(positions), the rest of the + # code should process *colors* properly. + pass + + if len(lineoffsets) == 1 and len(positions) != 1: + lineoffsets = np.tile(lineoffsets, len(positions)) + lineoffsets[0] = 0 + lineoffsets = np.cumsum(lineoffsets) + if len(linelengths) == 1: + linelengths = np.tile(linelengths, len(positions)) + if len(linewidths) == 1: + linewidths = np.tile(linewidths, len(positions)) + if len(colors) == 1: + colors = list(colors) * len(positions) + if len(alpha) == 1: + alpha = list(alpha) * len(positions) + if len(linestyles) == 1: + linestyles = [linestyles] * len(positions) + + if len(lineoffsets) != len(positions): + raise ValueError('lineoffsets and positions are unequal sized ' + 'sequences') + if len(linelengths) != len(positions): + raise ValueError('linelengths and positions are unequal sized ' + 'sequences') + if len(linewidths) != len(positions): + raise ValueError('linewidths and positions are unequal sized ' + 'sequences') + if len(colors) != len(positions): + raise ValueError('colors and positions are unequal sized ' + 'sequences') + if len(alpha) != len(positions): + raise ValueError('alpha and positions are unequal sized ' + 'sequences') + if len(linestyles) != len(positions): + raise ValueError('linestyles and positions are unequal sized ' + 'sequences') + + colls = [] + for position, lineoffset, linelength, linewidth, color, alpha_, \ + linestyle in \ + zip(positions, lineoffsets, linelengths, linewidths, + colors, alpha, linestyles): + coll = mcoll.EventCollection(position, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + alpha=alpha_, + linestyle=linestyle) + self.add_collection(coll, autolim=False) + coll._internal_update(kwargs) + colls.append(coll) + + if len(positions) > 0: + # try to get min/max + min_max = [(np.min(_p), np.max(_p)) for _p in positions + if len(_p) > 0] + # if we have any non-empty positions, try to autoscale + if len(min_max) > 0: + mins, maxes = zip(*min_max) + minpos = np.min(mins) + maxpos = np.max(maxes) + + minline = (lineoffsets - linelengths).min() + maxline = (lineoffsets + linelengths).max() + + if orientation == "vertical": + corners = (minline, minpos), (maxline, maxpos) + else: # "horizontal" + corners = (minpos, minline), (maxpos, maxline) + self.update_datalim(corners) + self._request_autoscale_view() + + return colls + + #### Basic plotting + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + @_docstring.interpd + def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs): + """ + Plot y versus x as lines and/or markers. + + Call signatures:: + + plot([x], y, [fmt], *, data=None, **kwargs) + plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + The coordinates of the points or line nodes are given by *x*, *y*. + + The optional parameter *fmt* is a convenient way for defining basic + formatting like color, marker and linestyle. It's a shortcut string + notation described in the *Notes* section below. + + >>> plot(x, y) # plot x and y using default line style and color + >>> plot(x, y, 'bo') # plot x and y using blue circle markers + >>> plot(y) # plot y using x as index array 0..N-1 + >>> plot(y, 'r+') # ditto, but with red plusses + + You can use `.Line2D` properties as keyword arguments for more + control on the appearance. Line properties and *fmt* can be mixed. + The following two calls yield identical results: + + >>> plot(x, y, 'go--', linewidth=2, markersize=12) + >>> plot(x, y, color='green', marker='o', linestyle='dashed', + ... linewidth=2, markersize=12) + + When conflicting with *fmt*, keyword arguments take precedence. + + + **Plotting labelled data** + + There's a convenient way for plotting objects with labelled data (i.e. + data that can be accessed by index ``obj['y']``). Instead of giving + the data in *x* and *y*, you can provide the object in the *data* + parameter and just give the labels for *x* and *y*:: + + >>> plot('xlabel', 'ylabel', data=obj) + + All indexable objects are supported. This could e.g. be a `dict`, a + `pandas.DataFrame` or a structured numpy array. + + + **Plotting multiple sets of data** + + There are various ways to plot multiple sets of data. + + - The most straight forward way is just to call `plot` multiple times. + Example: + + >>> plot(x1, y1, 'bo') + >>> plot(x2, y2, 'go') + + - If *x* and/or *y* are 2D arrays, a separate data set will be drawn + for every column. If both *x* and *y* are 2D, they must have the + same shape. If only one of them is 2D with shape (N, m) the other + must have length N and will be used for every data set m. + + Example: + + >>> x = [1, 2, 3] + >>> y = np.array([[1, 2], [3, 4], [5, 6]]) + >>> plot(x, y) + + is equivalent to: + + >>> for col in range(y.shape[1]): + ... plot(x, y[:, col]) + + - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]* + groups:: + + >>> plot(x1, y1, 'g^', x2, y2, 'g-') + + In this case, any additional keyword argument applies to all + datasets. Also, this syntax cannot be combined with the *data* + parameter. + + By default, each line is assigned a different style specified by a + 'style cycle'. The *fmt* and line property parameters are only + necessary if you want explicit deviations from these defaults. + Alternatively, you can also change the style cycle using + :rc:`axes.prop_cycle`. + + + Parameters + ---------- + x, y : array-like or float + The horizontal / vertical coordinates of the data points. + *x* values are optional and default to ``range(len(y))``. + + Commonly, these parameters are 1D arrays. + + They can also be scalars, or two-dimensional (in that case, the + columns represent separate data sets). + + These arguments cannot be passed as keywords. + + fmt : str, optional + A format string, e.g. 'ro' for red circles. See the *Notes* + section for a full description of the format strings. + + Format strings are just an abbreviation for quickly setting + basic line properties. All of these and more can also be + controlled by keyword arguments. + + This argument cannot be passed as keyword. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + .. note:: + Technically there's a slight ambiguity in calls where the + second label is a valid *fmt*. ``plot('n', 'o', data=obj)`` + could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases, + the former interpretation is chosen, but a warning is issued. + You may suppress the warning by adding an empty format string + ``plot('n', 'o', '', data=obj)``. + + Returns + ------- + list of `.Line2D` + A list of lines representing the plotted data. + + Other Parameters + ---------------- + scalex, scaley : bool, default: True + These parameters determine if the view limits are adapted to the + data limits. The values are passed on to + `~.axes.Axes.autoscale_view`. + + **kwargs : `~matplotlib.lines.Line2D` properties, optional + *kwargs* are used to specify properties like a line label (for + auto legends), linewidth, antialiasing, marker face color. + Example:: + + >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) + >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') + + If you specify multiple lines with one plot call, the kwargs apply + to all those lines. In case the label object is iterable, each + element is used as labels for each set of data. + + Here is a list of available `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + scatter : XY scatter plot with markers of varying size and/or color ( + sometimes also called bubble chart). + + Notes + ----- + **Format Strings** + + A format string consists of a part for color, marker and line:: + + fmt = '[marker][line][color]' + + Each of them is optional. If not provided, the value from the style + cycle is used. Exception: If ``line`` is given, but no ``marker``, + the data will be a line without markers. + + Other combinations such as ``[color][marker][line]`` are also + supported, but note that their parsing may be ambiguous. + + **Markers** + + ============= =============================== + character description + ============= =============================== + ``'.'`` point marker + ``','`` pixel marker + ``'o'`` circle marker + ``'v'`` triangle_down marker + ``'^'`` triangle_up marker + ``'<'`` triangle_left marker + ``'>'`` triangle_right marker + ``'1'`` tri_down marker + ``'2'`` tri_up marker + ``'3'`` tri_left marker + ``'4'`` tri_right marker + ``'8'`` octagon marker + ``'s'`` square marker + ``'p'`` pentagon marker + ``'P'`` plus (filled) marker + ``'*'`` star marker + ``'h'`` hexagon1 marker + ``'H'`` hexagon2 marker + ``'+'`` plus marker + ``'x'`` x marker + ``'X'`` x (filled) marker + ``'D'`` diamond marker + ``'d'`` thin_diamond marker + ``'|'`` vline marker + ``'_'`` hline marker + ============= =============================== + + **Line Styles** + + ============= =============================== + character description + ============= =============================== + ``'-'`` solid line style + ``'--'`` dashed line style + ``'-.'`` dash-dot line style + ``':'`` dotted line style + ============= =============================== + + Example format strings:: + + 'b' # blue markers with default shape + 'or' # red circles + '-g' # green solid line + '--' # dashed line with default color + '^k:' # black triangle_up markers connected by a dotted line + + **Colors** + + The supported color abbreviations are the single letter codes + + ============= =============================== + character color + ============= =============================== + ``'b'`` blue + ``'g'`` green + ``'r'`` red + ``'c'`` cyan + ``'m'`` magenta + ``'y'`` yellow + ``'k'`` black + ``'w'`` white + ============= =============================== + + and the ``'CN'`` colors that index into the default property cycle. + + If the color is the only part of the format string, you can + additionally use any `matplotlib.colors` spec, e.g. full names + (``'green'``) or hex strings (``'#008000'``). + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + lines = [*self._get_lines(self, *args, data=data, **kwargs)] + for line in lines: + self.add_line(line) + if scalex: + self._request_autoscale_view("x") + if scaley: + self._request_autoscale_view("y") + return lines + + @_api.deprecated("3.9", alternative="plot") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.interpd + def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False, + **kwargs): + """ + Plot coercing the axis to treat floats as dates. + + .. deprecated:: 3.9 + + This method exists for historic reasons and will be removed in version 3.11. + + - ``datetime``-like data should directly be plotted using + `~.Axes.plot`. + - If you need to plot plain numeric data as :ref:`date-format` or + need to set a timezone, call ``ax.xaxis.axis_date`` / + ``ax.yaxis.axis_date`` before `~.Axes.plot`. See + `.Axis.axis_date`. + + Similar to `.plot`, this plots *y* vs. *x* as lines or markers. + However, the axis labels are formatted as dates depending on *xdate* + and *ydate*. Note that `.plot` will work with `datetime` and + `numpy.datetime64` objects without resorting to this method. + + Parameters + ---------- + x, y : array-like + The coordinates of the data points. If *xdate* or *ydate* is + *True*, the respective values *x* or *y* are interpreted as + :ref:`Matplotlib dates `. + + fmt : str, optional + The plot format string. For details, see the corresponding + parameter in `.plot`. + + tz : timezone string or `datetime.tzinfo`, default: :rc:`timezone` + The time zone to use in labeling dates. + + xdate : bool, default: True + If *True*, the *x*-axis will be interpreted as Matplotlib dates. + + ydate : bool, default: False + If *True*, the *y*-axis will be interpreted as Matplotlib dates. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + matplotlib.dates : Helper functions on dates. + matplotlib.dates.date2num : Convert dates to num. + matplotlib.dates.num2date : Convert num to dates. + matplotlib.dates.drange : Create an equally spaced sequence of dates. + + Notes + ----- + If you are using custom date tickers and formatters, it may be + necessary to set the formatters/locators after the call to + `.plot_date`. `.plot_date` will set the default tick locator to + `.AutoDateLocator` (if the tick locator is not already set to a + `.DateLocator` instance) and the default tick formatter to + `.AutoDateFormatter` (if the tick formatter is not already set to a + `.DateFormatter` instance). + """ + if xdate: + self.xaxis_date(tz) + if ydate: + self.yaxis_date(tz) + return self.plot(x, y, fmt, **kwargs) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def loglog(self, *args, **kwargs): + """ + Make a plot with log scaling on both the x- and y-axis. + + Call signatures:: + + loglog([x], y, [fmt], data=None, **kwargs) + loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + both the x-axis and the y-axis to log scaling. All the concepts and + parameters of plot can be used here as well. + + The additional parameters *base*, *subs* and *nonpositive* control the + x/y-axis properties. They are just forwarded to `.Axes.set_xscale` and + `.Axes.set_yscale`. To use different properties on the x-axis and the + y-axis, use e.g. + ``ax.set_xscale("log", base=10); ax.set_yscale("log", base=2)``. + + Parameters + ---------- + base : float, default: 10 + Base of the logarithm. + + subs : sequence, optional + The location of the minor ticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale`/`.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values can be masked as invalid, or clipped to a very + small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + dx = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **dx) + dy = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **dy) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in {*dx, *dy}}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def semilogx(self, *args, **kwargs): + """ + Make a plot with log scaling on the x-axis. + + Call signatures:: + + semilogx([x], y, [fmt], data=None, **kwargs) + semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the x-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + x-axis properties. They are just forwarded to `.Axes.set_xscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the x logarithm. + + subs : array-like, optional + The location of the minor xticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_xscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in x can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basex', 'subsx', 'nonposx']} + self.set_xscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + # @_preprocess_data() # let 'plot' do the unpacking.. + @_docstring.interpd + def semilogy(self, *args, **kwargs): + """ + Make a plot with log scaling on the y-axis. + + Call signatures:: + + semilogy([x], y, [fmt], data=None, **kwargs) + semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + + This is just a thin wrapper around `.plot` which additionally changes + the y-axis to log scaling. All the concepts and parameters of plot can + be used here as well. + + The additional parameters *base*, *subs*, and *nonpositive* control the + y-axis properties. They are just forwarded to `.Axes.set_yscale`. + + Parameters + ---------- + base : float, default: 10 + Base of the y logarithm. + + subs : array-like, optional + The location of the minor yticks. If *None*, reasonable locations + are automatically chosen depending on the number of decades in the + plot. See `.Axes.set_yscale` for details. + + nonpositive : {'mask', 'clip'}, default: 'clip' + Non-positive values in y can be masked as invalid, or clipped to a + very small positive number. + + **kwargs + All parameters supported by `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + d = {k: v for k, v in kwargs.items() + if k in ['base', 'subs', 'nonpositive', + 'basey', 'subsy', 'nonposy']} + self.set_yscale('log', **d) + return self.plot( + *args, **{k: v for k, v in kwargs.items() if k not in d}) + + @_preprocess_data(replace_names=["x"], label_namer="x") + def acorr(self, x, **kwargs): + """ + Plot the autocorrelation of *x*. + + Parameters + ---------- + x : array-like + Not run through Matplotlib's unit conversion, so this should + be a unit-less array. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the acorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the acorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If ``None``, will return all + ``2 * len(x) - 1`` lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + return self.xcorr(x, x, **kwargs) + + @_api.make_keyword_only("3.10", "normed") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, + usevlines=True, maxlags=10, **kwargs): + r""" + Plot the cross correlation between *x* and *y*. + + The correlation with lag k is defined as + :math:`\sum_n x[n+k] \cdot y^*[n]`, where :math:`y^*` is the complex + conjugate of :math:`y`. + + Parameters + ---------- + x, y : array-like of length n + Neither *x* nor *y* are run through Matplotlib's unit conversion, so + these should be unit-less arrays. + + detrend : callable, default: `.mlab.detrend_none` (no detrending) + A detrending function applied to *x* and *y*. It must have the + signature :: + + detrend(x: np.ndarray) -> np.ndarray + + normed : bool, default: True + If ``True``, input vectors are normalised to unit length. + + usevlines : bool, default: True + Determines the plot style. + + If ``True``, vertical lines are plotted from 0 to the xcorr value + using `.Axes.vlines`. Additionally, a horizontal line is plotted + at y=0 using `.Axes.axhline`. + + If ``False``, markers are plotted at the xcorr values using + `.Axes.plot`. + + maxlags : int, default: 10 + Number of lags to show. If None, will return all ``2 * len(x) - 1`` + lags. + + Returns + ------- + lags : array (length ``2*maxlags+1``) + The lag vector. + c : array (length ``2*maxlags+1``) + The auto correlation vector. + line : `.LineCollection` or `.Line2D` + `.Artist` added to the Axes of the correlation: + + - `.LineCollection` if *usevlines* is True. + - `.Line2D` if *usevlines* is False. + b : `~matplotlib.lines.Line2D` or None + Horizontal line at 0 if *usevlines* is True + None *usevlines* is False. + + Other Parameters + ---------------- + linestyle : `~matplotlib.lines.Line2D` property, optional + The linestyle for plotting the data points. + Only used if *usevlines* is ``False``. + + marker : str, default: 'o' + The marker for plotting the data points. + Only used if *usevlines* is ``False``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed to `.Axes.vlines` and + `.Axes.axhline` if *usevlines* is ``True``; otherwise they are + passed to `.Axes.plot`. + + Notes + ----- + The cross correlation is performed with `numpy.correlate` with + ``mode = "full"``. + """ + Nx = len(x) + if Nx != len(y): + raise ValueError('x and y must be equal length') + + x = detrend(np.asarray(x)) + y = detrend(np.asarray(y)) + + correls = np.correlate(x, y, mode="full") + + if normed: + correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y)) + + if maxlags is None: + maxlags = Nx - 1 + + if maxlags >= Nx or maxlags < 1: + raise ValueError('maxlags must be None or strictly ' + 'positive < %d' % Nx) + + lags = np.arange(-maxlags, maxlags + 1) + correls = correls[Nx - 1 - maxlags:Nx + maxlags] + + if usevlines: + a = self.vlines(lags, [0], correls, **kwargs) + # Make label empty so only vertical lines get a legend entry + kwargs.pop('label', '') + b = self.axhline(**kwargs) + else: + kwargs.setdefault('marker', 'o') + kwargs.setdefault('linestyle', 'None') + a, = self.plot(lags, correls, **kwargs) + b = None + return lags, correls, a, b + + #### Specialized plotting + + # @_preprocess_data() # let 'plot' do the unpacking.. + def step(self, x, y, *args, where='pre', data=None, **kwargs): + """ + Make a step plot. + + Call signatures:: + + step(x, y, [fmt], *, data=None, where='pre', **kwargs) + step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs) + + This is just a thin wrapper around `.plot` which changes some + formatting options. Most of the concepts and parameters of plot can be + used here as well. + + .. note:: + + This method uses a standard plot with a step drawstyle: The *x* + values are the reference positions and steps extend left/right/both + directions depending on *where*. + + For the common case where you know the values and edges of the + steps, use `~.Axes.stairs` instead. + + Parameters + ---------- + x : array-like + 1D sequence of x positions. It is assumed, but not checked, that + it is uniformly increasing. + + y : array-like + 1D sequence of y levels. + + fmt : str, optional + A format string, e.g. 'g' for a green line. See `.plot` for a more + detailed description. + + Note: While full format strings are accepted, it is recommended to + only specify the color. Line styles are currently ignored (use + the keyword argument *linestyle* instead). Markers are accepted + and plotted on the given positions, however, this is a rarely + needed feature for step plots. + + where : {'pre', 'post', 'mid'}, default: 'pre' + Define where the steps should be placed: + + - 'pre': The y value is continued constantly to the left from + every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the + value ``y[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the + value ``y[i]``. + - 'mid': Steps occur half-way between the *x* positions. + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*. + + **kwargs + Additional parameters are the same as those for `.plot`. + + Returns + ------- + list of `.Line2D` + Objects representing the plotted data. + """ + _api.check_in_list(('pre', 'post', 'mid'), where=where) + kwargs['drawstyle'] = 'steps-' + where + return self.plot(x, y, *args, data=data, **kwargs) + + @staticmethod + def _convert_dx(dx, x0, xconv, convert): + """ + Small helper to do logic of width conversion flexibly. + + *dx* and *x0* have units, but *xconv* has already been converted + to unitless (and is an ndarray). This allows the *dx* to have units + that are different from *x0*, but are still accepted by the + ``__add__`` operator of *x0*. + """ + + # x should be an array... + assert type(xconv) is np.ndarray + + if xconv.size == 0: + # xconv has already been converted, but maybe empty... + return convert(dx) + + try: + # attempt to add the width to x0; this works for + # datetime+timedelta, for instance + + # only use the first element of x and x0. This saves + # having to be sure addition works across the whole + # vector. This is particularly an issue if + # x0 and dx are lists so x0 + dx just concatenates the lists. + # We can't just cast x0 and dx to numpy arrays because that + # removes the units from unit packages like `pint` that + # wrap numpy arrays. + try: + x0 = cbook._safe_first_finite(x0) + except (TypeError, IndexError, KeyError): + pass + + try: + x = cbook._safe_first_finite(xconv) + except (TypeError, IndexError, KeyError): + x = xconv + + delist = False + if not np.iterable(dx): + dx = [dx] + delist = True + dx = [convert(x0 + ddx) - x for ddx in dx] + if delist: + dx = dx[0] + except (ValueError, TypeError, AttributeError): + # if the above fails (for any reason) just fallback to what + # we do by default and convert dx by itself. + dx = convert(dx) + return dx + + def _parse_bar_color_args(self, kwargs): + """ + Helper function to process color-related arguments of `.Axes.bar`. + + Argument precedence for facecolors: + + - kwargs['facecolor'] + - kwargs['color'] + - 'Result of ``self._get_patches_for_fill.get_next_color`` + + Argument precedence for edgecolors: + + - kwargs['edgecolor'] + - None + + Parameters + ---------- + self : Axes + + kwargs : dict + Additional kwargs. If these keys exist, we pop and process them: + 'facecolor', 'edgecolor', 'color' + Note: The dict is modified by this function. + + + Returns + ------- + facecolor + The facecolor. One or more colors as (N, 4) rgba array. + edgecolor + The edgecolor. Not normalized; may be any valid color spec or None. + """ + color = kwargs.pop('color', None) + + facecolor = kwargs.pop('facecolor', color) + edgecolor = kwargs.pop('edgecolor', None) + + facecolor = (facecolor if facecolor is not None + else self._get_patches_for_fill.get_next_color()) + + try: + facecolor = mcolors.to_rgba_array(facecolor) + except ValueError as err: + raise ValueError( + "'facecolor' or 'color' argument must be a valid color or" + "sequence of colors." + ) from err + + return facecolor, edgecolor + + @_preprocess_data() + @_docstring.interpd + def bar(self, x, height, width=0.8, bottom=None, *, align="center", + **kwargs): + r""" + Make a bar plot. + + The bars are positioned at *x* with the given *align*\ment. Their + dimensions are given by *height* and *width*. The vertical baseline + is *bottom* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + x : float or array-like + The x coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + Bars are often used for categorical data, i.e. string labels below + the bars. You can provide a list of strings directly to *x*. + ``bar(['A', 'B', 'C'], [1, 2, 3])`` is often a shorter and more + convenient notation compared to + ``bar(range(3), [1, 2, 3], tick_label=['A', 'B', 'C'])``. They are + equivalent as long as the names are unique. The explicit *tick_label* + notation draws the names in the sequence given. However, when having + duplicate values in categorical *x* data, these values map to the same + numerical x coordinate, and hence the corresponding bars are drawn on + top of each other. + + height : float or array-like + The height(s) of the bars. + + Note that if *bottom* has units (e.g. datetime), *height* should be in + units that are a difference from the value of *bottom* (e.g. timedelta). + + width : float or array-like, default: 0.8 + The width(s) of the bars. + + Note that if *x* has units (e.g. datetime), then *width* should be in + units that are a difference (e.g. timedelta) around the *x* values. + + bottom : float or array-like, default: 0 + The y coordinate(s) of the bottom side(s) of the bars. + + Note that if *bottom* has units, then the y-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the bars to the *x* coordinates: + + - 'center': Center the base on the *x* positions. + - 'edge': Align the left edges of the bars with the *x* positions. + + To align the bars on the right edge pass a negative *width* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. This is an alias for *facecolor*. + If both are given, *facecolor* takes precedence. + + facecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + If both *color* and *facecolor are given, *facecolor* takes precedence. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *x* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (Default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If *True*, set the y-axis to be log scale. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + barh : Plot a horizontal bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *bottom* values per + bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`. + """ + kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) + facecolor, edgecolor = self._parse_bar_color_args(kwargs) + + linewidth = kwargs.pop('linewidth', None) + hatch = kwargs.pop('hatch', None) + + # Because xerr and yerr will be passed to errorbar, most dimension + # checking and processing will be left to the errorbar method. + xerr = kwargs.pop('xerr', None) + yerr = kwargs.pop('yerr', None) + error_kw = kwargs.pop('error_kw', None) + error_kw = {} if error_kw is None else error_kw.copy() + ezorder = error_kw.pop('zorder', None) + if ezorder is None: + ezorder = kwargs.get('zorder', None) + if ezorder is not None: + # If using the bar zorder, increment slightly to make sure + # errorbars are drawn on top of bars + ezorder += 0.01 + error_kw.setdefault('zorder', ezorder) + ecolor = kwargs.pop('ecolor', 'k') + capsize = kwargs.pop('capsize', mpl.rcParams["errorbar.capsize"]) + error_kw.setdefault('ecolor', ecolor) + error_kw.setdefault('capsize', capsize) + + # The keyword argument *orientation* is used by barh() to defer all + # logic and drawing to bar(). It is considered internal and is + # intentionally not mentioned in the docstring. + orientation = kwargs.pop('orientation', 'vertical') + _api.check_in_list(['vertical', 'horizontal'], orientation=orientation) + log = kwargs.pop('log', False) + label = kwargs.pop('label', '') + tick_labels = kwargs.pop('tick_label', None) + + y = bottom # Matches barh call signature. + if orientation == 'vertical': + if y is None: + y = 0 + else: # horizontal + if x is None: + x = 0 + + if orientation == 'vertical': + # It is possible for y (bottom) to contain unit information. + # However, it is also possible for y=0 for the default and height + # to contain unit information. This will prioritize the units of y. + self._process_unit_info( + [("x", x), ("y", y), ("y", height)], kwargs, convert=False) + if log: + self.set_yscale('log', nonpositive='clip') + else: # horizontal + # It is possible for x (left) to contain unit information. + # However, it is also possible for x=0 for the default and width + # to contain unit information. This will prioritize the units of x. + self._process_unit_info( + [("x", x), ("x", width), ("y", y)], kwargs, convert=False) + if log: + self.set_xscale('log', nonpositive='clip') + + # lets do some conversions now since some types cannot be + # subtracted uniformly + if self.xaxis is not None: + x0 = x + x = np.asarray(self.convert_xunits(x)) + width = self._convert_dx(width, x0, x, self.convert_xunits) + if xerr is not None: + xerr = self._convert_dx(xerr, x0, x, self.convert_xunits) + if self.yaxis is not None: + y0 = y + y = np.asarray(self.convert_yunits(y)) + height = self._convert_dx(height, y0, y, self.convert_yunits) + if yerr is not None: + yerr = self._convert_dx(yerr, y0, y, self.convert_yunits) + + x, height, width, y, linewidth, hatch = np.broadcast_arrays( + # Make args iterable too. + np.atleast_1d(x), height, width, y, linewidth, hatch) + + # Now that units have been converted, set the tick locations. + if orientation == 'vertical': + tick_label_axis = self.xaxis + tick_label_position = x + else: # horizontal + tick_label_axis = self.yaxis + tick_label_position = y + + if not isinstance(label, str) and np.iterable(label): + bar_container_label = '_nolegend_' + patch_labels = label + else: + bar_container_label = label + patch_labels = ['_nolegend_'] * len(x) + if len(patch_labels) != len(x): + raise ValueError(f'number of labels ({len(patch_labels)}) ' + f'does not match number of bars ({len(x)}).') + + linewidth = itertools.cycle(np.atleast_1d(linewidth)) + hatch = itertools.cycle(np.atleast_1d(hatch)) + facecolor = itertools.chain(itertools.cycle(facecolor), + # Fallback if color == "none". + itertools.repeat('none')) + if edgecolor is None: + edgecolor = itertools.repeat(None) + else: + edgecolor = itertools.chain( + itertools.cycle(mcolors.to_rgba_array(edgecolor)), + # Fallback if edgecolor == "none". + itertools.repeat('none')) + + # We will now resolve the alignment and really have + # left, bottom, width, height vectors + _api.check_in_list(['center', 'edge'], align=align) + if align == 'center': + if orientation == 'vertical': + try: + left = x - width / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters x ({x.dtype}) ' + f'and width ({width.dtype}) ' + f'are incompatible') from e + bottom = y + else: # horizontal + try: + bottom = y - height / 2 + except TypeError as e: + raise TypeError(f'the dtypes of parameters y ({y.dtype}) ' + f'and height ({height.dtype}) ' + f'are incompatible') from e + left = x + else: # edge + left = x + bottom = y + + patches = [] + args = zip(left, bottom, width, height, facecolor, edgecolor, linewidth, + hatch, patch_labels) + for l, b, w, h, c, e, lw, htch, lbl in args: + r = mpatches.Rectangle( + xy=(l, b), width=w, height=h, + facecolor=c, + edgecolor=e, + linewidth=lw, + label=lbl, + hatch=htch, + ) + r._internal_update(kwargs) + r.get_path()._interpolation_steps = 100 + if orientation == 'vertical': + r.sticky_edges.y.append(b) + else: # horizontal + r.sticky_edges.x.append(l) + self.add_patch(r) + patches.append(r) + + if xerr is not None or yerr is not None: + if orientation == 'vertical': + # using list comps rather than arrays to preserve unit info + ex = [l + 0.5 * w for l, w in zip(left, width)] + ey = [b + h for b, h in zip(bottom, height)] + + else: # horizontal + # using list comps rather than arrays to preserve unit info + ex = [l + w for l, w in zip(left, width)] + ey = [b + 0.5 * h for b, h in zip(bottom, height)] + + error_kw.setdefault("label", '_nolegend_') + + errorbar = self.errorbar(ex, ey, yerr=yerr, xerr=xerr, fmt='none', + **error_kw) + else: + errorbar = None + + self._request_autoscale_view() + + if orientation == 'vertical': + datavalues = height + else: # horizontal + datavalues = width + + bar_container = BarContainer(patches, errorbar, datavalues=datavalues, + orientation=orientation, + label=bar_container_label) + self.add_container(bar_container) + + if tick_labels is not None: + tick_labels = np.broadcast_to(tick_labels, len(patches)) + tick_label_axis.set_ticks(tick_label_position) + tick_label_axis.set_ticklabels(tick_labels) + + return bar_container + + # @_preprocess_data() # let 'bar' do the unpacking.. + @_docstring.interpd + def barh(self, y, width, height=0.8, left=None, *, align="center", + data=None, **kwargs): + r""" + Make a horizontal bar plot. + + The bars are positioned at *y* with the given *align*\ment. Their + dimensions are given by *width* and *height*. The horizontal baseline + is *left* (default 0). + + Many parameters can take either a single value applying to all bars + or a sequence of values, one for each bar. + + Parameters + ---------- + y : float or array-like + The y coordinates of the bars. See also *align* for the + alignment of the bars to the coordinates. + + Bars are often used for categorical data, i.e. string labels below + the bars. You can provide a list of strings directly to *y*. + ``barh(['A', 'B', 'C'], [1, 2, 3])`` is often a shorter and more + convenient notation compared to + ``barh(range(3), [1, 2, 3], tick_label=['A', 'B', 'C'])``. They are + equivalent as long as the names are unique. The explicit *tick_label* + notation draws the names in the sequence given. However, when having + duplicate values in categorical *y* data, these values map to the same + numerical y coordinate, and hence the corresponding bars are drawn on + top of each other. + + width : float or array-like + The width(s) of the bars. + + Note that if *left* has units (e.g. datetime), *width* should be in + units that are a difference from the value of *left* (e.g. timedelta). + + height : float or array-like, default: 0.8 + The heights of the bars. + + Note that if *y* has units (e.g. datetime), then *height* should be in + units that are a difference (e.g. timedelta) around the *y* values. + + left : float or array-like, default: 0 + The x coordinates of the left side(s) of the bars. + + Note that if *left* has units, then the x-axis will get a Locator and + Formatter appropriate for the units (e.g. dates, or categorical). + + align : {'center', 'edge'}, default: 'center' + Alignment of the base to the *y* coordinates*: + + - 'center': Center the bars on the *y* positions. + - 'edge': Align the bottom edges of the bars with the *y* + positions. + + To align the bars on the top edge pass a negative *height* and + ``align='edge'``. + + Returns + ------- + `.BarContainer` + Container with all the bars and optionally errorbars. + + Other Parameters + ---------------- + color : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar faces. + + edgecolor : :mpltype:`color` or list of :mpltype:`color`, optional + The colors of the bar edges. + + linewidth : float or array-like, optional + Width of the bar edge(s). If 0, don't draw edges. + + tick_label : str or list of str, optional + The tick labels of the bars. + Default: None (Use default numeric labels.) + + label : str or list of str, optional + A single label is attached to the resulting `.BarContainer` as a + label for the whole dataset. + If a list is provided, it must be the same length as *y* and + labels the individual bars. Repeated labels are not de-duplicated + and will cause repeated label entries, so this is best used when + bars also differ in style (e.g., by passing a list to *color*.) + + xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional + If not *None*, add horizontal / vertical errorbars to the bar tips. + The values are +/- sizes relative to the data: + + - scalar: symmetric +/- values for all bars + - shape(N,): symmetric +/- values for each bar + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. (default) + + See :doc:`/gallery/statistics/errorbar_features` for an example on + the usage of *xerr* and *yerr*. + + ecolor : :mpltype:`color` or list of :mpltype:`color`, default: 'black' + The line color of the errorbars. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + error_kw : dict, optional + Dictionary of keyword arguments to be passed to the + `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined + here take precedence over the independent keyword arguments. + + log : bool, default: False + If ``True``, set the x-axis to be log scale. + + data : indexable object, optional + If given, all parameters also accept a string ``s``, which is + interpreted as ``data[s]`` if ``s`` is a key in ``data``. + + **kwargs : `.Rectangle` properties + + %(Rectangle:kwdoc)s + + See Also + -------- + bar : Plot a vertical bar plot. + + Notes + ----- + Stacked bars can be achieved by passing individual *left* values per + bar. See + :doc:`/gallery/lines_bars_and_markers/horizontal_barchart_distribution`. + """ + kwargs.setdefault('orientation', 'horizontal') + patches = self.bar(x=left, height=height, width=width, bottom=y, + align=align, data=data, **kwargs) + return patches + + def bar_label(self, container, labels=None, *, fmt="%g", label_type="edge", + padding=0, **kwargs): + """ + Label a bar plot. + + Adds labels to bars in the given `.BarContainer`. + You may need to adjust the axis limits to fit the labels. + + Parameters + ---------- + container : `.BarContainer` + Container with all the bars and optionally errorbars, likely + returned from `.bar` or `.barh`. + + labels : array-like, optional + A list of label texts, that should be displayed. If not given, the + label texts will be the data values formatted with *fmt*. + + fmt : str or callable, default: '%g' + An unnamed %-style or {}-style format string for the label or a + function to call with the value as the first argument. + When *fmt* is a string and can be interpreted in both formats, + %-style takes precedence over {}-style. + + .. versionadded:: 3.7 + Support for {}-style format string and callables. + + label_type : {'edge', 'center'}, default: 'edge' + The label type. Possible values: + + - 'edge': label placed at the end-point of the bar segment, and the + value displayed will be the position of that end-point. + - 'center': label placed in the center of the bar segment, and the + value displayed will be the length of that segment. + (useful for stacked bars, i.e., + :doc:`/gallery/lines_bars_and_markers/bar_label_demo`) + + padding : float, default: 0 + Distance of label from the end of the bar, in points. + + **kwargs + Any remaining keyword arguments are passed through to + `.Axes.annotate`. The alignment parameters ( + *horizontalalignment* / *ha*, *verticalalignment* / *va*) are + not supported because the labels are automatically aligned to + the bars. + + Returns + ------- + list of `.Annotation` + A list of `.Annotation` instances for the labels. + """ + for key in ['horizontalalignment', 'ha', 'verticalalignment', 'va']: + if key in kwargs: + raise ValueError( + f"Passing {key!r} to bar_label() is not supported.") + + a, b = self.yaxis.get_view_interval() + y_inverted = a > b + c, d = self.xaxis.get_view_interval() + x_inverted = c > d + + # want to know whether to put label on positive or negative direction + # cannot use np.sign here because it will return 0 if x == 0 + def sign(x): + return 1 if x >= 0 else -1 + + _api.check_in_list(['edge', 'center'], label_type=label_type) + + bars = container.patches + errorbar = container.errorbar + datavalues = container.datavalues + orientation = container.orientation + + if errorbar: + # check "ErrorbarContainer" for the definition of these elements + lines = errorbar.lines # attribute of "ErrorbarContainer" (tuple) + barlinecols = lines[2] # 0: data_line, 1: caplines, 2: barlinecols + barlinecol = barlinecols[0] # the "LineCollection" of error bars + errs = barlinecol.get_segments() + else: + errs = [] + + if labels is None: + labels = [] + + annotations = [] + + for bar, err, dat, lbl in itertools.zip_longest( + bars, errs, datavalues, labels + ): + (x0, y0), (x1, y1) = bar.get_bbox().get_points() + xc, yc = (x0 + x1) / 2, (y0 + y1) / 2 + + if orientation == "vertical": + extrema = max(y0, y1) if dat >= 0 else min(y0, y1) + length = abs(y0 - y1) + else: # horizontal + extrema = max(x0, x1) if dat >= 0 else min(x0, x1) + length = abs(x0 - x1) + + if err is None or np.size(err) == 0: + endpt = extrema + elif orientation == "vertical": + endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min() + else: # horizontal + endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min() + + if label_type == "center": + value = sign(dat) * length + else: # edge + value = extrema + + if label_type == "center": + xy = (0.5, 0.5) + kwargs["xycoords"] = ( + lambda r, b=bar: + mtransforms.Bbox.intersection( + b.get_window_extent(r), b.get_clip_box() + ) or mtransforms.Bbox.null() + ) + else: # edge + if orientation == "vertical": + xy = xc, endpt + else: # horizontal + xy = endpt, yc + + if orientation == "vertical": + y_direction = -1 if y_inverted else 1 + xytext = 0, y_direction * sign(dat) * padding + else: # horizontal + x_direction = -1 if x_inverted else 1 + xytext = x_direction * sign(dat) * padding, 0 + + if label_type == "center": + ha, va = "center", "center" + else: # edge + if orientation == "vertical": + ha = 'center' + if y_inverted: + va = 'top' if dat > 0 else 'bottom' # also handles NaN + else: + va = 'top' if dat < 0 else 'bottom' # also handles NaN + else: # horizontal + if x_inverted: + ha = 'right' if dat > 0 else 'left' # also handles NaN + else: + ha = 'right' if dat < 0 else 'left' # also handles NaN + va = 'center' + + if np.isnan(dat): + lbl = '' + + if lbl is None: + if isinstance(fmt, str): + lbl = cbook._auto_format_str(fmt, value) + elif callable(fmt): + lbl = fmt(value) + else: + raise TypeError("fmt must be a str or callable") + annotation = self.annotate(lbl, + xy, xytext, textcoords="offset points", + ha=ha, va=va, **kwargs) + annotations.append(annotation) + + return annotations + + @_preprocess_data() + @_docstring.interpd + def broken_barh(self, xranges, yrange, **kwargs): + """ + Plot a horizontal sequence of rectangles. + + A rectangle is drawn for each element of *xranges*. All rectangles + have the same vertical position and size defined by *yrange*. + + Parameters + ---------- + xranges : sequence of tuples (*xmin*, *xwidth*) + The x-positions and extents of the rectangles. For each tuple + (*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* + + *xwidth*. + yrange : (*ymin*, *yheight*) + The y-position and extent for all the rectangles. + + Returns + ------- + `~.collections.PolyCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `.PolyCollection` properties + + Each *kwarg* can be either a single argument applying to all + rectangles, e.g.:: + + facecolors='black' + + or a sequence of arguments over which is cycled, e.g.:: + + facecolors=('black', 'blue') + + would create interleaving black and blue rectangles. + + Supported keywords: + + %(PolyCollection:kwdoc)s + """ + # process the unit information + xdata = cbook._safe_first_finite(xranges) if len(xranges) else None + ydata = cbook._safe_first_finite(yrange) if len(yrange) else None + self._process_unit_info( + [("x", xdata), ("y", ydata)], kwargs, convert=False) + + vertices = [] + y0, dy = yrange + y0, y1 = self.convert_yunits((y0, y0 + dy)) + for xr in xranges: # convert the absolute values, not the x and dx + try: + x0, dx = xr + except Exception: + raise ValueError( + "each range in xrange must be a sequence with two " + "elements (i.e. xrange must be an (N, 2) array)") from None + x0, x1 = self.convert_xunits((x0, x0 + dx)) + vertices.append([(x0, y0), (x0, y1), (x1, y1), (x1, y0)]) + + col = mcoll.PolyCollection(np.array(vertices), **kwargs) + self.add_collection(col, autolim=True) + self._request_autoscale_view() + + return col + + @_preprocess_data() + def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, + label=None, orientation='vertical'): + """ + Create a stem plot. + + A stem plot draws lines perpendicular to a baseline at each location + *locs* from the baseline to *heads*, and places a marker there. For + vertical stem plots (the default), the *locs* are *x* positions, and + the *heads* are *y* values. For horizontal stem plots, the *locs* are + *y* positions, and the *heads* are *x* values. + + Call signature:: + + stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None) + + The *locs*-positions are optional. *linefmt* may be provided as + positional, but all other formats must be provided as keyword + arguments. + + Parameters + ---------- + locs : array-like, default: (0, 1, ..., len(heads) - 1) + For vertical stem plots, the x-positions of the stems. + For horizontal stem plots, the y-positions of the stems. + + heads : array-like + For vertical stem plots, the y-values of the stem heads. + For horizontal stem plots, the x-values of the stem heads. + + linefmt : str, optional + A string defining the color and/or linestyle of the vertical lines: + + ========= ============= + Character Line Style + ========= ============= + ``'-'`` solid line + ``'--'`` dashed line + ``'-.'`` dash-dot line + ``':'`` dotted line + ========= ============= + + Default: 'C0-', i.e. solid line with the first color of the color + cycle. + + Note: Markers specified through this parameter (e.g. 'x') will be + silently ignored. Instead, markers should be specified using + *markerfmt*. + + markerfmt : str, optional + A string defining the color and/or shape of the markers at the stem + heads. If the marker is not given, use the marker 'o', i.e. filled + circles. If the color is not given, use the color from *linefmt*. + + basefmt : str, default: 'C3-' ('C2-' in classic mode) + A format string defining the properties of the baseline. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The orientation of the stems. + + bottom : float, default: 0 + The y/x-position of the baseline (depending on *orientation*). + + label : str, optional + The label to use for the stems in legends. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + `.StemContainer` + The container may be treated like a tuple + (*markerline*, *stemlines*, *baseline*) + + Notes + ----- + .. seealso:: + The MATLAB function + `stem `_ + which inspired this method. + """ + if not 1 <= len(args) <= 3: + raise _api.nargs_error('stem', '1-3', len(args)) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if len(args) == 1: + heads, = args + locs = np.arange(len(heads)) + args = () + elif isinstance(args[1], str): + heads, *args = args + locs = np.arange(len(heads)) + else: + locs, heads, *args = args + + if orientation == 'vertical': + locs, heads = self._process_unit_info([("x", locs), ("y", heads)]) + else: # horizontal + heads, locs = self._process_unit_info([("x", heads), ("y", locs)]) + + # resolve line format + if linefmt is None: + linefmt = args[0] if len(args) > 0 else "C0-" + linestyle, linemarker, linecolor = _process_plot_format(linefmt) + + # resolve marker format + if markerfmt is None: + # if not given as kwarg, fall back to 'o' + markerfmt = "o" + if markerfmt == '': + markerfmt = ' ' # = empty line style; '' would resolve rcParams + markerstyle, markermarker, markercolor = \ + _process_plot_format(markerfmt) + if markermarker is None: + markermarker = 'o' + if markerstyle is None: + markerstyle = 'None' + if markercolor is None: + markercolor = linecolor + + # resolve baseline format + if basefmt is None: + basefmt = ("C2-" if mpl.rcParams["_internal.classic_mode"] else + "C3-") + basestyle, basemarker, basecolor = _process_plot_format(basefmt) + + # New behaviour in 3.1 is to use a LineCollection for the stemlines + if linestyle is None: + linestyle = mpl.rcParams['lines.linestyle'] + xlines = self.vlines if orientation == "vertical" else self.hlines + stemlines = xlines( + locs, bottom, heads, + colors=linecolor, linestyles=linestyle, label="_nolegend_") + + if orientation == 'horizontal': + marker_x = heads + marker_y = locs + baseline_x = [bottom, bottom] + baseline_y = [np.min(locs), np.max(locs)] + else: + marker_x = locs + marker_y = heads + baseline_x = [np.min(locs), np.max(locs)] + baseline_y = [bottom, bottom] + + markerline, = self.plot(marker_x, marker_y, + color=markercolor, linestyle=markerstyle, + marker=markermarker, label="_nolegend_") + + baseline, = self.plot(baseline_x, baseline_y, + color=basecolor, linestyle=basestyle, + marker=basemarker, label="_nolegend_") + + stem_container = StemContainer((markerline, stemlines, baseline), + label=label) + self.add_container(stem_container) + return stem_container + + @_api.make_keyword_only("3.10", "explode") + @_preprocess_data(replace_names=["x", "explode", "labels", "colors"]) + def pie(self, x, explode=None, labels=None, colors=None, + autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, + startangle=0, radius=1, counterclock=True, + wedgeprops=None, textprops=None, center=(0, 0), + frame=False, rotatelabels=False, *, normalize=True, hatch=None): + """ + Plot a pie chart. + + Make a pie chart of array *x*. The fractional area of each wedge is + given by ``x/sum(x)``. + + The wedges are plotted counterclockwise, by default starting from the + x-axis. + + Parameters + ---------- + x : 1D array-like + The wedge sizes. + + explode : array-like, default: None + If not *None*, is a ``len(x)`` array which specifies the fraction + of the radius with which to offset each wedge. + + labels : list, default: None + A sequence of strings providing the labels for each wedge + + colors : :mpltype:`color` or list of :mpltype:`color`, default: None + A sequence of colors through which the pie chart will cycle. If + *None*, will use the colors in the currently active cycle. + + hatch : str or list, default: None + Hatching pattern applied to all pie wedges or sequence of patterns + through which the chart will cycle. For a list of valid patterns, + see :doc:`/gallery/shapes_and_collections/hatch_style_reference`. + + .. versionadded:: 3.7 + + autopct : None or str or callable, default: None + If not *None*, *autopct* is a string or function used to label the + wedges with their numeric value. The label will be placed inside + the wedge. If *autopct* is a format string, the label will be + ``fmt % pct``. If *autopct* is a function, then it will be called. + + pctdistance : float, default: 0.6 + The relative distance along the radius at which the text + generated by *autopct* is drawn. To draw the text outside the pie, + set *pctdistance* > 1. This parameter is ignored if *autopct* is + ``None``. + + labeldistance : float or None, default: 1.1 + The relative distance along the radius at which the labels are + drawn. To draw the labels inside the pie, set *labeldistance* < 1. + If set to ``None``, labels are not drawn but are still stored for + use in `.legend`. + + shadow : bool or dict, default: False + If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow + passing the properties in the dict to `.Shadow`. + + .. versionadded:: 3.8 + *shadow* can be a dict. + + startangle : float, default: 0 degrees + The angle by which the start of the pie is rotated, + counterclockwise from the x-axis. + + radius : float, default: 1 + The radius of the pie. + + counterclock : bool, default: True + Specify fractions direction, clockwise or counterclockwise. + + wedgeprops : dict, default: None + Dict of arguments passed to each `.patches.Wedge` of the pie. + For example, ``wedgeprops = {'linewidth': 3}`` sets the width of + the wedge border lines equal to 3. By default, ``clip_on=False``. + When there is a conflict between these properties and other + keywords, properties passed to *wedgeprops* take precedence. + + textprops : dict, default: None + Dict of arguments to pass to the text objects. + + center : (float, float), default: (0, 0) + The coordinates of the center of the chart. + + frame : bool, default: False + Plot Axes frame with the chart if true. + + rotatelabels : bool, default: False + Rotate each label to the angle of the corresponding slice if true. + + normalize : bool, default: True + When *True*, always make a full pie by normalizing x so that + ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1`` + and raises a `ValueError` for ``sum(x) > 1``. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + patches : list + A sequence of `matplotlib.patches.Wedge` instances + + texts : list + A list of the label `.Text` instances. + + autotexts : list + A list of `.Text` instances for the numeric labels. This will only + be returned if the parameter *autopct* is not *None*. + + Notes + ----- + The pie chart will probably look best if the figure and Axes are + square, or the Axes aspect is equal. + This method sets the aspect ratio of the axis to "equal". + The Axes aspect ratio can be controlled with `.Axes.set_aspect`. + """ + self.set_aspect('equal') + # The use of float32 is "historical", but can't be changed without + # regenerating the test baselines. + x = np.asarray(x, np.float32) + if x.ndim > 1: + raise ValueError("x must be 1D") + + if np.any(x < 0): + raise ValueError("Wedge sizes 'x' must be non negative values") + + sx = x.sum() + + if normalize: + x = x / sx + elif sx > 1: + raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1') + if labels is None: + labels = [''] * len(x) + if explode is None: + explode = [0] * len(x) + if len(x) != len(labels): + raise ValueError(f"'labels' must be of length 'x', not {len(labels)}") + if len(x) != len(explode): + raise ValueError(f"'explode' must be of length 'x', not {len(explode)}") + if colors is None: + get_next_color = self._get_patches_for_fill.get_next_color + else: + color_cycle = itertools.cycle(colors) + + def get_next_color(): + return next(color_cycle) + + hatch_cycle = itertools.cycle(np.atleast_1d(hatch)) + + _api.check_isinstance(Real, radius=radius, startangle=startangle) + if radius <= 0: + raise ValueError(f"'radius' must be a positive number, not {radius}") + + # Starting theta1 is the start fraction of the circle + theta1 = startangle / 360 + + if wedgeprops is None: + wedgeprops = {} + if textprops is None: + textprops = {} + + texts = [] + slices = [] + autotexts = [] + + for frac, label, expl in zip(x, labels, explode): + x, y = center + theta2 = (theta1 + frac) if counterclock else (theta1 - frac) + thetam = 2 * np.pi * 0.5 * (theta1 + theta2) + x += expl * math.cos(thetam) + y += expl * math.sin(thetam) + + w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2), + 360. * max(theta1, theta2), + facecolor=get_next_color(), + hatch=next(hatch_cycle), + clip_on=False, + label=label) + w.set(**wedgeprops) + slices.append(w) + self.add_patch(w) + + if shadow: + # Make sure to add a shadow after the call to add_patch so the + # figure and transform props will be set. + shadow_dict = {'ox': -0.02, 'oy': -0.02, 'label': '_nolegend_'} + if isinstance(shadow, dict): + shadow_dict.update(shadow) + self.add_patch(mpatches.Shadow(w, **shadow_dict)) + + if labeldistance is not None: + xt = x + labeldistance * radius * math.cos(thetam) + yt = y + labeldistance * radius * math.sin(thetam) + label_alignment_h = 'left' if xt > 0 else 'right' + label_alignment_v = 'center' + label_rotation = 'horizontal' + if rotatelabels: + label_alignment_v = 'bottom' if yt > 0 else 'top' + label_rotation = (np.rad2deg(thetam) + + (0 if xt > 0 else 180)) + t = self.text(xt, yt, label, + clip_on=False, + horizontalalignment=label_alignment_h, + verticalalignment=label_alignment_v, + rotation=label_rotation, + size=mpl.rcParams['xtick.labelsize']) + t.set(**textprops) + texts.append(t) + + if autopct is not None: + xt = x + pctdistance * radius * math.cos(thetam) + yt = y + pctdistance * radius * math.sin(thetam) + if isinstance(autopct, str): + s = autopct % (100. * frac) + elif callable(autopct): + s = autopct(100. * frac) + else: + raise TypeError( + 'autopct must be callable or a format string') + if mpl._val_or_rc(textprops.get("usetex"), "text.usetex"): + # escape % (i.e. \%) if it is not already escaped + s = re.sub(r"([^\\])%", r"\1\\%", s) + t = self.text(xt, yt, s, + clip_on=False, + horizontalalignment='center', + verticalalignment='center') + t.set(**textprops) + autotexts.append(t) + + theta1 = theta2 + + if frame: + self._request_autoscale_view() + else: + self.set(frame_on=False, xticks=[], yticks=[], + xlim=(-1.25 + center[0], 1.25 + center[0]), + ylim=(-1.25 + center[1], 1.25 + center[1])) + + if autopct is None: + return slices, texts + else: + return slices, texts, autotexts + + @staticmethod + def _errorevery_to_mask(x, errorevery): + """ + Normalize `errorbar`'s *errorevery* to be a boolean mask for data *x*. + + This function is split out to be usable both by 2D and 3D errorbars. + """ + if isinstance(errorevery, Integral): + errorevery = (0, errorevery) + if isinstance(errorevery, tuple): + if (len(errorevery) == 2 and + isinstance(errorevery[0], Integral) and + isinstance(errorevery[1], Integral)): + errorevery = slice(errorevery[0], None, errorevery[1]) + else: + raise ValueError( + f'{errorevery=!r} is a not a tuple of two integers') + elif isinstance(errorevery, slice): + pass + elif not isinstance(errorevery, str) and np.iterable(errorevery): + try: + x[errorevery] # fancy indexing + except (ValueError, IndexError) as err: + raise ValueError( + f"{errorevery=!r} is iterable but not a valid NumPy fancy " + "index to match 'xerr'/'yerr'") from err + else: + raise ValueError(f"{errorevery=!r} is not a recognized value") + everymask = np.zeros(len(x), bool) + everymask[errorevery] = True + return everymask + + @_api.make_keyword_only("3.10", "ecolor") + @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"], + label_namer="y") + @_docstring.interpd + def errorbar(self, x, y, yerr=None, xerr=None, + fmt='', ecolor=None, elinewidth=None, capsize=None, + barsabove=False, lolims=False, uplims=False, + xlolims=False, xuplims=False, errorevery=1, capthick=None, + **kwargs): + """ + Plot y versus x as lines and/or markers with attached errorbars. + + *x*, *y* define the data locations, *xerr*, *yerr* define the errorbar + sizes. By default, this draws the data markers/lines as well as the + errorbars. Use fmt='none' to draw errorbars without any data markers. + + .. versionadded:: 3.7 + Caps and error lines are drawn in polar coordinates on polar plots. + + + Parameters + ---------- + x, y : float or array-like + The data positions. + + xerr, yerr : float or array-like, shape(N,) or shape(2, N), optional + The errorbar sizes: + + - scalar: Symmetric +/- values for all data points. + - shape(N,): Symmetric +/-values for each data point. + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. + + All values must be >= 0. + + See :doc:`/gallery/statistics/errorbar_features` + for an example on the usage of ``xerr`` and ``yerr``. + + fmt : str, default: '' + The format for the data points / data lines. See `.plot` for + details. + + Use 'none' (case-insensitive) to plot errorbars without any data + markers. + + ecolor : :mpltype:`color`, default: None + The color of the errorbar lines. If None, use the color of the + line connecting the markers. + + elinewidth : float, default: None + The linewidth of the errorbar lines. If None, the linewidth of + the current style is used. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + capthick : float, default: None + An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*). + This setting is a more sensible name for the property that + controls the thickness of the error bar cap in points. For + backwards compatibility, if *mew* or *markeredgewidth* are given, + then they will over-ride *capthick*. This may change in future + releases. + + barsabove : bool, default: False + If True, will plot the errorbars above the plot + symbols. Default is below. + + lolims, uplims, xlolims, xuplims : bool or array-like, default: False + These arguments can be used to indicate that a value gives only + upper/lower limits. In that case a caret symbol is used to + indicate this. *lims*-arguments may be scalars, or array-likes of + the same length as *xerr* and *yerr*. To use limits with inverted + axes, `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before + :meth:`errorbar`. Note the tricky parameter names: setting e.g. + *lolims* to True means that the y-value is a *lower* limit of the + True value, so, only an *upward*-pointing arrow will be drawn! + + errorevery : int or (int, int), default: 1 + draws error bars on a subset of the data. *errorevery* =N draws + error bars on the points (x[::N], y[::N]). + *errorevery* =(start, N) draws error bars on the points + (x[start::N], y[start::N]). e.g. errorevery=(6, 3) + adds error bars to the data at (x[6], x[9], x[12], x[15], ...). + Used to avoid overlapping error bars when two series share x-axis + values. + + Returns + ------- + `.ErrorbarContainer` + The container contains: + + - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers + and/or line. + - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error + bar caps. + - barlinecols : A tuple of `.LineCollection` with the horizontal and + vertical error ranges. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to the `~.Axes.plot` call + drawing the markers. For example, this code makes big red squares + with thick green edges:: + + x, y, yerr = rand(3, 10) + errorbar(x, y, yerr, marker='s', mfc='red', + mec='green', ms=20, mew=4) + + where *mfc*, *mec*, *ms* and *mew* are aliases for the longer + property names, *markerfacecolor*, *markeredgecolor*, *markersize* + and *markeredgewidth*. + + Valid kwargs for the marker properties are: + + - *dashes* + - *dash_capstyle* + - *dash_joinstyle* + - *drawstyle* + - *fillstyle* + - *linestyle* + - *marker* + - *markeredgecolor* + - *markeredgewidth* + - *markerfacecolor* + - *markerfacecoloralt* + - *markersize* + - *markevery* + - *solid_capstyle* + - *solid_joinstyle* + + Refer to the corresponding `.Line2D` property for more details: + + %(Line2D:kwdoc)s + """ + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # Drop anything that comes in as None to use the default instead. + kwargs = {k: v for k, v in kwargs.items() if v is not None} + kwargs.setdefault('zorder', 2) + + # Casting to object arrays preserves units. + if not isinstance(x, np.ndarray): + x = np.asarray(x, dtype=object) + if not isinstance(y, np.ndarray): + y = np.asarray(y, dtype=object) + + def _upcast_err(err): + """ + Safely handle tuple of containers that carry units. + + This function covers the case where the input to the xerr/yerr is a + length 2 tuple of equal length ndarray-subclasses that carry the + unit information in the container. + + If we have a tuple of nested numpy array (subclasses), we defer + coercing the units to be consistent to the underlying unit + library (and implicitly the broadcasting). + + Otherwise, fallback to casting to an object array. + """ + + if ( + # make sure it is not a scalar + np.iterable(err) and + # and it is not empty + len(err) > 0 and + # and the first element is an array sub-class use + # safe_first_element because getitem is index-first not + # location first on pandas objects so err[0] almost always + # fails. + isinstance(cbook._safe_first_finite(err), np.ndarray) + ): + # Get the type of the first element + atype = type(cbook._safe_first_finite(err)) + # Promote the outer container to match the inner container + if atype is np.ndarray: + # Converts using np.asarray, because data cannot + # be directly passed to init of np.ndarray + return np.asarray(err, dtype=object) + # If atype is not np.ndarray, directly pass data to init. + # This works for types such as unyts and astropy units + return atype(err) + # Otherwise wrap it in an object array + return np.asarray(err, dtype=object) + + if xerr is not None and not isinstance(xerr, np.ndarray): + xerr = _upcast_err(xerr) + if yerr is not None and not isinstance(yerr, np.ndarray): + yerr = _upcast_err(yerr) + x, y = np.atleast_1d(x, y) # Make sure all the args are iterable. + if len(x) != len(y): + raise ValueError("'x' and 'y' must have the same size") + + everymask = self._errorevery_to_mask(x, errorevery) + + label = kwargs.pop("label", None) + kwargs['label'] = '_nolegend_' + + # Create the main line and determine overall kwargs for child artists. + # We avoid calling self.plot() directly, or self._get_lines(), because + # that would call self._process_unit_info again, and do other indirect + # data processing. + (data_line, base_style), = self._get_lines._plot_args( + self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) + + # Do this after creating `data_line` to avoid modifying `base_style`. + if barsabove: + data_line.set_zorder(kwargs['zorder'] - .1) + else: + data_line.set_zorder(kwargs['zorder'] + .1) + + # Add line to plot, or throw it away and use it to determine kwargs. + if fmt.lower() != 'none': + self.add_line(data_line) + else: + data_line = None + # Remove alpha=0 color that _get_lines._plot_args returns for + # 'none' format, and replace it with user-specified color, if + # supplied. + base_style.pop('color') + if 'color' in kwargs: + base_style['color'] = kwargs.pop('color') + + if 'color' not in base_style: + base_style['color'] = 'C0' + if ecolor is None: + ecolor = base_style['color'] + + # Eject any line-specific information from format string, as it's not + # needed for bars or caps. + for key in ['marker', 'markersize', 'markerfacecolor', + 'markerfacecoloralt', + 'markeredgewidth', 'markeredgecolor', 'markevery', + 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', + 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle', + 'dashes']: + base_style.pop(key, None) + + # Make the style dict for the line collections (the bars). + eb_lines_style = {**base_style, 'color': ecolor} + + if elinewidth is not None: + eb_lines_style['linewidth'] = elinewidth + elif 'linewidth' in kwargs: + eb_lines_style['linewidth'] = kwargs['linewidth'] + + for key in ('transform', 'alpha', 'zorder', 'rasterized'): + if key in kwargs: + eb_lines_style[key] = kwargs[key] + + # Make the style dict for caps (the "hats"). + eb_cap_style = {**base_style, 'linestyle': 'none'} + if capsize is None: + capsize = mpl.rcParams["errorbar.capsize"] + if capsize > 0: + eb_cap_style['markersize'] = 2. * capsize + if capthick is not None: + eb_cap_style['markeredgewidth'] = capthick + + # For backwards-compat, allow explicit setting of + # 'markeredgewidth' to over-ride capthick. + for key in ('markeredgewidth', 'transform', 'alpha', + 'zorder', 'rasterized'): + if key in kwargs: + eb_cap_style[key] = kwargs[key] + eb_cap_style['color'] = ecolor + + barcols = [] + caplines = {'x': [], 'y': []} + + # Vectorized fancy-indexer. + def apply_mask(arrays, mask): + return [array[mask] for array in arrays] + + # dep: dependent dataset, indep: independent dataset + for (dep_axis, dep, err, lolims, uplims, indep, lines_func, + marker, lomarker, himarker) in [ + ("x", x, xerr, xlolims, xuplims, y, self.hlines, + "|", mlines.CARETRIGHTBASE, mlines.CARETLEFTBASE), + ("y", y, yerr, lolims, uplims, x, self.vlines, + "_", mlines.CARETUPBASE, mlines.CARETDOWNBASE), + ]: + if err is None: + continue + lolims = np.broadcast_to(lolims, len(dep)).astype(bool) + uplims = np.broadcast_to(uplims, len(dep)).astype(bool) + try: + np.broadcast_to(err, (2, len(dep))) + except ValueError: + raise ValueError( + f"'{dep_axis}err' (shape: {np.shape(err)}) must be a " + f"scalar or a 1D or (2, n) array-like whose shape matches " + f"'{dep_axis}' (shape: {np.shape(dep)})") from None + if err.dtype is np.dtype(object) and np.any(err == None): # noqa: E711 + raise ValueError( + f"'{dep_axis}err' must not contain None. " + "Use NaN if you want to skip a value.") + + # Raise if any errors are negative, but not if they are nan. + # To avoid nan comparisons (which lead to warnings on some + # platforms), we select with `err==err` (which is False for nan). + # Also, since datetime.timedelta cannot be compared with 0, + # we compare with the negative error instead. + if np.any((check := err[err == err]) < -check): + raise ValueError( + f"'{dep_axis}err' must not contain negative values") + # This is like + # elow, ehigh = np.broadcast_to(...) + # return dep - elow * ~lolims, dep + ehigh * ~uplims + # except that broadcast_to would strip units. + low, high = dep + np.vstack([-(1 - lolims), 1 - uplims]) * err + barcols.append(lines_func( + *apply_mask([indep, low, high], everymask), **eb_lines_style)) + if self.name == "polar" and dep_axis == "x": + for b in barcols: + for p in b.get_paths(): + p._interpolation_steps = 2 + # Normal errorbars for points without upper/lower limits. + nolims = ~(lolims | uplims) + if nolims.any() and capsize > 0: + indep_masked, lo_masked, hi_masked = apply_mask( + [indep, low, high], nolims & everymask) + for lh_masked in [lo_masked, hi_masked]: + # Since this has to work for x and y as dependent data, we + # first set both x and y to the independent variable and + # overwrite the respective dependent data in a second step. + line = mlines.Line2D(indep_masked, indep_masked, + marker=marker, **eb_cap_style) + line.set(**{f"{dep_axis}data": lh_masked}) + caplines[dep_axis].append(line) + for idx, (lims, hl) in enumerate([(lolims, high), (uplims, low)]): + if not lims.any(): + continue + hlmarker = ( + himarker + if self._axis_map[dep_axis].get_inverted() ^ idx + else lomarker) + x_masked, y_masked, hl_masked = apply_mask( + [x, y, hl], lims & everymask) + # As above, we set the dependent data in a second step. + line = mlines.Line2D(x_masked, y_masked, + marker=hlmarker, **eb_cap_style) + line.set(**{f"{dep_axis}data": hl_masked}) + caplines[dep_axis].append(line) + if capsize > 0: + caplines[dep_axis].append(mlines.Line2D( + x_masked, y_masked, marker=marker, **eb_cap_style)) + if self.name == 'polar': + trans_shift = self.transShift + for axis in caplines: + for l in caplines[axis]: + # Rotate caps to be perpendicular to the error bars + for theta, r in zip(l.get_xdata(), l.get_ydata()): + rotation = _ScaledRotation(theta=theta, trans_shift=trans_shift) + if axis == 'y': + rotation += mtransforms.Affine2D().rotate(np.pi / 2) + ms = mmarkers.MarkerStyle(marker=marker, + transform=rotation) + self.add_line(mlines.Line2D([theta], [r], marker=ms, + **eb_cap_style)) + else: + for axis in caplines: + for l in caplines[axis]: + self.add_line(l) + + self._request_autoscale_view() + caplines = caplines['x'] + caplines['y'] + errorbar_container = ErrorbarContainer( + (data_line, tuple(caplines), tuple(barcols)), + has_xerr=(xerr is not None), has_yerr=(yerr is not None), + label=label) + self.add_container(errorbar_container) + + return errorbar_container # (l0, caplines, barcols) + + @_api.make_keyword_only("3.10", "notch") + @_preprocess_data() + @_api.rename_parameter("3.9", "labels", "tick_labels") + def boxplot(self, x, notch=None, sym=None, vert=None, + orientation='vertical', whis=None, positions=None, + widths=None, patch_artist=None, bootstrap=None, + usermedians=None, conf_intervals=None, + meanline=None, showmeans=None, showcaps=None, + showbox=None, showfliers=None, boxprops=None, + tick_labels=None, flierprops=None, medianprops=None, + meanprops=None, capprops=None, whiskerprops=None, + manage_ticks=True, autorange=False, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot. + + The box extends from the first quartile (Q1) to the third + quartile (Q3) of the data, with a line at the median. + The whiskers extend from the box to the farthest data point + lying within 1.5x the inter-quartile range (IQR) from the box. + Flier points are those past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + Q1-1.5IQR Q1 median Q3 Q3+1.5IQR + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier <-----------> fliers + IQR + + + Parameters + ---------- + x : Array or a sequence of vectors. + The input data. If a 2D array, a boxplot is drawn for each column + in *x*. If a sequence of 1D arrays, a boxplot is drawn for each + array in *x*. + + notch : bool, default: :rc:`boxplot.notch` + Whether to draw a notched boxplot (`True`), or a rectangular + boxplot (`False`). The notches represent the confidence interval + (CI) around the median. The documentation for *bootstrap* + describes how the locations of the notches are computed by + default, but their locations may also be overridden by setting the + *conf_intervals* parameter. + + .. note:: + + In cases where the values of the CI are less than the + lower quartile or greater than the upper quartile, the + notches will extend beyond the box, giving it a + distinctive "flipped" appearance. This is expected + behavior and consistent with other statistical + visualization packages. + + sym : str, optional + The default symbol for flier points. An empty string ('') hides + the fliers. If `None`, then the fliers default to 'b+'. More + control is provided by the *flierprops* parameter. + + vert : bool, optional + .. deprecated:: 3.11 + Use *orientation* instead. + + This is a pending deprecation for 3.10, with full deprecation + in 3.11 and removal in 3.13. + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the boxes vertically. + If False, plots the boxes horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the boxes horizontally. + Otherwise, plots the boxes vertically. + + .. versionadded:: 3.10 + + whis : float or (float, float), default: 1.5 + The position of the whiskers. + + If a float, the lower whisker is at the lowest datum above + ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum + below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and + third quartiles. The default value of ``whis = 1.5`` corresponds + to Tukey's original definition of boxplots. + + If a pair of floats, they indicate the percentiles at which to + draw the whiskers (e.g., (5, 95)). In particular, setting this to + (0, 100) results in whiskers covering the whole range of the data. + + In the edge case where ``Q1 == Q3``, *whis* is automatically set + to (0, 100) (cover the whole range of the data) if *autorange* is + True. + + Beyond the whiskers, data are considered outliers and are plotted + as individual points. + + bootstrap : int, optional + Specifies whether to bootstrap the confidence intervals + around the median for notched boxplots. If *bootstrap* is + None, no bootstrapping is performed, and notches are + calculated using a Gaussian-based asymptotic approximation + (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and + Kendall and Stuart, 1967). Otherwise, bootstrap specifies + the number of times to bootstrap the median to determine its + 95% confidence intervals. Values between 1000 and 10000 are + recommended. + + usermedians : 1D array-like, optional + A 1D array-like of length ``len(x)``. Each entry that is not + `None` forces the value of the median for the corresponding + dataset. For entries that are `None`, the medians are computed + by Matplotlib as normal. + + conf_intervals : array-like, optional + A 2D array-like of shape ``(len(x), 2)``. Each entry that is not + None forces the location of the corresponding notch (which is + only drawn if *notch* is `True`). For entries that are `None`, + the notches are computed by the method specified by the other + parameters (e.g., *bootstrap*). + + positions : array-like, optional + The positions of the boxes. The ticks and limits are + automatically set to match the positions. Defaults to + ``range(1, N+1)`` where N is the number of boxes to be drawn. + + widths : float or array-like + The widths of the boxes. The default is 0.5, or ``0.15*(distance + between extreme positions)``, if that is smaller. + + patch_artist : bool, default: :rc:`boxplot.patchartist` + If `False` produces boxes with the Line2D artist. Otherwise, + boxes are drawn with Patch artists. + + tick_labels : list of str, optional + The tick labels of each boxplot. + Ticks are always placed at the box *positions*. If *tick_labels* is given, + the ticks are labelled accordingly. Otherwise, they keep their numeric + values. + + .. versionchanged:: 3.9 + Renamed from *labels*, which is deprecated since 3.9 + and will be removed in 3.11. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match + the boxplot positions. + + autorange : bool, default: False + When `True` and the data are distributed such that the 25th and + 75th percentiles are equal, *whis* is set to (0, 100) such + that the whisker ends are at the minimum and maximum of the data. + + meanline : bool, default: :rc:`boxplot.meanline` + If `True` (and *showmeans* is `True`), will try to render the + mean as a line spanning the full width of the box according to + *meanprops* (see below). Not recommended if *shownotches* is also + True. Otherwise, means will be shown as points. + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: the main body of the boxplot showing the + quartiles and the median's confidence intervals if + enabled. + + - ``medians``: horizontal lines at the median of each box. + + - ``whiskers``: the vertical lines extending to the most + extreme, non-outlier data points. + + - ``caps``: the horizontal lines at the ends of the + whiskers. + + - ``fliers``: points representing data that extend beyond + the whiskers (fliers). + + - ``means``: points or lines representing the means. + + Other Parameters + ---------------- + showcaps : bool, default: :rc:`boxplot.showcaps` + Show the caps on the ends of whiskers. + showbox : bool, default: :rc:`boxplot.showbox` + Show the central box. + showfliers : bool, default: :rc:`boxplot.showfliers` + Show the outliers beyond the caps. + showmeans : bool, default: :rc:`boxplot.showmeans` + Show the arithmetic means. + capprops : dict, default: None + The style of the caps. + capwidths : float or array, default: None + The widths of the caps. + boxprops : dict, default: None + The style of the box. + whiskerprops : dict, default: None + The style of the whiskers. + flierprops : dict, default: None + The style of the fliers. + medianprops : dict, default: None + The style of the median. + meanprops : dict, default: None + The style of the mean. + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + See Also + -------- + .Axes.bxp : Draw a boxplot from pre-computed statistics. + violinplot : Draw an estimate of the probability density function. + """ + + # Missing arguments default to rcParams. + if whis is None: + whis = mpl.rcParams['boxplot.whiskers'] + if bootstrap is None: + bootstrap = mpl.rcParams['boxplot.bootstrap'] + + bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, + labels=tick_labels, autorange=autorange) + if notch is None: + notch = mpl.rcParams['boxplot.notch'] + if patch_artist is None: + patch_artist = mpl.rcParams['boxplot.patchartist'] + if meanline is None: + meanline = mpl.rcParams['boxplot.meanline'] + if showmeans is None: + showmeans = mpl.rcParams['boxplot.showmeans'] + if showcaps is None: + showcaps = mpl.rcParams['boxplot.showcaps'] + if showbox is None: + showbox = mpl.rcParams['boxplot.showbox'] + if showfliers is None: + showfliers = mpl.rcParams['boxplot.showfliers'] + + if boxprops is None: + boxprops = {} + if whiskerprops is None: + whiskerprops = {} + if capprops is None: + capprops = {} + if medianprops is None: + medianprops = {} + if meanprops is None: + meanprops = {} + if flierprops is None: + flierprops = {} + + if patch_artist: + boxprops['linestyle'] = 'solid' # Not consistent with bxp. + if 'color' in boxprops: + boxprops['edgecolor'] = boxprops.pop('color') + + # if non-default sym value, put it into the flier dictionary + # the logic for providing the default symbol ('b+') now lives + # in bxp in the initial value of flierkw + # handle all of the *sym* related logic here so we only have to pass + # on the flierprops dict. + if sym is not None: + # no-flier case, which should really be done with + # 'showfliers=False' but none-the-less deal with it to keep back + # compatibility + if sym == '': + # blow away existing dict and make one for invisible markers + flierprops = dict(linestyle='none', marker='', color='none') + # turn the fliers off just to be safe + showfliers = False + # now process the symbol string + else: + # process the symbol string + # discarded linestyle + _, marker, color = _process_plot_format(sym) + # if we have a marker, use it + if marker is not None: + flierprops['marker'] = marker + # if we have a color, use it + if color is not None: + # assume that if color is passed in the user want + # filled symbol, if the users want more control use + # flierprops + flierprops['color'] = color + flierprops['markerfacecolor'] = color + flierprops['markeredgecolor'] = color + + # replace medians if necessary: + if usermedians is not None: + if (len(np.ravel(usermedians)) != len(bxpstats) or + np.shape(usermedians)[0] != len(bxpstats)): + raise ValueError( + "'usermedians' and 'x' have different lengths") + else: + # reassign medians as necessary + for stats, med in zip(bxpstats, usermedians): + if med is not None: + stats['med'] = med + + if conf_intervals is not None: + if len(conf_intervals) != len(bxpstats): + raise ValueError( + "'conf_intervals' and 'x' have different lengths") + else: + for stats, ci in zip(bxpstats, conf_intervals): + if ci is not None: + if len(ci) != 2: + raise ValueError('each confidence interval must ' + 'have two values') + else: + if ci[0] is not None: + stats['cilo'] = ci[0] + if ci[1] is not None: + stats['cihi'] = ci[1] + + artists = self.bxp(bxpstats, positions=positions, widths=widths, + vert=vert, patch_artist=patch_artist, + shownotches=notch, showmeans=showmeans, + showcaps=showcaps, showbox=showbox, + boxprops=boxprops, flierprops=flierprops, + medianprops=medianprops, meanprops=meanprops, + meanline=meanline, showfliers=showfliers, + capprops=capprops, whiskerprops=whiskerprops, + manage_ticks=manage_ticks, zorder=zorder, + capwidths=capwidths, label=label, + orientation=orientation) + return artists + + @_api.make_keyword_only("3.10", "widths") + def bxp(self, bxpstats, positions=None, widths=None, vert=None, + orientation='vertical', patch_artist=False, shownotches=False, + showmeans=False, showcaps=True, showbox=True, showfliers=True, + boxprops=None, whiskerprops=None, flierprops=None, + medianprops=None, capprops=None, meanprops=None, + meanline=False, manage_ticks=True, zorder=None, + capwidths=None, label=None): + """ + Draw a box and whisker plot from pre-computed statistics. + + The box extends from the first quartile *q1* to the third + quartile *q3* of the data, with a line at the median (*med*). + The whiskers extend from *whislow* to *whishi*. + Flier points are markers past the end of the whiskers. + See https://en.wikipedia.org/wiki/Box_plot for reference. + + .. code-block:: none + + whislow q1 med q3 whishi + |-----:-----| + o |--------| : |--------| o o + |-----:-----| + flier fliers + + .. note:: + This is a low-level drawing function for when you already + have the statistical parameters. If you want a boxplot based + on a dataset, use `~.Axes.boxplot` instead. + + Parameters + ---------- + bxpstats : list of dicts + A list of dictionaries containing stats for each boxplot. + Required keys are: + + - ``med``: Median (float). + - ``q1``, ``q3``: First & third quartiles (float). + - ``whislo``, ``whishi``: Lower & upper whisker positions (float). + + Optional keys are: + + - ``mean``: Mean (float). Needed if ``showmeans=True``. + - ``fliers``: Data beyond the whiskers (array-like). + Needed if ``showfliers=True``. + - ``cilo``, ``cihi``: Lower & upper confidence intervals + about the median. Needed if ``shownotches=True``. + - ``label``: Name of the dataset (str). If available, + this will be used a tick label for the boxplot + + positions : array-like, default: [1, 2, ..., n] + The positions of the boxes. The ticks and limits + are automatically set to match the positions. + + widths : float or array-like, default: None + The widths of the boxes. The default is + ``clip(0.15*(distance between extreme positions), 0.15, 0.5)``. + + capwidths : float or array-like, default: None + Either a scalar or a vector and sets the width of each cap. + The default is ``0.5*(width of the box)``, see *widths*. + + vert : bool, optional + .. deprecated:: 3.11 + Use *orientation* instead. + + This is a pending deprecation for 3.10, with full deprecation + in 3.11 and removal in 3.13. + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the boxes vertically. + If False, plots the boxes horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the boxes horizontally. + Otherwise, plots the boxes vertically. + + .. versionadded:: 3.10 + + patch_artist : bool, default: False + If `False` produces boxes with the `.Line2D` artist. + If `True` produces boxes with the `~matplotlib.patches.Patch` artist. + + shownotches, showmeans, showcaps, showbox, showfliers : bool + Whether to draw the CI notches, the mean value (both default to + False), the caps, the box, and the fliers (all three default to + True). + + boxprops, whiskerprops, capprops, flierprops, medianprops, meanprops :\ + dict, optional + Artist properties for the boxes, whiskers, caps, fliers, medians, and + means. + + meanline : bool, default: False + If `True` (and *showmeans* is `True`), will try to render the mean + as a line spanning the full width of the box according to + *meanprops*. Not recommended if *shownotches* is also True. + Otherwise, means will be shown as points. + + manage_ticks : bool, default: True + If True, the tick locations and labels will be adjusted to match the + boxplot positions. + + label : str or list of str, optional + Legend labels. Use a single string when all boxes have the same style and + you only want a single legend entry for them. Use a list of strings to + label all boxes individually. To be distinguishable, the boxes should be + styled individually, which is currently only possible by modifying the + returned artists, see e.g. :doc:`/gallery/statistics/boxplot_demo`. + + In the case of a single string, the legend entry will technically be + associated with the first box only. By default, the legend will show the + median line (``result["medians"]``); if *patch_artist* is True, the legend + will show the box `.Patch` artists (``result["boxes"]``) instead. + + .. versionadded:: 3.9 + + zorder : float, default: ``Line2D.zorder = 2`` + The zorder of the resulting boxplot. + + Returns + ------- + dict + A dictionary mapping each component of the boxplot to a list + of the `.Line2D` instances created. That dictionary has the + following keys (assuming vertical boxplots): + + - ``boxes``: main bodies of the boxplot showing the quartiles, and + the median's confidence intervals if enabled. + - ``medians``: horizontal lines at the median of each box. + - ``whiskers``: vertical lines up to the last non-outlier data. + - ``caps``: horizontal lines at the ends of the whiskers. + - ``fliers``: points representing data beyond the whiskers (fliers). + - ``means``: points or lines representing the means. + + See Also + -------- + boxplot : Draw a boxplot from data instead of pre-computed statistics. + """ + # Clamp median line to edge of box by default. + medianprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(medianprops or {}), + } + meanprops = { + "solid_capstyle": "butt", + "dash_capstyle": "butt", + **(meanprops or {}), + } + + # lists of artists to be output + whiskers = [] + caps = [] + boxes = [] + medians = [] + means = [] + fliers = [] + + # empty list of xticklabels + datalabels = [] + + # Use default zorder if none specified + if zorder is None: + zorder = mlines.Line2D.zorder + + zdelta = 0.1 + + def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): + d = {k.split('.')[-1]: v for k, v in mpl.rcParams.items() + if k.startswith(f'boxplot.{subkey}props')} + d['zorder'] = zorder + zdelta + if not usemarker: + d['marker'] = '' + d.update(cbook.normalize_kwargs(explicit, mlines.Line2D)) + return d + + box_kw = { + 'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'], + 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'], + 'edgecolor': mpl.rcParams['boxplot.boxprops.color'], + 'facecolor': ('white' if mpl.rcParams['_internal.classic_mode'] + else mpl.rcParams['patch.facecolor']), + 'zorder': zorder, + **cbook.normalize_kwargs(boxprops, mpatches.PathPatch) + } if patch_artist else merge_kw_rc('box', boxprops, usemarker=False) + whisker_kw = merge_kw_rc('whisker', whiskerprops, usemarker=False) + cap_kw = merge_kw_rc('cap', capprops, usemarker=False) + flier_kw = merge_kw_rc('flier', flierprops) + median_kw = merge_kw_rc('median', medianprops, zdelta, usemarker=False) + mean_kw = merge_kw_rc('mean', meanprops, zdelta) + removed_prop = 'marker' if meanline else 'linestyle' + # Only remove the property if it's not set explicitly as a parameter. + if meanprops is None or removed_prop not in meanprops: + mean_kw[removed_prop] = '' + + # vert and orientation parameters are linked until vert's + # deprecation period expires. vert only takes precedence + # if set to False. + if vert is None: + vert = mpl.rcParams['boxplot.vertical'] + else: + _api.warn_deprecated( + "3.11", + name="vert: bool", + alternative="orientation: {'vertical', 'horizontal'}", + pending=True, + ) + if vert is False: + orientation = 'horizontal' + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if not mpl.rcParams['boxplot.vertical']: + _api.warn_deprecated( + "3.10", + name='boxplot.vertical', obj_type="rcparam" + ) + + # vertical or horizontal plot? + maybe_swap = slice(None) if orientation == 'vertical' else slice(None, None, -1) + + def do_plot(xs, ys, **kwargs): + return self.plot(*[xs, ys][maybe_swap], **kwargs)[0] + + def do_patch(xs, ys, **kwargs): + path = mpath.Path._create_closed( + np.column_stack([xs, ys][maybe_swap])) + patch = mpatches.PathPatch(path, **kwargs) + self.add_artist(patch) + return patch + + # input validation + N = len(bxpstats) + datashape_message = ("List of boxplot statistics and `{0}` " + "values must have same the length") + # check position + if positions is None: + positions = list(range(1, N + 1)) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + positions = np.array(positions) + if len(positions) > 0 and not all(isinstance(p, Real) for p in positions): + raise TypeError("positions should be an iterable of numbers") + + # width + if widths is None: + widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N + elif np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # capwidth + if capwidths is None: + capwidths = 0.5 * np.array(widths) + elif np.isscalar(capwidths): + capwidths = [capwidths] * N + elif len(capwidths) != N: + raise ValueError(datashape_message.format("capwidths")) + + for pos, width, stats, capwidth in zip(positions, widths, bxpstats, + capwidths): + # try to find a new label + datalabels.append(stats.get('label', pos)) + + # whisker coords + whis_x = [pos, pos] + whislo_y = [stats['q1'], stats['whislo']] + whishi_y = [stats['q3'], stats['whishi']] + # cap coords + cap_left = pos - capwidth * 0.5 + cap_right = pos + capwidth * 0.5 + cap_x = [cap_left, cap_right] + cap_lo = np.full(2, stats['whislo']) + cap_hi = np.full(2, stats['whishi']) + # box and median coords + box_left = pos - width * 0.5 + box_right = pos + width * 0.5 + med_y = [stats['med'], stats['med']] + # notched boxes + if shownotches: + notch_left = pos - width * 0.25 + notch_right = pos + width * 0.25 + box_x = [box_left, box_right, box_right, notch_right, + box_right, box_right, box_left, box_left, notch_left, + box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['cilo'], + stats['med'], stats['cihi'], stats['q3'], + stats['q3'], stats['cihi'], stats['med'], + stats['cilo'], stats['q1']] + med_x = [notch_left, notch_right] + # plain boxes + else: + box_x = [box_left, box_right, box_right, box_left, box_left] + box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'], + stats['q1']] + med_x = [box_left, box_right] + + # maybe draw the box + if showbox: + do_box = do_patch if patch_artist else do_plot + boxes.append(do_box(box_x, box_y, **box_kw)) + median_kw.setdefault('label', '_nolegend_') + # draw the whiskers + whisker_kw.setdefault('label', '_nolegend_') + whiskers.append(do_plot(whis_x, whislo_y, **whisker_kw)) + whiskers.append(do_plot(whis_x, whishi_y, **whisker_kw)) + # maybe draw the caps + if showcaps: + cap_kw.setdefault('label', '_nolegend_') + caps.append(do_plot(cap_x, cap_lo, **cap_kw)) + caps.append(do_plot(cap_x, cap_hi, **cap_kw)) + # draw the medians + medians.append(do_plot(med_x, med_y, **median_kw)) + # maybe draw the means + if showmeans: + if meanline: + means.append(do_plot( + [box_left, box_right], [stats['mean'], stats['mean']], + **mean_kw + )) + else: + means.append(do_plot([pos], [stats['mean']], **mean_kw)) + # maybe draw the fliers + if showfliers: + flier_kw.setdefault('label', '_nolegend_') + flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64) + flier_y = stats['fliers'] + fliers.append(do_plot(flier_x, flier_y, **flier_kw)) + + # Set legend labels + if label: + box_or_med = boxes if showbox and patch_artist else medians + if cbook.is_scalar_or_string(label): + # assign the label only to the first box + box_or_med[0].set_label(label) + else: # label is a sequence + if len(box_or_med) != len(label): + raise ValueError(datashape_message.format("label")) + for artist, lbl in zip(box_or_med, label): + artist.set_label(lbl) + + if manage_ticks: + axis_name = "x" if orientation == 'vertical' else "y" + interval = getattr(self.dataLim, f"interval{axis_name}") + axis = self._axis_map[axis_name] + positions = axis.convert_units(positions) + # The 0.5 additional padding ensures reasonable-looking boxes + # even when drawing a single box. We set the sticky edge to + # prevent margins expansion, in order to match old behavior (back + # when separate calls to boxplot() would completely reset the axis + # limits regardless of what was drawn before). The sticky edges + # are attached to the median lines, as they are always present. + interval[:] = (min(interval[0], min(positions) - .5), + max(interval[1], max(positions) + .5)) + for median, position in zip(medians, positions): + getattr(median.sticky_edges, axis_name).extend( + [position - .5, position + .5]) + # Modified from Axis.set_ticks and Axis.set_ticklabels. + locator = axis.get_major_locator() + if not isinstance(axis.get_major_locator(), + mticker.FixedLocator): + locator = mticker.FixedLocator([]) + axis.set_major_locator(locator) + locator.locs = np.array([*locator.locs, *positions]) + formatter = axis.get_major_formatter() + if not isinstance(axis.get_major_formatter(), + mticker.FixedFormatter): + formatter = mticker.FixedFormatter([]) + axis.set_major_formatter(formatter) + formatter.seq = [*formatter.seq, *datalabels] + + self._request_autoscale_view() + + return dict(whiskers=whiskers, caps=caps, boxes=boxes, + medians=medians, fliers=fliers, means=means) + + @staticmethod + def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, + get_next_color_func): + """ + Helper function to process color related arguments of `.Axes.scatter`. + + Argument precedence for facecolors: + + - c (if not None) + - kwargs['facecolor'] + - kwargs['facecolors'] + - kwargs['color'] (==kwcolor) + - 'b' if in classic mode else the result of ``get_next_color_func()`` + + Argument precedence for edgecolors: + + - kwargs['edgecolor'] + - edgecolors (is an explicit kw argument in scatter()) + - kwargs['color'] (==kwcolor) + - 'face' if not in classic mode else None + + Parameters + ---------- + c : :mpltype:`color` or array-like or list of :mpltype:`color` or None + See argument description of `.Axes.scatter`. + edgecolors : :mpltype:`color` or sequence of color or {'face', 'none'} or None + See argument description of `.Axes.scatter`. + kwargs : dict + Additional kwargs. If these keys exist, we pop and process them: + 'facecolors', 'facecolor', 'edgecolor', 'color' + Note: The dict is modified by this function. + xsize : int + The size of the x and y arrays passed to `.Axes.scatter`. + get_next_color_func : callable + A callable that returns a color. This color is used as facecolor + if no other color is provided. + + Note, that this is a function rather than a fixed color value to + support conditional evaluation of the next color. As of the + current implementation obtaining the next color from the + property cycle advances the cycle. This must only happen if we + actually use the color, which will only be decided within this + method. + + Returns + ------- + c + The input *c* if it was not *None*, else a color derived from the + other inputs or defaults. + colors : array(N, 4) or None + The facecolors as RGBA values, or *None* if a colormap is used. + edgecolors + The edgecolor. + + """ + facecolors = kwargs.pop('facecolors', None) + facecolors = kwargs.pop('facecolor', facecolors) + edgecolors = kwargs.pop('edgecolor', edgecolors) + + kwcolor = kwargs.pop('color', None) + + if kwcolor is not None and c is not None: + raise ValueError("Supply a 'c' argument or a 'color'" + " kwarg but not both; they differ but" + " their functionalities overlap.") + + if kwcolor is not None: + try: + mcolors.to_rgba_array(kwcolor) + except ValueError as err: + raise ValueError( + "'color' kwarg must be a color or sequence of color " + "specs. For a sequence of values to be color-mapped, use " + "the 'c' argument instead.") from err + if edgecolors is None: + edgecolors = kwcolor + if facecolors is None: + facecolors = kwcolor + + if edgecolors is None and not mpl.rcParams['_internal.classic_mode']: + edgecolors = mpl.rcParams['scatter.edgecolors'] + + # Raise a warning if both `c` and `facecolor` are set (issue #24404). + if c is not None and facecolors is not None: + _api.warn_external( + "You passed both c and facecolor/facecolors for the markers. " + "c has precedence over facecolor/facecolors. " + "This behavior may change in the future." + ) + + c_was_none = c is None + if c is None: + c = (facecolors if facecolors is not None + else "b" if mpl.rcParams['_internal.classic_mode'] + else get_next_color_func()) + c_is_string_or_strings = ( + isinstance(c, str) + or (np.iterable(c) and len(c) > 0 + and isinstance(cbook._safe_first_finite(c), str))) + + def invalid_shape_exception(csize, xsize): + return ValueError( + f"'c' argument has {csize} elements, which is inconsistent " + f"with 'x' and 'y' with size {xsize}.") + + c_is_mapped = False # Unless proven otherwise below. + valid_shape = True # Unless proven otherwise below. + if not c_was_none and kwcolor is None and not c_is_string_or_strings: + try: # First, does 'c' look suitable for value-mapping? + c = np.asanyarray(c, dtype=float) + except ValueError: + pass # Failed to convert to float array; must be color specs. + else: + # handle the documented special case of a 2D array with 1 + # row which as RGB(A) to broadcast. + if c.shape == (1, 4) or c.shape == (1, 3): + c_is_mapped = False + if c.size != xsize: + valid_shape = False + # If c can be either mapped values or an RGB(A) color, prefer + # the former if shapes match, the latter otherwise. + elif c.size == xsize: + c = c.ravel() + c_is_mapped = True + else: # Wrong size; it must not be intended for mapping. + if c.shape in ((3,), (4,)): + _api.warn_external( + "*c* argument looks like a single numeric RGB or " + "RGBA sequence, which should be avoided as value-" + "mapping will have precedence in case its length " + "matches with *x* & *y*. Please use the *color* " + "keyword-argument or provide a 2D array " + "with a single row if you intend to specify " + "the same RGB or RGBA value for all points.") + valid_shape = False + if not c_is_mapped: + try: # Is 'c' acceptable as PathCollection facecolors? + colors = mcolors.to_rgba_array(c) + except (TypeError, ValueError) as err: + if "RGBA values should be within 0-1 range" in str(err): + raise + else: + if not valid_shape: + raise invalid_shape_exception(c.size, xsize) from err + # Both the mapping *and* the RGBA conversion failed: pretty + # severe failure => one may appreciate a verbose feedback. + raise ValueError( + f"'c' argument must be a color, a sequence of colors, " + f"or a sequence of numbers, not {c!r}") from err + else: + if len(colors) not in (0, 1, xsize): + # NB: remember that a single color is also acceptable. + # Besides *colors* will be an empty array if c == 'none'. + raise invalid_shape_exception(len(colors), xsize) + else: + colors = None # use cmap, norm after collection is created + return c, colors, edgecolors + + @_api.make_keyword_only("3.10", "marker") + @_preprocess_data(replace_names=["x", "y", "s", "linewidths", + "edgecolors", "c", "facecolor", + "facecolors", "color"], + label_namer="y") + @_docstring.interpd + def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, + vmin=None, vmax=None, alpha=None, linewidths=None, *, + edgecolors=None, colorizer=None, plotnonfinite=False, **kwargs): + """ + A scatter plot of *y* vs. *x* with varying marker size and/or color. + + Parameters + ---------- + x, y : float or array-like, shape (n, ) + The data positions. + + s : float or array-like, shape (n, ), optional + The marker size in points**2 (typographic points are 1/72 in.). + Default is ``rcParams['lines.markersize'] ** 2``. + + The linewidth and edgecolor can visually interact with the marker + size, and can lead to artifacts if the marker size is smaller than + the linewidth. + + If the linewidth is greater than 0 and the edgecolor is anything + but *'none'*, then the effective size of the marker will be + increased by half the linewidth because the stroke will be centered + on the edge of the shape. + + To eliminate the marker edge either set *linewidth=0* or + *edgecolor='none'*. + + c : array-like or list of :mpltype:`color` or :mpltype:`color`, optional + The marker colors. Possible values: + + - A scalar or sequence of n numbers to be mapped to colors using + *cmap* and *norm*. + - A 2D array in which the rows are RGB or RGBA. + - A sequence of colors of length n. + - A single color format string. + + Note that *c* should not be a single numeric RGB or RGBA sequence + because that is indistinguishable from an array of values to be + colormapped. If you want to specify the same RGB or RGBA value for + all points, use a 2D array with a single row. Otherwise, + value-matching will have precedence in case of a size matching with + *x* and *y*. + + If you wish to specify a single color for all points + prefer the *color* keyword argument. + + Defaults to `None`. In that case the marker color is determined + by the value of *color*, *facecolor* or *facecolors*. In case + those are not specified or `None`, the marker color is determined + by the next color of the ``Axes``' current "shape and fill" color + cycle. This cycle defaults to :rc:`axes.prop_cycle`. + + marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker` + The marker style. *marker* can be either an instance of the class + or the text shorthand for a particular marker. + See :mod:`matplotlib.markers` for more information about marker + styles. + + %(cmap_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *c* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *c* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float or array-like, default: :rc:`lines.linewidth` + The linewidth of the marker edges. Note: The default *edgecolors* + is 'face'. You may want to change this as well. + + edgecolors : {'face', 'none', *None*} or :mpltype:`color` or list of \ +:mpltype:`color`, default: :rc:`scatter.edgecolors` + The edge color of the marker. Possible values: + + - 'face': The edge color will always be the same as the face color. + - 'none': No patch boundary will be drawn. + - A color or sequence of colors. + + For non-filled markers, *edgecolors* is ignored. Instead, the color + is determined like with 'face', i.e. from *c*, *colors*, or + *facecolors*. + + %(colorizer_doc)s + + This parameter is ignored if *c* is RGB(A). + + plotnonfinite : bool, default: False + Whether to plot points with nonfinite *c* (i.e. ``inf``, ``-inf`` + or ``nan``). If ``True`` the points are drawn with the *bad* + colormap color (see `.Colormap.set_bad`). + + Returns + ------- + `~matplotlib.collections.PathCollection` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs : `~matplotlib.collections.PathCollection` properties + %(PathCollection:kwdoc)s + + See Also + -------- + plot : To plot scatter plots when markers are identical in size and + color. + + Notes + ----- + * The `.plot` function will be faster for scatterplots where markers + don't vary in size or color. + + * Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which + case all masks will be combined and only unmasked points will be + plotted. + + * Fundamentally, scatter works with 1D arrays; *x*, *y*, *s*, and *c* + may be input as N-D arrays, but within scatter they will be + flattened. The exception is *c*, which will be flattened only if its + size matches the size of *x* and *y*. + + """ + # add edgecolors and linewidths to kwargs so they + # can be processed by normailze_kwargs + if edgecolors is not None: + kwargs.update({'edgecolors': edgecolors}) + if linewidths is not None: + kwargs.update({'linewidths': linewidths}) + + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + # re direct linewidth and edgecolor so it can be + # further processed by the rest of the function + linewidths = kwargs.pop('linewidth', None) + edgecolors = kwargs.pop('edgecolor', None) + # Process **kwargs to handle aliases, conflicts with explicit kwargs: + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + # np.ma.ravel yields an ndarray, not a masked array, + # unless its argument is a masked array. + x = np.ma.ravel(x) + y = np.ma.ravel(y) + if x.size != y.size: + raise ValueError("x and y must be the same size") + + if s is None: + s = (20 if mpl.rcParams['_internal.classic_mode'] else + mpl.rcParams['lines.markersize'] ** 2.0) + s = np.ma.ravel(s) + if (len(s) not in (1, x.size) or + (not np.issubdtype(s.dtype, np.floating) and + not np.issubdtype(s.dtype, np.integer))): + raise ValueError( + "s must be a scalar, " + "or float array-like with the same size as x and y") + + # get the original edgecolor the user passed before we normalize + orig_edgecolor = edgecolors + if edgecolors is None: + orig_edgecolor = kwargs.get('edgecolor', None) + c, colors, edgecolors = \ + self._parse_scatter_color_args( + c, edgecolors, kwargs, x.size, + get_next_color_func=self._get_patches_for_fill.get_next_color) + + if plotnonfinite and colors is None: + c = np.ma.masked_invalid(c) + x, y, s, edgecolors, linewidths = \ + cbook._combine_masks(x, y, s, edgecolors, linewidths) + else: + x, y, s, c, colors, edgecolors, linewidths = \ + cbook._combine_masks( + x, y, s, c, colors, edgecolors, linewidths) + # Unmask edgecolors if it was actually a single RGB or RGBA. + if (x.size in (3, 4) + and np.ma.is_masked(edgecolors) + and not np.ma.is_masked(orig_edgecolor)): + edgecolors = edgecolors.data + + scales = s # Renamed for readability below. + + # load default marker from rcParams + if marker is None: + marker = mpl.rcParams['scatter.marker'] + + if isinstance(marker, mmarkers.MarkerStyle): + marker_obj = marker + else: + marker_obj = mmarkers.MarkerStyle(marker) + + path = marker_obj.get_path().transformed( + marker_obj.get_transform()) + if not marker_obj.is_filled(): + if orig_edgecolor is not None: + _api.warn_external( + f"You passed a edgecolor/edgecolors ({orig_edgecolor!r}) " + f"for an unfilled marker ({marker!r}). Matplotlib is " + "ignoring the edgecolor in favor of the facecolor. This " + "behavior may change in the future." + ) + # We need to handle markers that cannot be filled (like + # '+' and 'x') differently than markers that can be + # filled, but have their fillstyle set to 'none'. This is + # to get: + # + # - respecting the fillestyle if set + # - maintaining back-compatibility for querying the facecolor of + # the un-fillable markers. + # + # While not an ideal situation, but is better than the + # alternatives. + if marker_obj.get_fillstyle() == 'none': + # promote the facecolor to be the edgecolor + edgecolors = colors + # set the facecolor to 'none' (at the last chance) because + # we cannot fill a path if the facecolor is non-null + # (which is defendable at the renderer level). + colors = 'none' + else: + # if we are not nulling the face color we can do this + # simpler + edgecolors = 'face' + + if linewidths is None: + linewidths = mpl.rcParams['lines.linewidth'] + elif np.iterable(linewidths): + linewidths = [ + lw if lw is not None else mpl.rcParams['lines.linewidth'] + for lw in linewidths] + + offsets = np.ma.column_stack([x, y]) + + collection = mcoll.PathCollection( + (path,), scales, + facecolors=colors, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=kwargs.pop('transform', self.transData), + alpha=alpha, + ) + collection.set_transform(mtransforms.IdentityTransform()) + if colors is None: + if colorizer: + collection._set_colorizer_check_keywords(colorizer, cmap=cmap, + norm=norm, vmin=vmin, + vmax=vmax) + else: + collection.set_cmap(cmap) + collection.set_norm(norm) + collection.set_array(c) + collection._scale_norm(norm, vmin, vmax) + else: + extra_kwargs = { + 'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax + } + extra_keys = [k for k, v in extra_kwargs.items() if v is not None] + if any(extra_keys): + keys_str = ", ".join(f"'{k}'" for k in extra_keys) + _api.warn_external( + "No data for colormapping provided via 'c'. " + f"Parameters {keys_str} will be ignored") + collection._internal_update(kwargs) + + # Classic mode only: + # ensure there are margins to allow for the + # finite size of the symbols. In v2.x, margins + # are present by default, so we disable this + # scatter-specific override. + if mpl.rcParams['_internal.classic_mode']: + if self._xmargin < 0.05 and x.size > 0: + self.set_xmargin(0.05) + if self._ymargin < 0.05 and x.size > 0: + self.set_ymargin(0.05) + + self.add_collection(collection) + self._request_autoscale_view() + + return collection + + @_api.make_keyword_only("3.10", "gridsize") + @_preprocess_data(replace_names=["x", "y", "C"], label_namer="y") + @_docstring.interpd + def hexbin(self, x, y, C=None, gridsize=100, bins=None, + xscale='linear', yscale='linear', extent=None, + cmap=None, norm=None, vmin=None, vmax=None, + alpha=None, linewidths=None, edgecolors='face', + reduce_C_function=np.mean, mincnt=None, marginals=False, + colorizer=None, **kwargs): + """ + Make a 2D hexagonal binning plot of points *x*, *y*. + + If *C* is *None*, the value of the hexagon is determined by the number + of points in the hexagon. Otherwise, *C* specifies values at the + coordinate (x[i], y[i]). For each hexagon, these values are reduced + using *reduce_C_function*. + + Parameters + ---------- + x, y : array-like + The data positions. *x* and *y* must be of the same length. + + C : array-like, optional + If given, these values are accumulated in the bins. Otherwise, + every point has a value of 1. Must be of the same length as *x* + and *y*. + + gridsize : int or (int, int), default: 100 + If a single int, the number of hexagons in the *x*-direction. + The number of hexagons in the *y*-direction is chosen such that + the hexagons are approximately regular. + + Alternatively, if a tuple (*nx*, *ny*), the number of hexagons + in the *x*-direction and the *y*-direction. In the + *y*-direction, counting is done along vertically aligned + hexagons, not along the zig-zag chains of hexagons; see the + following illustration. + + .. plot:: + + import numpy + import matplotlib.pyplot as plt + + np.random.seed(19680801) + n= 300 + x = np.random.standard_normal(n) + y = np.random.standard_normal(n) + + fig, ax = plt.subplots(figsize=(4, 4)) + h = ax.hexbin(x, y, gridsize=(5, 3)) + hx, hy = h.get_offsets().T + ax.plot(hx[24::3], hy[24::3], 'ro-') + ax.plot(hx[-3:], hy[-3:], 'ro-') + ax.set_title('gridsize=(5, 3)') + ax.axis('off') + + To get approximately regular hexagons, choose + :math:`n_x = \\sqrt{3}\\,n_y`. + + bins : 'log' or int or sequence, default: None + Discretization of the hexagon values. + + - If *None*, no binning is applied; the color of each hexagon + directly corresponds to its count value. + - If 'log', use a logarithmic scale for the colormap. + Internally, :math:`log_{10}(i+1)` is used to determine the + hexagon color. This is equivalent to ``norm=LogNorm()``. + - If an integer, divide the counts in the specified number + of bins, and color the hexagons accordingly. + - If a sequence of values, the values of the lower bound of + the bins to be used. + + xscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the horizontal axis. + + yscale : {'linear', 'log'}, default: 'linear' + Use a linear or log10 scale on the vertical axis. + + mincnt : int >= 0, default: *None* + If not *None*, only display cells with at least *mincnt* + number of points in the cell. + + marginals : bool, default: *False* + If marginals is *True*, plot the marginal density as + colormapped rectangles along the bottom of the x-axis and + left of the y-axis. + + extent : 4-tuple of float, default: *None* + The limits of the bins (xmin, xmax, ymin, ymax). + The default assigns the limits based on + *gridsize*, *x*, *y*, *xscale* and *yscale*. + + If *xscale* or *yscale* is set to 'log', the limits are + expected to be the exponent for a power of 10. E.g. for + x-limits of 1 and 50 in 'linear' scale and y-limits + of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3). + + Returns + ------- + `~matplotlib.collections.PolyCollection` + A `.PolyCollection` defining the hexagonal bins. + + - `.PolyCollection.get_offsets` contains a Mx2 array containing + the x, y positions of the M hexagon centers in data coordinates. + - `.PolyCollection.get_array` contains the values of the M + hexagons. + + If *marginals* is *True*, horizontal + bar and vertical bar (both PolyCollections) will be attached + to the return collection as attributes *hbar* and *vbar*. + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + alpha : float between 0 and 1, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + + linewidths : float, default: *None* + If *None*, defaults to :rc:`patch.linewidth`. + + edgecolors : {'face', 'none', *None*} or color, default: 'face' + The color of the hexagon edges. Possible values are: + + - 'face': Draw the edges in the same color as the fill color. + - 'none': No edges are drawn. This can sometimes lead to unsightly + unpainted pixels between the hexagons. + - *None*: Draw outlines in the default color. + - An explicit color. + + reduce_C_function : callable, default: `numpy.mean` + The function to aggregate *C* within the bins. It is ignored if + *C* is not given. This must have the signature:: + + def reduce_C_function(C: array) -> float + + Commonly used functions are: + + - `numpy.mean`: average of the points + - `numpy.sum`: integral of the point values + - `numpy.amax`: value taken from the largest point + + By default will only reduce cells with at least 1 point because some + reduction functions (such as `numpy.amax`) will error/warn with empty + input. Changing *mincnt* will adjust the cutoff, and if set to 0 will + pass empty input to the reduction function. + + %(colorizer_doc)s + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.collections.PolyCollection` properties + All other keyword arguments are passed on to `.PolyCollection`: + + %(PolyCollection:kwdoc)s + + See Also + -------- + hist2d : 2D histogram rectangular bins + """ + self._process_unit_info([("x", x), ("y", y)], kwargs, convert=False) + + x, y, C = cbook.delete_masked_points(x, y, C) + + # Set the size of the hexagon grid + if np.iterable(gridsize): + nx, ny = gridsize + else: + nx = gridsize + ny = int(nx / math.sqrt(3)) + # Count the number of data in each hexagon + x = np.asarray(x, float) + y = np.asarray(y, float) + + # Will be log()'d if necessary, and then rescaled. + tx = x + ty = y + + if xscale == 'log': + if np.any(x <= 0.0): + raise ValueError( + "x contains non-positive values, so cannot be log-scaled") + tx = np.log10(tx) + if yscale == 'log': + if np.any(y <= 0.0): + raise ValueError( + "y contains non-positive values, so cannot be log-scaled") + ty = np.log10(ty) + if extent is not None: + xmin, xmax, ymin, ymax = extent + if xmin > xmax: + raise ValueError("In extent, xmax must be greater than xmin") + if ymin > ymax: + raise ValueError("In extent, ymax must be greater than ymin") + else: + xmin, xmax = (tx.min(), tx.max()) if len(x) else (0, 1) + ymin, ymax = (ty.min(), ty.max()) if len(y) else (0, 1) + + # to avoid issues with singular data, expand the min/max pairs + xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1) + ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1) + + nx1 = nx + 1 + ny1 = ny + 1 + nx2 = nx + ny2 = ny + n = nx1 * ny1 + nx2 * ny2 + + # In the x-direction, the hexagons exactly cover the region from + # xmin to xmax. Need some padding to avoid roundoff errors. + padding = 1.e-9 * (xmax - xmin) + xmin -= padding + xmax += padding + sx = (xmax - xmin) / nx + sy = (ymax - ymin) / ny + # Positions in hexagon index coordinates. + ix = (tx - xmin) / sx + iy = (ty - ymin) / sy + ix1 = np.round(ix).astype(int) + iy1 = np.round(iy).astype(int) + ix2 = np.floor(ix).astype(int) + iy2 = np.floor(iy).astype(int) + # flat indices, plus one so that out-of-range points go to position 0. + i1 = np.where((0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1), + ix1 * ny1 + iy1 + 1, 0) + i2 = np.where((0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2), + ix2 * ny2 + iy2 + 1, 0) + + d1 = (ix - ix1) ** 2 + 3.0 * (iy - iy1) ** 2 + d2 = (ix - ix2 - 0.5) ** 2 + 3.0 * (iy - iy2 - 0.5) ** 2 + bdist = (d1 < d2) + + if C is None: # [1:] drops out-of-range points. + counts1 = np.bincount(i1[bdist], minlength=1 + nx1 * ny1)[1:] + counts2 = np.bincount(i2[~bdist], minlength=1 + nx2 * ny2)[1:] + accum = np.concatenate([counts1, counts2]).astype(float) + if mincnt is not None: + accum[accum < mincnt] = np.nan + C = np.ones(len(x)) + else: + # store the C values in a list per hexagon index + Cs_at_i1 = [[] for _ in range(1 + nx1 * ny1)] + Cs_at_i2 = [[] for _ in range(1 + nx2 * ny2)] + for i in range(len(x)): + if bdist[i]: + Cs_at_i1[i1[i]].append(C[i]) + else: + Cs_at_i2[i2[i]].append(C[i]) + if mincnt is None: + mincnt = 1 + accum = np.array( + [reduce_C_function(acc) if len(acc) >= mincnt else np.nan + for Cs_at_i in [Cs_at_i1, Cs_at_i2] + for acc in Cs_at_i[1:]], # [1:] drops out-of-range points. + float) + + good_idxs = ~np.isnan(accum) + + offsets = np.zeros((n, 2), float) + offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1) + offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1) + offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2) + offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5 + offsets[:, 0] *= sx + offsets[:, 1] *= sy + offsets[:, 0] += xmin + offsets[:, 1] += ymin + # remove accumulation bins with no data + offsets = offsets[good_idxs, :] + accum = accum[good_idxs] + + polygon = [sx, sy / 3] * np.array( + [[.5, -.5], [.5, .5], [0., 1.], [-.5, .5], [-.5, -.5], [0., -1.]]) + + if linewidths is None: + linewidths = [mpl.rcParams['patch.linewidth']] + + if xscale == 'log' or yscale == 'log': + polygons = np.expand_dims(polygon, 0) + if xscale == 'log': + polygons[:, :, 0] = 10.0 ** polygons[:, :, 0] + xmin = 10.0 ** xmin + xmax = 10.0 ** xmax + self.set_xscale(xscale) + if yscale == 'log': + polygons[:, :, 1] = 10.0 ** polygons[:, :, 1] + ymin = 10.0 ** ymin + ymax = 10.0 ** ymax + self.set_yscale(yscale) + else: + polygons = [polygon] + + collection = mcoll.PolyCollection( + polygons, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + offset_transform=mtransforms.AffineDeltaTransform(self.transData) + ) + + # Set normalizer if bins is 'log' + if cbook._str_equal(bins, 'log'): + if norm is not None: + _api.warn_external("Only one of 'bins' and 'norm' arguments " + f"can be supplied, ignoring {bins=}") + else: + norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) + vmin = vmax = None + bins = None + + if bins is not None: + if not np.iterable(bins): + minimum, maximum = min(accum), max(accum) + bins -= 1 # one less edge than bins + bins = minimum + (maximum - minimum) * np.arange(bins) / bins + bins = np.sort(bins) + accum = bins.searchsorted(accum) + + if colorizer: + collection._set_colorizer_check_keywords(colorizer, cmap=cmap, + norm=norm, vmin=vmin, + vmax=vmax) + else: + collection.set_cmap(cmap) + collection.set_norm(norm) + collection.set_array(accum) + collection.set_alpha(alpha) + collection._internal_update(kwargs) + collection._scale_norm(norm, vmin, vmax) + + # autoscale the norm with current accum values if it hasn't been set + if norm is not None: + if collection.norm.vmin is None and collection.norm.vmax is None: + collection.norm.autoscale() + + corners = ((xmin, ymin), (xmax, ymax)) + self.update_datalim(corners) + self._request_autoscale_view(tight=True) + + # add the collection last + self.add_collection(collection, autolim=False) + if not marginals: + return collection + + # Process marginals + bars = [] + for zname, z, zmin, zmax, zscale, nbins in [ + ("x", x, xmin, xmax, xscale, nx), + ("y", y, ymin, ymax, yscale, 2 * ny), + ]: + + if zscale == "log": + bin_edges = np.geomspace(zmin, zmax, nbins + 1) + else: + bin_edges = np.linspace(zmin, zmax, nbins + 1) + + verts = np.empty((nbins, 4, 2)) + verts[:, 0, 0] = verts[:, 1, 0] = bin_edges[:-1] + verts[:, 2, 0] = verts[:, 3, 0] = bin_edges[1:] + verts[:, 0, 1] = verts[:, 3, 1] = .00 + verts[:, 1, 1] = verts[:, 2, 1] = .05 + if zname == "y": + verts = verts[:, :, ::-1] # Swap x and y. + + # Sort z-values into bins defined by bin_edges. + bin_idxs = np.searchsorted(bin_edges, z) - 1 + values = np.empty(nbins) + for i in range(nbins): + # Get C-values for each bin, and compute bin value with + # reduce_C_function. + ci = C[bin_idxs == i] + values[i] = reduce_C_function(ci) if len(ci) > 0 else np.nan + + mask = ~np.isnan(values) + verts = verts[mask] + values = values[mask] + + trans = getattr(self, f"get_{zname}axis_transform")(which="grid") + bar = mcoll.PolyCollection( + verts, transform=trans, edgecolors="face") + bar.set_array(values) + bar.set_cmap(cmap) + bar.set_norm(norm) + bar.set_alpha(alpha) + bar._internal_update(kwargs) + bars.append(self.add_collection(bar, autolim=False)) + + collection.hbar, collection.vbar = bars + + def on_changed(collection): + collection.hbar.set_cmap(collection.get_cmap()) + collection.hbar.set_cmap(collection.get_cmap()) + collection.vbar.set_clim(collection.get_clim()) + collection.vbar.set_clim(collection.get_clim()) + + collection.callbacks.connect('changed', on_changed) + + return collection + + @_docstring.interpd + def arrow(self, x, y, dx, dy, **kwargs): + """ + [*Discouraged*] Add an arrow to the Axes. + + This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``. + + .. admonition:: Discouraged + + The use of this method is discouraged because it is not guaranteed + that the arrow renders reasonably. For example, the resulting arrow + is affected by the Axes aspect ratio and limits, which may distort + the arrow. + + Consider using `~.Axes.annotate` without a text instead, e.g. :: + + ax.annotate("", xytext=(0, 0), xy=(0.5, 0.5), + arrowprops=dict(arrowstyle="->")) + + Parameters + ---------- + %(FancyArrow)s + + Returns + ------- + `.FancyArrow` + The created `.FancyArrow` object. + """ + # Strip away units for the underlying patch since units + # do not make sense to most patch-like code + x = self.convert_xunits(x) + y = self.convert_yunits(y) + dx = self.convert_xunits(dx) + dy = self.convert_yunits(dy) + + a = mpatches.FancyArrow(x, y, dx, dy, **kwargs) + self.add_patch(a) + self._request_autoscale_view() + return a + + @_docstring.copy(mquiver.QuiverKey.__init__) + def quiverkey(self, Q, X, Y, U, label, **kwargs): + qk = mquiver.QuiverKey(Q, X, Y, U, label, **kwargs) + self.add_artist(qk) + return qk + + # Handle units for x and y, if they've been passed + def _quiver_units(self, args, kwargs): + if len(args) > 3: + x, y = args[0:2] + x, y = self._process_unit_info([("x", x), ("y", y)], kwargs) + return (x, y) + args[2:] + return args + + # args can be a combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.interpd + def quiver(self, *args, **kwargs): + """%(quiver_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + q = mquiver.Quiver(self, *args, **kwargs) + self.add_collection(q, autolim=True) + self._request_autoscale_view() + return q + + # args can be some combination of X, Y, U, V, C and all should be replaced + @_preprocess_data() + @_docstring.interpd + def barbs(self, *args, **kwargs): + """%(barbs_doc)s""" + # Make sure units are handled for x and y values + args = self._quiver_units(args, kwargs) + b = mquiver.Barbs(self, *args, **kwargs) + self.add_collection(b, autolim=True) + self._request_autoscale_view() + return b + + # Uses a custom implementation of data-kwarg handling in + # _process_plot_var_args. + def fill(self, *args, data=None, **kwargs): + """ + Plot filled polygons. + + Parameters + ---------- + *args : sequence of x, y, [color] + Each polygon is defined by the lists of *x* and *y* positions of + its nodes, optionally followed by a *color* specifier. See + :mod:`matplotlib.colors` for supported color specifiers. The + standard color cycle is used for polygons without a color + specifier. + + You can plot multiple polygons by providing multiple *x*, *y*, + *[color]* groups. + + For example, each of the following is legal:: + + ax.fill(x, y) # a polygon with default color + ax.fill(x, y, "b") # a blue polygon + ax.fill(x, y, x2, y2) # two polygons + ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon + + data : indexable object, optional + An object with labelled data. If given, provide the label names to + plot in *x* and *y*, e.g.:: + + ax.fill("time", "signal", + data={"time": [0, 1, 2], "signal": [0, 1, 0]}) + + Returns + ------- + list of `~matplotlib.patches.Polygon` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.patches.Polygon` properties + + Notes + ----- + Use :meth:`fill_between` if you would like to fill the region between + two curves. + """ + # For compatibility(!), get aliases from Line2D rather than Patch. + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # _get_patches_for_fill returns a generator, convert it to a list. + patches = [*self._get_patches_for_fill(self, *args, data=data, **kwargs)] + for poly in patches: + self.add_patch(poly) + self._request_autoscale_view() + return patches + + def _fill_between_x_or_y( + self, ind_dir, ind, dep1, dep2=0, *, + where=None, interpolate=False, step=None, **kwargs): + # Common implementation between fill_between (*ind_dir*="x") and + # fill_betweenx (*ind_dir*="y"). *ind* is the independent variable, + # *dep* the dependent variable. The docstring below is interpolated + # to generate both methods' docstrings. + """ + Fill the area between two {dir} curves. + + The curves are defined by the points (*{ind}*, *{dep}1*) and (*{ind}*, + *{dep}2*). This creates one or multiple polygons describing the filled + area. + + You may exclude some {dir} sections from filling using *where*. + + By default, the edges connect the given points directly. Use *step* + if the filling should be a step function, i.e. constant in between + *{ind}*. + + Parameters + ---------- + {ind} : array-like + The {ind} coordinates of the nodes defining the curves. + + {dep}1 : array-like or float + The {dep} coordinates of the nodes defining the first curve. + + {dep}2 : array-like or float, default: 0 + The {dep} coordinates of the nodes defining the second curve. + + where : array-like of bool, optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``{ind}[where]``. + More precisely, fill between ``{ind}[i]`` and ``{ind}[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + interpolate : bool, default: False + This option is only relevant if *where* is used and the two curves + are crossing each other. + + Semantically, *where* is often used for *{dep}1* > *{dep}2* or + similar. By default, the nodes of the polygon defining the filled + region will only be placed at the positions in the *{ind}* array. + Such a polygon cannot describe the above semantics close to the + intersection. The {ind}-sections containing the intersection are + simply clipped. + + Setting *interpolate* to *True* will calculate the actual + intersection point and extend the filled region up to this point. + + step : {{'pre', 'post', 'mid'}}, optional + Define *step* if the filling should be a step function, + i.e. constant in between *{ind}*. The value determines where the + step will occur: + + - 'pre': The {dep} value is continued constantly to the left from + every *{ind}* position, i.e. the interval ``({ind}[i-1], {ind}[i]]`` + has the value ``{dep}[i]``. + - 'post': The y value is continued constantly to the right from + every *{ind}* position, i.e. the interval ``[{ind}[i], {ind}[i+1])`` + has the value ``{dep}[i]``. + - 'mid': Steps occur half-way between the *{ind}* positions. + + Returns + ------- + `.FillBetweenPolyCollection` + A `.FillBetweenPolyCollection` containing the plotted polygons. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed on to + `.FillBetweenPolyCollection`. They control the `.Polygon` properties: + + %(FillBetweenPolyCollection:kwdoc)s + + See Also + -------- + fill_between : Fill between two sets of y-values. + fill_betweenx : Fill between two sets of x-values. + """ + dep_dir = mcoll.FillBetweenPolyCollection._f_dir_from_t(ind_dir) + + if not mpl.rcParams["_internal.classic_mode"]: + kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) + if not any(c in kwargs for c in ("color", "facecolor")): + kwargs["facecolor"] = self._get_patches_for_fill.get_next_color() + + ind, dep1, dep2 = self._fill_between_process_units( + ind_dir, dep_dir, ind, dep1, dep2, **kwargs) + + collection = mcoll.FillBetweenPolyCollection( + ind_dir, ind, dep1, dep2, + where=where, interpolate=interpolate, step=step, **kwargs) + + self.add_collection(collection) + self._request_autoscale_view() + return collection + + def _fill_between_process_units(self, ind_dir, dep_dir, ind, dep1, dep2, **kwargs): + """Handle united data, such as dates.""" + return map(np.ma.masked_invalid, self._process_unit_info( + [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs)) + + def fill_between(self, x, y1, y2=0, where=None, interpolate=False, + step=None, **kwargs): + return self._fill_between_x_or_y( + "x", x, y1, y2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_between.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="horizontal", ind="x", dep="y" + ) + fill_between = _preprocess_data( + _docstring.interpd(fill_between), + replace_names=["x", "y1", "y2", "where"]) + + def fill_betweenx(self, y, x1, x2=0, where=None, + step=None, interpolate=False, **kwargs): + return self._fill_between_x_or_y( + "y", y, x1, x2, + where=where, interpolate=interpolate, step=step, **kwargs) + + if _fill_between_x_or_y.__doc__: + fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format( + dir="vertical", ind="y", dep="x" + ) + fill_betweenx = _preprocess_data( + _docstring.interpd(fill_betweenx), + replace_names=["y", "x1", "x2", "where"]) + + #### plotting z(x, y): imshow, pcolor and relatives, contour + + @_preprocess_data() + @_docstring.interpd + def imshow(self, X, cmap=None, norm=None, *, aspect=None, + interpolation=None, alpha=None, + vmin=None, vmax=None, colorizer=None, origin=None, extent=None, + interpolation_stage=None, filternorm=True, filterrad=4.0, + resample=None, url=None, **kwargs): + """ + Display data as an image, i.e., on a 2D regular raster. + + The input may either be actual RGB(A) data, or 2D scalar data, which + will be rendered as a pseudocolor image. For displaying a grayscale + image, set up the colormapping using the parameters + ``cmap='gray', vmin=0, vmax=255``. + + The number of pixels used to render an image is set by the Axes size + and the figure *dpi*. This can lead to aliasing artifacts when + the image is resampled, because the displayed image size will usually + not match the size of *X* (see + :doc:`/gallery/images_contours_and_fields/image_antialiasing`). + The resampling can be controlled via the *interpolation* parameter + and/or :rc:`image.interpolation`. + + Parameters + ---------- + X : array-like or PIL image + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + Out-of-range RGB(A) values are clipped. + + %(cmap_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *X* is RGB(A). + + %(colorizer_doc)s + + This parameter is ignored if *X* is RGB(A). + + aspect : {'equal', 'auto'} or float or None, default: None + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square + (unless pixel sizes are explicitly made non-square in data + coordinates using *extent*). + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + + Normally, None (the default) means to use :rc:`image.aspect`. However, if + the image uses a transform that does not contain the axes data transform, + then None means to not modify the axes aspect at all (in that case, directly + call `.Axes.set_aspect` if desired). + + interpolation : str, default: :rc:`image.interpolation` + The interpolation method used. + + Supported values are 'none', 'auto', 'nearest', 'bilinear', + 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', + 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', + 'sinc', 'lanczos', 'blackman'. + + The data *X* is resampled to the pixel size of the image on the + figure canvas, using the interpolation method to either up- or + downsample the data. + + If *interpolation* is 'none', then for the ps, pdf, and svg + backends no down- or upsampling occurs, and the image data is + passed to the backend as a native image. Note that different ps, + pdf, and svg viewers may display these raw pixels differently. On + other backends, 'none' is the same as 'nearest'. + + If *interpolation* is the default 'auto', then 'nearest' + interpolation is used if the image is upsampled by more than a + factor of three (i.e. the number of display pixels is at least + three times the size of the data array). If the upsampling rate is + smaller than 3, or the image is downsampled, then 'hanning' + interpolation is used to act as an anti-aliasing filter, unless the + image happens to be upsampled by exactly a factor of two or one. + + See + :doc:`/gallery/images_contours_and_fields/interpolation_methods` + for an overview of the supported interpolation methods, and + :doc:`/gallery/images_contours_and_fields/image_antialiasing` for + a discussion of image antialiasing. + + Some interpolation methods require an additional radius parameter, + which can be set by *filterrad*. Additionally, the antigrain image + resize filter is controlled by the parameter *filternorm*. + + interpolation_stage : {'auto', 'data', 'rgba'}, default: 'auto' + Supported values: + + - 'data': Interpolation is carried out on the data provided by the user + This is useful if interpolating between pixels during upsampling. + - 'rgba': The interpolation is carried out in RGBA-space after the + color-mapping has been applied. This is useful if downsampling and + combining pixels visually. + - 'auto': Select a suitable interpolation stage automatically. This uses + 'rgba' when downsampling, or upsampling at a rate less than 3, and + 'data' when upsampling at a higher rate. + + See :doc:`/gallery/images_contours_and_fields/image_antialiasing` for + a discussion of image antialiasing. + + alpha : float or array-like, optional + The alpha blending value, between 0 (transparent) and 1 (opaque). + If *alpha* is an array, the alpha blending values are applied pixel + by pixel, and *alpha* must have the same shape as *X*. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower + left corner of the Axes. The convention (the default) 'upper' is + typically used for matrices and images. + + Note that the vertical axis points upward for 'lower' + but downward for 'upper'. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + extent : floats (left, right, bottom, top), optional + The bounding box in data coordinates that the image will fill. + These values may be unitful and match the units of the Axes. + The image is stretched individually along x and y to fill the box. + + The default extent is determined by the following conditions. + Pixels have unit size in data coordinates. Their centers are on + integer coordinates, and their center coordinates range from 0 to + columns-1 horizontally and from 0 to rows-1 vertically. + + Note that the direction of the vertical axis and thus the default + values for top and bottom depend on *origin*: + + - For ``origin == 'upper'`` the default is + ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``. + - For ``origin == 'lower'`` the default is + ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``. + + See the :ref:`imshow_extent` tutorial for + examples and a more detailed description. + + filternorm : bool, default: True + A parameter for the antigrain image resize filter (see the + antigrain documentation). If *filternorm* is set, the filter + normalizes integer values and corrects the rounding errors. It + doesn't do anything with the source floating point values, it + corrects only integers according to the rule of 1.0 which means + that any sum of pixel weights must be equal to 1.0. So, the + filter function must produce a graph of the proper shape. + + filterrad : float > 0, default: 4.0 + The filter radius for filters that have a radius parameter, i.e. + when interpolation is one of: 'sinc', 'lanczos' or 'blackman'. + + resample : bool, default: :rc:`image.resample` + When *True*, use a full resampling method. When *False*, only + resample when the output image is larger than the input image. + + url : str, optional + Set the url of the created `.AxesImage`. See `.Artist.set_url`. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs : `~matplotlib.artist.Artist` properties + These parameters are passed on to the constructor of the + `.AxesImage` artist. + + See Also + -------- + matshow : Plot a matrix or an array as an image. + + Notes + ----- + Unless *extent* is used, pixel centers will be located at integer + coordinates. In other words: the origin will coincide with the center + of pixel (0, 0). + + There are two common representations for RGB images with an alpha + channel: + + - Straight (unassociated) alpha: R, G, and B channels represent the + color of the pixel, disregarding its opacity. + - Premultiplied (associated) alpha: R, G, and B channels represent + the color of the pixel, adjusted for its opacity by multiplication. + + `~matplotlib.pyplot.imshow` expects RGB images adopting the straight + (unassociated) alpha representation. + """ + im = mimage.AxesImage(self, cmap=cmap, norm=norm, colorizer=colorizer, + interpolation=interpolation, origin=origin, + extent=extent, filternorm=filternorm, + filterrad=filterrad, resample=resample, + interpolation_stage=interpolation_stage, + **kwargs) + + if aspect is None and not ( + im.is_transform_set() + and not im.get_transform().contains_branch(self.transData)): + aspect = mpl.rcParams['image.aspect'] + if aspect is not None: + self.set_aspect(aspect) + + im.set_data(X) + im.set_alpha(alpha) + if im.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + im.set_clip_path(self.patch) + im._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + im._scale_norm(norm, vmin, vmax) + im.set_url(url) + + # update ax.dataLim, and, if autoscaling, set viewLim + # to tightly fit the image, regardless of dataLim. + im.set_extent(im.get_extent()) + + self.add_image(im) + return im + + def _pcolorargs(self, funcname, *args, shading='auto', **kwargs): + # - create X and Y if not present; + # - reshape X and Y as needed if they are 1-D; + # - check for proper sizes based on `shading` kwarg; + # - reset shading if shading='auto' to flat or nearest + # depending on size; + + _valid_shading = ['gouraud', 'nearest', 'flat', 'auto'] + try: + _api.check_in_list(_valid_shading, shading=shading) + except ValueError: + _api.warn_external(f"shading value '{shading}' not in list of " + f"valid values {_valid_shading}. Setting " + "shading='auto'.") + shading = 'auto' + + if len(args) == 1: + C = np.asanyarray(args[0]) + nrows, ncols = C.shape[:2] + if shading in ['gouraud', 'nearest']: + X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows)) + else: + X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1)) + shading = 'flat' + elif len(args) == 3: + # Check x and y for bad data... + C = np.asanyarray(args[2]) + # unit conversion allows e.g. datetime objects as axis values + X, Y = args[:2] + X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs) + X, Y = (cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]) + + if funcname == 'pcolormesh': + if np.ma.is_masked(X) or np.ma.is_masked(Y): + raise ValueError( + 'x and y arguments to pcolormesh cannot have ' + 'non-finite values or be of type ' + 'numpy.ma.MaskedArray with masked values') + nrows, ncols = C.shape[:2] + else: + raise _api.nargs_error(funcname, takes="1 or 3", given=len(args)) + + Nx = X.shape[-1] + Ny = Y.shape[0] + if X.ndim != 2 or X.shape[0] == 1: + x = X.reshape(1, Nx) + X = x.repeat(Ny, axis=0) + if Y.ndim != 2 or Y.shape[1] == 1: + y = Y.reshape(Ny, 1) + Y = y.repeat(Nx, axis=1) + if X.shape != Y.shape: + raise TypeError(f'Incompatible X, Y inputs to {funcname}; ' + f'see help({funcname})') + + if shading == 'auto': + if ncols == Nx and nrows == Ny: + shading = 'nearest' + else: + shading = 'flat' + + if shading == 'flat': + if (Nx, Ny) != (ncols + 1, nrows + 1): + raise TypeError(f"Dimensions of C {C.shape} should" + f" be one smaller than X({Nx}) and Y({Ny})" + f" while using shading='flat'" + f" see help({funcname})") + else: # ['nearest', 'gouraud']: + if (Nx, Ny) != (ncols, nrows): + raise TypeError('Dimensions of C %s are incompatible with' + ' X (%d) and/or Y (%d); see help(%s)' % ( + C.shape, Nx, Ny, funcname)) + if shading == 'nearest': + # grid is specified at the center, so define corners + # at the midpoints between the grid centers and then use the + # flat algorithm. + def _interp_grid(X, require_monotonicity=False): + # helper for below. To ensure the cell edges are calculated + # correctly, when expanding columns, the monotonicity of + # X coords needs to be checked. When expanding rows, the + # monotonicity of Y coords needs to be checked. + if np.shape(X)[1] > 1: + dX = np.diff(X, axis=1) * 0.5 + if (require_monotonicity and + not (np.all(dX >= 0) or np.all(dX <= 0))): + _api.warn_external( + f"The input coordinates to {funcname} are " + "interpreted as cell centers, but are not " + "monotonically increasing or decreasing. " + "This may lead to incorrectly calculated cell " + "edges, in which case, please supply " + f"explicit cell edges to {funcname}.") + + hstack = np.ma.hstack if np.ma.isMA(X) else np.hstack + X = hstack((X[:, [0]] - dX[:, [0]], + X[:, :-1] + dX, + X[:, [-1]] + dX[:, [-1]])) + else: + # This is just degenerate, but we can't reliably guess + # a dX if there is just one value. + X = np.hstack((X, X)) + return X + + if ncols == Nx: + X = _interp_grid(X, require_monotonicity=True) + Y = _interp_grid(Y) + if nrows == Ny: + X = _interp_grid(X.T).T + Y = _interp_grid(Y.T, require_monotonicity=True).T + shading = 'flat' + + C = cbook.safe_masked_invalid(C, copy=True) + return X, Y, C, shading + + @_preprocess_data() + @_docstring.interpd + def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None, + vmin=None, vmax=None, colorizer=None, **kwargs): + r""" + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolor([X, Y,] C, /, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + The arguments *X*, *Y*, *C* are positional-only. + + .. hint:: + + ``pcolor()`` can be very slow for large arrays. In most + cases you should use the similar but much faster + `~.Axes.pcolormesh` instead. See + :ref:`Differences between pcolor() and pcolormesh() + ` for a discussion of the + differences. + + Parameters + ---------- + C : 2D array-like + The color-mapped values. Color-mapping is controlled by *cmap*, + *norm*, *vmin*, and *vmax*. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'``, the dimensions of *X* and *Y* should be + the same as those of *C* (if not, a ValueError will be raised). The + color ``C[i, j]`` will be centered on ``(X[i, j], Y[i, j])``. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + shading : {'flat', 'nearest', 'auto'}, default: :rc:`pcolor.shading` + The fill style for the quadrilateral. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value of the face color, between 0 (transparent) + and 1 (opaque). Note: The edgecolor is currently not affected by + this. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `matplotlib.collections.PolyQuadMesh` + + Other Parameters + ---------------- + antialiaseds : bool, default: False + The default *antialiaseds* is False if the default + *edgecolors*\ ="none" is used. This eliminates artificial lines + at patch boundaries, and works regardless of the value of alpha. + If *edgecolors* is not "none", then the default *antialiaseds* + is taken from :rc:`patch.antialiased`. + Stroking the edges may be preferred if *alpha* is 1, but will + cause artifacts otherwise. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.PolyQuadMesh` constructor: + + %(PolyCollection:kwdoc)s + + See Also + -------- + pcolormesh : for an explanation of the differences between + pcolor and pcolormesh. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *X*, *Y* and *C* may be masked arrays. If either ``C[i, j]``, or one + of the vertices surrounding ``C[i, j]`` (*X* or *Y* at + ``[i, j], [i+1, j], [i, j+1], [i+1, j+1]``) is masked, nothing is + plotted. + + .. _axes-pcolor-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + """ + + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading, + kwargs=kwargs) + linewidths = (0.25,) + if 'linewidth' in kwargs: + kwargs['linewidths'] = kwargs.pop('linewidth') + kwargs.setdefault('linewidths', linewidths) + + if 'edgecolor' in kwargs: + kwargs['edgecolors'] = kwargs.pop('edgecolor') + ec = kwargs.setdefault('edgecolors', 'none') + + # aa setting will default via collections to patch.antialiased + # unless the boundary is not stroked, in which case the + # default will be False; with unstroked boundaries, aa + # makes artifacts that are often disturbing. + if 'antialiaseds' in kwargs: + kwargs['antialiased'] = kwargs.pop('antialiaseds') + if 'antialiased' not in kwargs and cbook._str_lower_equal(ec, "none"): + kwargs['antialiased'] = False + + kwargs.setdefault('snap', False) + + if np.ma.isMaskedArray(X) or np.ma.isMaskedArray(Y): + stack = np.ma.stack + X = np.ma.asarray(X) + Y = np.ma.asarray(Y) + # For bounds collections later + x = X.compressed() + y = Y.compressed() + else: + stack = np.stack + x = X + y = Y + coords = stack([X, Y], axis=-1) + + collection = mcoll.PolyQuadMesh( + coords, array=C, cmap=cmap, norm=norm, colorizer=colorizer, + alpha=alpha, **kwargs) + collection._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + collection._scale_norm(norm, vmin, vmax) + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + pts = np.vstack([x, y]).T.astype(float) + transformed_pts = trans_to_data.transform(pts) + x = transformed_pts[..., 0] + y = transformed_pts[..., 1] + + self.add_collection(collection, autolim=False) + + minx = np.min(x) + maxx = np.max(x) + miny = np.min(y) + maxy = np.max(y) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.interpd + def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, colorizer=None, shading=None, antialiased=False, + **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + pcolormesh([X, Y,] C, /, **kwargs) + + *X* and *Y* can be used to specify the corners of the quadrilaterals. + + The arguments *X*, *Y*, *C* are positional-only. + + .. hint:: + + `~.Axes.pcolormesh` is similar to `~.Axes.pcolor`. It is much faster + and preferred in most cases. For a detailed discussion on the + differences see :ref:`Differences between pcolor() and pcolormesh() + `. + + Parameters + ---------- + C : array-like + The mesh data. Supported array shapes are: + + - (M, N) or M*N: a mesh with scalar data. The values are mapped to + colors using normalization and a colormap. See parameters *norm*, + *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the mesh data. + + X, Y : array-like, optional + The coordinates of the corners of quadrilaterals of a pcolormesh:: + + (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) + ●╶───╴● + │ │ + ●╶───╴● + (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1]) + + Note that the column index corresponds to the x-coordinate, and + the row index corresponds to y. For details, see the + :ref:`Notes ` section below. + + If ``shading='flat'`` the dimensions of *X* and *Y* should be one + greater than those of *C*, and the quadrilateral is colored due + to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal + dimensions, a warning will be raised and the last row and column + of *C* will be ignored. + + If ``shading='nearest'`` or ``'gouraud'``, the dimensions of *X* + and *Y* should be the same as those of *C* (if not, a ValueError + will be raised). For ``'nearest'`` the color ``C[i, j]`` is + centered on ``(X[i, j], Y[i, j])``. For ``'gouraud'``, a smooth + interpolation is carried out between the quadrilateral corners. + + If *X* and/or *Y* are 1-D arrays or column vectors they will be + expanded as needed into the appropriate 2D arrays, making a + rectangular grid. + + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + edgecolors : {'none', None, 'face', color, color sequence}, optional + The color of the edges. Defaults to 'none'. Possible values: + + - 'none' or '': No edge. + - *None*: :rc:`patch.edgecolor` will be used. Note that currently + :rc:`patch.force_edgecolor` has to be True for this to work. + - 'face': Use the adjacent face color. + - A color or sequence of colors will set the edge color. + + The singular form *edgecolor* works as an alias. + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + shading : {'flat', 'nearest', 'gouraud', 'auto'}, optional + The fill style for the quadrilateral; defaults to + :rc:`pcolor.shading`. Possible values: + + - 'flat': A solid color is used for each quad. The color of the + quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by + ``C[i, j]``. The dimensions of *X* and *Y* should be + one greater than those of *C*; if they are the same as *C*, + then a deprecation warning is raised, and the last row + and column of *C* are dropped. + - 'nearest': Each grid point will have a color centered on it, + extending halfway between the adjacent grid centers. The + dimensions of *X* and *Y* must be the same as *C*. + - 'gouraud': Each quad will be Gouraud shaded: The color of the + corners (i', j') are given by ``C[i', j']``. The color values of + the area in between is interpolated from the corner values. + The dimensions of *X* and *Y* must be the same as *C*. When + Gouraud shading is used, *edgecolors* is ignored. + - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one + larger than *C*. Choose 'nearest' if dimensions are the same. + + See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids` + for more description. + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + rasterized : bool, optional + Rasterize the pcolormesh when drawing vector graphics. This can + speed up rendering and produce smaller files for large data sets. + See also :doc:`/gallery/misc/rasterization_demo`. + + Returns + ------- + `matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additionally, the following arguments are allowed. They are passed + along to the `~matplotlib.collections.QuadMesh` constructor: + + %(QuadMesh:kwdoc)s + + See Also + -------- + pcolor : An alternative implementation with slightly different + features. For a detailed discussion on the differences see + :ref:`Differences between pcolor() and pcolormesh() + `. + imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a + faster alternative. + + Notes + ----- + **Masked arrays** + + *C* may be a masked array. If ``C[i, j]`` is masked, the corresponding + quadrilateral will be transparent. Masking of *X* and *Y* is not + supported. Use `~.Axes.pcolor` if you need this functionality. + + .. _axes-pcolormesh-grid-orientation: + + **Grid orientation** + + The grid orientation follows the standard matrix convention: An array + *C* with shape (nrows, ncolumns) is plotted with the column number as + *X* and the row number as *Y*. + + .. _differences-pcolor-pcolormesh: + + **Differences between pcolor() and pcolormesh()** + + Both methods are used to create a pseudocolor plot of a 2D array + using quadrilaterals. + + The main difference lies in the created object and internal data + handling: + While `~.Axes.pcolor` returns a `.PolyQuadMesh`, `~.Axes.pcolormesh` + returns a `.QuadMesh`. The latter is more specialized for the given + purpose and thus is faster. It should almost always be preferred. + + There is also a slight difference in the handling of masked arrays. + Both `~.Axes.pcolor` and `~.Axes.pcolormesh` support masked arrays + for *C*. However, only `~.Axes.pcolor` supports masked arrays for *X* + and *Y*. The reason lies in the internal handling of the masked values. + `~.Axes.pcolor` leaves out the respective polygons from the + PolyQuadMesh. `~.Axes.pcolormesh` sets the facecolor of the masked + elements to transparent. You can see the difference when using + edgecolors. While all edges are drawn irrespective of masking in a + QuadMesh, the edge between two adjacent masked quadrilaterals in + `~.Axes.pcolor` is not drawn as the corresponding polygons do not + exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual + polygon, it also supports applying hatches and linestyles to the collection. + + Another difference is the support of Gouraud shading in + `~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`. + + """ + if shading is None: + shading = mpl.rcParams['pcolor.shading'] + shading = shading.lower() + kwargs.setdefault('edgecolors', 'none') + + X, Y, C, shading = self._pcolorargs('pcolormesh', *args, + shading=shading, kwargs=kwargs) + coords = np.stack([X, Y], axis=-1) + + kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap']) + + collection = mcoll.QuadMesh( + coords, antialiased=antialiased, shading=shading, + array=C, cmap=cmap, norm=norm, colorizer=colorizer, alpha=alpha, **kwargs) + collection._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax) + collection._scale_norm(norm, vmin, vmax) + + coords = coords.reshape(-1, 2) # flatten the grid structure; keep x, y + + # Transform from native to data coordinates? + t = collection._transform + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): + t = t._as_mpl_transform(self.axes) + + if t and any(t.contains_branch_seperately(self.transData)): + trans_to_data = t - self.transData + coords = trans_to_data.transform(coords) + + self.add_collection(collection, autolim=False) + + minx, miny = np.min(coords, axis=0) + maxx, maxy = np.max(coords, axis=0) + collection.sticky_edges.x[:] = [minx, maxx] + collection.sticky_edges.y[:] = [miny, maxy] + corners = (minx, miny), (maxx, maxy) + self.update_datalim(corners) + self._request_autoscale_view() + return collection + + @_preprocess_data() + @_docstring.interpd + def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None, + vmax=None, colorizer=None, **kwargs): + """ + Create a pseudocolor plot with a non-regular rectangular grid. + + Call signature:: + + ax.pcolorfast([X, Y], C, /, **kwargs) + + The arguments *X*, *Y*, *C* are positional-only. + + This method is similar to `~.Axes.pcolor` and `~.Axes.pcolormesh`. + It's designed to provide the fastest pcolor-type plotting with the + Agg backend. To achieve this, it uses different algorithms internally + depending on the complexity of the input grid (regular rectangular, + non-regular rectangular or arbitrary quadrilateral). + + .. warning:: + + This method is experimental. Compared to `~.Axes.pcolor` or + `~.Axes.pcolormesh` it has some limitations: + + - It supports only flat shading (no outlines) + - It lacks support for log scaling of the axes. + - It does not have a pyplot wrapper. + + Parameters + ---------- + C : array-like + The image data. Supported array shapes are: + + - (M, N): an image with scalar data. Color-mapping is controlled + by *cmap*, *norm*, *vmin*, and *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + The first two dimensions (M, N) define the rows and columns of + the image. + + This parameter can only be passed positionally. + + X, Y : tuple or array-like, default: ``(0, N)``, ``(0, M)`` + *X* and *Y* are used to specify the coordinates of the + quadrilaterals. There are different ways to do this: + + - Use tuples ``X=(xmin, xmax)`` and ``Y=(ymin, ymax)`` to define + a *uniform rectangular grid*. + + The tuples define the outer edges of the grid. All individual + quadrilaterals will be of the same size. This is the fastest + version. + + - Use 1D arrays *X*, *Y* to specify a *non-uniform rectangular + grid*. + + In this case *X* and *Y* have to be monotonic 1D arrays of length + *N+1* and *M+1*, specifying the x and y boundaries of the cells. + + The speed is intermediate. Note: The grid is checked, and if + found to be uniform the fast version is used. + + - Use 2D arrays *X*, *Y* if you need an *arbitrary quadrilateral + grid* (i.e. if the quadrilaterals are not rectangular). + + In this case *X* and *Y* are 2D arrays with shape (M + 1, N + 1), + specifying the x and y coordinates of the corners of the colored + quadrilaterals. + + This is the most general, but the slowest to render. It may + produce faster and more compact output using ps, pdf, and + svg backends, however. + + These arguments can only be passed positionally. + + %(cmap_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(norm_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(vmin_vmax_doc)s + + This parameter is ignored if *C* is RGB(A). + + %(colorizer_doc)s + + This parameter is ignored if *C* is RGB(A). + + alpha : float, default: None + The alpha blending value, between 0 (transparent) and 1 (opaque). + + snap : bool, default: False + Whether to snap the mesh to pixel boundaries. + + Returns + ------- + `.AxesImage` or `.PcolorImage` or `.QuadMesh` + The return type depends on the type of grid: + + - `.AxesImage` for a regular rectangular grid. + - `.PcolorImage` for a non-regular rectangular grid. + - `.QuadMesh` for a non-rectangular grid. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Supported additional parameters depend on the type of grid. + See return types of *image* for further description. + """ + + C = args[-1] + nr, nc = np.shape(C)[:2] + if len(args) == 1: + style = "image" + x = [0, nc] + y = [0, nr] + elif len(args) == 3: + x, y = args[:2] + x = np.asarray(x) + y = np.asarray(y) + if x.ndim == 1 and y.ndim == 1: + if x.size == 2 and y.size == 2: + style = "image" + else: + if x.size != nc + 1: + raise ValueError( + f"Length of X ({x.size}) must be one larger than the " + f"number of columns in C ({nc})") + if y.size != nr + 1: + raise ValueError( + f"Length of Y ({y.size}) must be one larger than the " + f"number of rows in C ({nr})" + ) + dx = np.diff(x) + dy = np.diff(y) + if (np.ptp(dx) < 0.01 * abs(dx.mean()) and + np.ptp(dy) < 0.01 * abs(dy.mean())): + style = "image" + else: + style = "pcolorimage" + elif x.ndim == 2 and y.ndim == 2: + style = "quadmesh" + else: + raise TypeError( + f"When 3 positional parameters are passed to pcolorfast, the first " + f"two (X and Y) must be both 1D or both 2D; the given X was " + f"{x.ndim}D and the given Y was {y.ndim}D") + else: + raise _api.nargs_error('pcolorfast', '1 or 3', len(args)) + + mcolorizer.ColorizingArtist._check_exclusionary_keywords(colorizer, vmin=vmin, + vmax=vmax) + if style == "quadmesh": + # data point in each cell is value at lower left corner + coords = np.stack([x, y], axis=-1) + if np.ndim(C) not in {2, 3}: + raise ValueError("C must be 2D or 3D") + collection = mcoll.QuadMesh( + coords, array=C, + alpha=alpha, cmap=cmap, norm=norm, colorizer=colorizer, + antialiased=False, edgecolors="none") + self.add_collection(collection, autolim=False) + xl, xr, yb, yt = x.min(), x.max(), y.min(), y.max() + ret = collection + + else: # It's one of the two image styles. + extent = xl, xr, yb, yt = x[0], x[-1], y[0], y[-1] + if style == "image": + im = mimage.AxesImage( + self, cmap=cmap, norm=norm, colorizer=colorizer, + data=C, alpha=alpha, extent=extent, + interpolation='nearest', origin='lower', + **kwargs) + elif style == "pcolorimage": + im = mimage.PcolorImage( + self, x, y, C, + cmap=cmap, norm=norm, colorizer=colorizer, alpha=alpha, + extent=extent, **kwargs) + self.add_image(im) + ret = im + + if np.ndim(C) == 2: # C.ndim == 3 is RGB(A) so doesn't need scaling. + ret._scale_norm(norm, vmin, vmax) + + if ret.get_clip_path() is None: + # image does not already have clipping set, clip to Axes patch + ret.set_clip_path(self.patch) + + ret.sticky_edges.x[:] = [xl, xr] + ret.sticky_edges.y[:] = [yb, yt] + self.update_datalim(np.array([[xl, yb], [xr, yt]])) + self._request_autoscale_view(tight=True) + return ret + + @_preprocess_data() + @_docstring.interpd + def contour(self, *args, **kwargs): + """ + Plot contour lines. + + Call signature:: + + contour([X, Y,] Z, /, [levels], **kwargs) + + The arguments *X*, *Y*, *Z* are positional-only. + %(contour_doc)s + """ + kwargs['filled'] = False + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + @_preprocess_data() + @_docstring.interpd + def contourf(self, *args, **kwargs): + """ + Plot filled contours. + + Call signature:: + + contourf([X, Y,] Z, /, [levels], **kwargs) + + The arguments *X*, *Y*, *Z* are positional-only. + %(contour_doc)s + """ + kwargs['filled'] = True + contours = mcontour.QuadContourSet(self, *args, **kwargs) + self._request_autoscale_view() + return contours + + def clabel(self, CS, levels=None, **kwargs): + """ + Label a contour plot. + + Adds labels to line contours in given `.ContourSet`. + + Parameters + ---------- + CS : `.ContourSet` instance + Line contours to label. + + levels : array-like, optional + A list of level values, that should be labeled. The list must be + a subset of ``CS.levels``. If not given, all levels are labeled. + + **kwargs + All other parameters are documented in `~.ContourLabeler.clabel`. + """ + return CS.clabel(levels, **kwargs) + + #### Data analysis + + @_api.make_keyword_only("3.10", "range") + @_preprocess_data(replace_names=["x", 'weights'], label_namer="x") + def hist(self, x, bins=None, range=None, density=False, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, + color=None, label=None, stacked=False, **kwargs): + """ + Compute and plot a histogram. + + This method uses `numpy.histogram` to bin the data in *x* and count the + number of values in each bin, then draws the distribution either as a + `.BarContainer` or `.Polygon`. The *bins*, *range*, *density*, and + *weights* parameters are forwarded to `numpy.histogram`. + + If the data has already been binned and counted, use `~.bar` or + `~.stairs` to plot the distribution:: + + counts, bins = np.histogram(x) + plt.stairs(counts, bins) + + Alternatively, plot pre-computed bins and counts using ``hist()`` by + treating each bin as a single point with a weight equal to its count:: + + plt.hist(bins[:-1], bins, weights=counts) + + The data input *x* can be a singular array, a list of datasets of + potentially different lengths ([*x0*, *x1*, ...]), or a 2D ndarray in + which each column is a dataset. Note that the ndarray form is + transposed relative to the list form. If the input is an array, then + the return value is a tuple (*n*, *bins*, *patches*); if the input is a + sequence of arrays, then the return value is a tuple + ([*n0*, *n1*, ...], *bins*, [*patches0*, *patches1*, ...]). + + Masked arrays are not supported. + + Parameters + ---------- + x : (n,) array or sequence of (n,) arrays + Input values, this takes either a single array or a sequence of + arrays which are not required to be of the same length. + + bins : int or sequence or str, default: :rc:`hist.bins` + If *bins* is an integer, it defines the number of equal-width bins + in the range. + + If *bins* is a sequence, it defines the bin edges, including the + left edge of the first bin and the right edge of the last bin; + in this case, bins may be unequally spaced. All but the last + (righthand-most) bin is half-open. In other words, if *bins* is:: + + [1, 2, 3, 4] + + then the first bin is ``[1, 2)`` (including 1, but excluding 2) and + the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which + *includes* 4. + + If *bins* is a string, it is one of the binning strategies + supported by `numpy.histogram_bin_edges`: 'auto', 'fd', 'doane', + 'scott', 'stone', 'rice', 'sturges', or 'sqrt'. + + range : tuple or None, default: None + The lower and upper range of the bins. Lower and upper outliers + are ignored. If not provided, *range* is ``(x.min(), x.max())``. + Range has no effect if *bins* is a sequence. + + If *bins* is a sequence or *range* is specified, autoscaling + is based on the specified bin range instead of the + range of x. + + density : bool, default: False + If ``True``, draw and return a probability density: each bin + will display the bin's raw count divided by the total number of + counts *and the bin width* + (``density = counts / (sum(counts) * np.diff(bins))``), + so that the area under the histogram integrates to 1 + (``np.sum(density * np.diff(bins)) == 1``). + + If *stacked* is also ``True``, the sum of the histograms is + normalized to 1. + + weights : (n,) array-like or None, default: None + An array of weights, of the same shape as *x*. Each value in + *x* only contributes its associated weight towards the bin count + (instead of 1). If *density* is ``True``, the weights are + normalized, so that the integral of the density over the range + remains 1. + + cumulative : bool or -1, default: False + If ``True``, then a histogram is computed where each bin gives the + counts in that bin plus all bins for smaller values. The last bin + gives the total number of datapoints. + + If *density* is also ``True`` then the histogram is normalized such + that the last bin equals 1. + + If *cumulative* is a number less than 0 (e.g., -1), the direction + of accumulation is reversed. In this case, if *density* is also + ``True``, then the histogram is normalized such that the first bin + equals 1. + + bottom : array-like or float, default: 0 + Location of the bottom of each bin, i.e. bins are drawn from + ``bottom`` to ``bottom + hist(x, bins)`` If a scalar, the bottom + of each bin is shifted by the same amount. If an array, each bin + is shifted independently and the length of bottom must match the + number of bins. If None, defaults to 0. + + histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar' + The type of histogram to draw. + + - 'bar' is a traditional bar-type histogram. If multiple data + are given the bars are arranged side by side. + - 'barstacked' is a bar-type histogram where multiple + data are stacked on top of each other. + - 'step' generates a lineplot that is by default unfilled. + - 'stepfilled' generates a lineplot that is by default filled. + + align : {'left', 'mid', 'right'}, default: 'mid' + The horizontal alignment of the histogram bars. + + - 'left': bars are centered on the left bin edges. + - 'mid': bars are centered between the bin edges. + - 'right': bars are centered on the right bin edges. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', `~.Axes.barh` will be used for bar-type histograms + and the *bottom* kwarg will be the left edges. + + rwidth : float or None, default: None + The relative width of the bars as a fraction of the bin width. If + ``None``, automatically compute the width. + + Ignored if *histtype* is 'step' or 'stepfilled'. + + log : bool, default: False + If ``True``, the histogram axis will be set to a log scale. + + color : :mpltype:`color` or list of :mpltype:`color` or None, default: None + Color or sequence of colors, one per dataset. Default (``None``) + uses the standard line color sequence. + + label : str or list of str, optional + String, or sequence of strings to match multiple datasets. Bar + charts yield multiple patches per dataset, but only the first gets + the label, so that `~.Axes.legend` will work as expected. + + stacked : bool, default: False + If ``True``, multiple data are stacked on top of each other If + ``False`` multiple data are arranged side by side if histtype is + 'bar' or on top of each other if histtype is 'step' + + Returns + ------- + n : array or list of arrays + The values of the histogram bins. See *density* and *weights* for a + description of the possible semantics. If input *x* is an array, + then this is an array of length *nbins*. If input is a sequence of + arrays ``[data1, data2, ...]``, then this is a list of arrays with + the values of the histograms for each of the arrays in the same + order. The dtype of the array *n* (or of its element arrays) will + always be float even if no weighting or normalization is used. + + bins : array + The edges of the bins. Length nbins + 1 (nbins left edges and right + edge of last bin). Always a single array even when multiple data + sets are passed in. + + patches : `.BarContainer` or list of a single `.Polygon` or list of \ +such objects + Container of individual artists used to create the histogram + or list of such containers if there are multiple input datasets. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.Patch` properties. The following properties + additionally accept a sequence of values corresponding to the + datasets in *x*: + *edgecolor*, *facecolor*, *linewidth*, *linestyle*, *hatch*. + + .. versionadded:: 3.10 + Allowing sequences of values in above listed Patch properties. + + See Also + -------- + hist2d : 2D histogram with rectangular bins + hexbin : 2D histogram with hexagonal bins + stairs : Plot a pre-computed histogram + bar : Plot a pre-computed histogram + + Notes + ----- + For large numbers of bins (>1000), plotting can be significantly + accelerated by using `~.Axes.stairs` to plot a pre-computed histogram + (``plt.stairs(*np.histogram(data))``), or by setting *histtype* to + 'step' or 'stepfilled' rather than 'bar' or 'barstacked'. + """ + # Avoid shadowing the builtin. + bin_range = range + from builtins import range + + kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) + + if np.isscalar(x): + x = [x] + + if bins is None: + bins = mpl.rcParams['hist.bins'] + + # Validate string inputs here to avoid cluttering subsequent code. + _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'], + histtype=histtype) + _api.check_in_list(['left', 'mid', 'right'], align=align) + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + if histtype == 'barstacked' and not stacked: + stacked = True + + # Massage 'x' for processing. + x = cbook._reshape_2D(x, 'x') + nx = len(x) # number of datasets + + # Process unit information. _process_unit_info sets the unit and + # converts the first dataset; then we convert each following dataset + # one at a time. + if orientation == "vertical": + convert_units = self.convert_xunits + x = [*self._process_unit_info([("x", x[0])], kwargs), + *map(convert_units, x[1:])] + else: # horizontal + convert_units = self.convert_yunits + x = [*self._process_unit_info([("y", x[0])], kwargs), + *map(convert_units, x[1:])] + + if bin_range is not None: + bin_range = convert_units(bin_range) + + if not cbook.is_scalar_or_string(bins): + bins = convert_units(bins) + + # We need to do to 'weights' what was done to 'x' + if weights is not None: + w = cbook._reshape_2D(weights, 'weights') + else: + w = [None] * nx + + if len(w) != nx: + raise ValueError('weights should have the same shape as x') + + input_empty = True + for xi, wi in zip(x, w): + len_xi = len(xi) + if wi is not None and len(wi) != len_xi: + raise ValueError('weights should have the same shape as x') + if len_xi: + input_empty = False + + if color is None: + colors = [self._get_lines.get_next_color() for i in range(nx)] + else: + colors = mcolors.to_rgba_array(color) + if len(colors) != nx: + raise ValueError(f"The 'color' keyword argument must have one " + f"color per dataset, but {nx} datasets and " + f"{len(colors)} colors were provided") + + hist_kwargs = dict() + + # if the bin_range is not given, compute without nan numpy + # does not do this for us when guessing the range (but will + # happily ignore nans when computing the histogram). + if bin_range is None: + xmin = np.inf + xmax = -np.inf + for xi in x: + if len(xi): + # python's min/max ignore nan, + # np.minnan returns nan for all nan input + xmin = min(xmin, np.nanmin(xi)) + xmax = max(xmax, np.nanmax(xi)) + if xmin <= xmax: # Only happens if we have seen a finite value. + bin_range = (xmin, xmax) + + # If bins are not specified either explicitly or via range, + # we need to figure out the range required for all datasets, + # and supply that to np.histogram. + if not input_empty and len(x) > 1: + if weights is not None: + _w = np.concatenate(w) + else: + _w = None + bins = np.histogram_bin_edges( + np.concatenate(x), bins, bin_range, _w) + else: + hist_kwargs['range'] = bin_range + + density = bool(density) + if density and not stacked: + hist_kwargs['density'] = density + + # List to store all the top coordinates of the histograms + tops = [] # Will have shape (n_datasets, n_bins). + # Loop through datasets + for i in range(nx): + # this will automatically overwrite bins, + # so that each histogram uses the same bins + m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) + tops.append(m) + tops = np.array(tops, float) # causes problems later if it's an int + bins = np.array(bins, float) # causes problems if float16 + if stacked: + tops = tops.cumsum(axis=0) + # If a stacked density plot, normalize so the area of all the + # stacked histograms together is 1 + if density: + tops = (tops / np.diff(bins)) / tops[-1].sum() + if cumulative: + slc = slice(None) + if isinstance(cumulative, Number) and cumulative < 0: + slc = slice(None, None, -1) + if density: + tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc] + else: + tops = tops[:, slc].cumsum(axis=1)[:, slc] + + patches = [] + + if histtype.startswith('bar'): + + totwidth = np.diff(bins) + + if rwidth is not None: + dr = np.clip(rwidth, 0, 1) + elif (len(tops) > 1 and + ((not stacked) or mpl.rcParams['_internal.classic_mode'])): + dr = 0.8 + else: + dr = 1.0 + + if histtype == 'bar' and not stacked: + width = dr * totwidth / nx + dw = width + boffset = -0.5 * dr * totwidth * (1 - 1 / nx) + elif histtype == 'barstacked' or stacked: + width = dr * totwidth + boffset, dw = 0.0, 0.0 + + if align == 'mid': + boffset += 0.5 * totwidth + elif align == 'right': + boffset += totwidth + + if orientation == 'horizontal': + _barfunc = self.barh + bottom_kwarg = 'left' + else: # orientation == 'vertical' + _barfunc = self.bar + bottom_kwarg = 'bottom' + + for top, color in zip(tops, colors): + if bottom is None: + bottom = np.zeros(len(top)) + if stacked: + height = top - bottom + else: + height = top + bars = _barfunc(bins[:-1]+boffset, height, width, + align='center', log=log, + color=color, **{bottom_kwarg: bottom}) + patches.append(bars) + if stacked: + bottom = top + boffset += dw + # Remove stickies from all bars but the lowest ones, as otherwise + # margin expansion would be unable to cross the stickies in the + # middle of the bars. + for bars in patches[1:]: + for patch in bars: + patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = [] + + elif histtype.startswith('step'): + # these define the perimeter of the polygon + x = np.zeros(4 * len(bins) - 3) + y = np.zeros(4 * len(bins) - 3) + + x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1] + x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1] + + if bottom is None: + bottom = 0 + + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + + if log: + if orientation == 'horizontal': + self.set_xscale('log', nonpositive='clip') + else: # orientation == 'vertical' + self.set_yscale('log', nonpositive='clip') + + if align == 'left': + x -= 0.5*(bins[1]-bins[0]) + elif align == 'right': + x += 0.5*(bins[1]-bins[0]) + + # If fill kwarg is set, it will be passed to the patch collection, + # overriding this + fill = (histtype == 'stepfilled') + + xvals, yvals = [], [] + for top in tops: + if stacked: + # top of the previous polygon becomes the bottom + y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1] + # set the top of this polygon + y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = top + bottom + + # The starting point of the polygon has not yet been + # updated. So far only the endpoint was adjusted. This + # assignment closes the polygon. The redundant endpoint is + # later discarded (for step and stepfilled). + y[0] = y[-1] + + if orientation == 'horizontal': + xvals.append(y.copy()) + yvals.append(x.copy()) + else: + xvals.append(x.copy()) + yvals.append(y.copy()) + + # stepfill is closed, step is not + split = -1 if fill else 2 * len(bins) + # add patches in reverse order so that when stacking, + # items lower in the stack are plotted on top of + # items higher in the stack + for x, y, color in reversed(list(zip(xvals, yvals, colors))): + patches.append(self.fill( + x[:split], y[:split], + closed=True if fill else None, + facecolor=color, + edgecolor=None if fill else color, + fill=fill if fill else None, + zorder=None if fill else mlines.Line2D.zorder)) + for patch_list in patches: + for patch in patch_list: + if orientation == 'vertical': + patch.sticky_edges.y.append(0) + elif orientation == 'horizontal': + patch.sticky_edges.x.append(0) + + # we return patches, so put it back in the expected order + patches.reverse() + + # If None, make all labels None (via zip_longest below); otherwise, + # cast each element to str, but keep a single str as it. + labels = [] if label is None else np.atleast_1d(np.asarray(label, str)) + + if histtype == "step": + ec = kwargs.get('edgecolor', colors) + else: + ec = kwargs.get('edgecolor', None) + if ec is None or cbook._str_lower_equal(ec, 'none'): + edgecolors = itertools.repeat(ec) + else: + edgecolors = itertools.cycle(mcolors.to_rgba_array(ec)) + + fc = kwargs.get('facecolor', colors) + if cbook._str_lower_equal(fc, 'none'): + facecolors = itertools.repeat(fc) + else: + facecolors = itertools.cycle(mcolors.to_rgba_array(fc)) + + hatches = itertools.cycle(np.atleast_1d(kwargs.get('hatch', None))) + linewidths = itertools.cycle(np.atleast_1d(kwargs.get('linewidth', None))) + if 'linestyle' in kwargs: + linestyles = itertools.cycle(mlines._get_dash_patterns(kwargs['linestyle'])) + else: + linestyles = itertools.repeat(None) + + for patch, lbl in itertools.zip_longest(patches, labels): + if not patch: + continue + p = patch[0] + kwargs.update({ + 'hatch': next(hatches), + 'linewidth': next(linewidths), + 'linestyle': next(linestyles), + 'edgecolor': next(edgecolors), + 'facecolor': next(facecolors), + }) + p._internal_update(kwargs) + if lbl is not None: + p.set_label(lbl) + for p in patch[1:]: + p._internal_update(kwargs) + p.set_label('_nolegend_') + + if nx == 1: + return tops[0], bins, patches[0] + else: + patch_type = ("BarContainer" if histtype.startswith("bar") + else "list[Polygon]") + return tops, bins, cbook.silent_list(patch_type, patches) + + @_preprocess_data() + def stairs(self, values, edges=None, *, + orientation='vertical', baseline=0, fill=False, **kwargs): + """ + Draw a stepwise constant function as a line or a filled plot. + + *edges* define the x-axis positions of the steps. *values* the function values + between these steps. Depending on *fill*, the function is drawn either as a + continuous line with vertical segments at the edges, or as a filled area. + + Parameters + ---------- + values : array-like + The step heights. + + edges : array-like + The step positions, with ``len(edges) == len(vals) + 1``, + between which the curve takes on vals values. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + The direction of the steps. Vertical means that *values* are along + the y-axis, and edges are along the x-axis. + + baseline : float, array-like or None, default: 0 + The bottom value of the bounding edges or when + ``fill=True``, position of lower edge. If *fill* is + True or an array is passed to *baseline*, a closed + path is drawn. + + If None, then drawn as an unclosed Path. + + fill : bool, default: False + Whether the area under the step curve should be filled. + + Passing both ``fill=True` and ``baseline=None`` will likely result in + undesired filling: the first and last points will be connected + with a straight line and the fill will be between this line and the stairs. + + + Returns + ------- + StepPatch : `~matplotlib.patches.StepPatch` + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + `~matplotlib.patches.StepPatch` properties + + """ + + if 'color' in kwargs: + _color = kwargs.pop('color') + else: + _color = self._get_lines.get_next_color() + if fill: + kwargs.setdefault('linewidth', 0) + kwargs.setdefault('facecolor', _color) + else: + kwargs.setdefault('edgecolor', _color) + + if edges is None: + edges = np.arange(len(values) + 1) + + edges, values, baseline = self._process_unit_info( + [("x", edges), ("y", values), ("y", baseline)], kwargs) + + patch = mpatches.StepPatch(values, + edges, + baseline=baseline, + orientation=orientation, + fill=fill, + **kwargs) + self.add_patch(patch) + if baseline is None and fill: + _api.warn_external( + f"Both {baseline=} and {fill=} have been passed. " + "baseline=None is only intended for unfilled stair plots. " + "Because baseline is None, the Path used to draw the stairs will " + "not be closed, thus because fill is True the polygon will be closed " + "by drawing an (unstroked) edge from the first to last point. It is " + "very likely that the resulting fill patterns is not the desired " + "result." + ) + + if baseline is not None: + if orientation == 'vertical': + patch.sticky_edges.y.append(np.min(baseline)) + self.update_datalim([(edges[0], np.min(baseline))]) + else: + patch.sticky_edges.x.append(np.min(baseline)) + self.update_datalim([(np.min(baseline), edges[0])]) + self._request_autoscale_view() + return patch + + @_api.make_keyword_only("3.10", "range") + @_preprocess_data(replace_names=["x", "y", "weights"]) + @_docstring.interpd + def hist2d(self, x, y, bins=10, range=None, density=False, weights=None, + cmin=None, cmax=None, **kwargs): + """ + Make a 2D histogram plot. + + Parameters + ---------- + x, y : array-like, shape (n, ) + Input values + + bins : None or int or [int, int] or array-like or [array, array] + + The bin specification: + + - If int, the number of bins for the two dimensions + (``nx = ny = bins``). + - If ``[int, int]``, the number of bins in each dimension + (``nx, ny = bins``). + - If array-like, the bin edges for the two dimensions + (``x_edges = y_edges = bins``). + - If ``[array, array]``, the bin edges in each dimension + (``x_edges, y_edges = bins``). + + The default value is 10. + + range : array-like shape(2, 2), optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the bins parameters): ``[[xmin, + xmax], [ymin, ymax]]``. All values outside of this range will be + considered outliers and not tallied in the histogram. + + density : bool, default: False + Normalize histogram. See the documentation for the *density* + parameter of `~.Axes.hist` for more details. + + weights : array-like, shape (n, ), optional + An array of values w_i weighing each sample (x_i, y_i). + + cmin, cmax : float, default: None + All bins that has count less than *cmin* or more than *cmax* will not be + displayed (set to NaN before passing to `~.Axes.pcolormesh`) and these count + values in the return value count histogram will also be set to nan upon + return. + + Returns + ------- + h : 2D array + The bi-dimensional histogram of samples x and y. Values in x are + histogrammed along the first dimension and values in y are + histogrammed along the second dimension. + xedges : 1D array + The bin edges along the x-axis. + yedges : 1D array + The bin edges along the y-axis. + image : `~.matplotlib.collections.QuadMesh` + + Other Parameters + ---------------- + %(cmap_doc)s + + %(norm_doc)s + + %(vmin_vmax_doc)s + + %(colorizer_doc)s + + alpha : ``0 <= scalar <= 1`` or ``None``, optional + The alpha blending value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Additional parameters are passed along to the + `~.Axes.pcolormesh` method and `~matplotlib.collections.QuadMesh` + constructor. + + See Also + -------- + hist : 1D histogram plotting + hexbin : 2D histogram with hexagonal bins + + Notes + ----- + - Currently ``hist2d`` calculates its own axis limits, and any limits + previously set are ignored. + - Rendering the histogram with a logarithmic color scale is + accomplished by passing a `.colors.LogNorm` instance to the *norm* + keyword argument. Likewise, power-law normalization (similar + in effect to gamma correction) can be accomplished with + `.colors.PowerNorm`. + """ + + h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range, + density=density, weights=weights) + + if cmin is not None: + h[h < cmin] = None + if cmax is not None: + h[h > cmax] = None + + pc = self.pcolormesh(xedges, yedges, h.T, **kwargs) + self.set_xlim(xedges[0], xedges[-1]) + self.set_ylim(yedges[0], yedges[-1]) + + return h, xedges, yedges, pc + + @_preprocess_data(replace_names=["x", "weights"], label_namer="x") + @_docstring.interpd + def ecdf(self, x, weights=None, *, complementary=False, + orientation="vertical", compress=False, **kwargs): + """ + Compute and plot the empirical cumulative distribution function of *x*. + + .. versionadded:: 3.8 + + Parameters + ---------- + x : 1d array-like + The input data. Infinite entries are kept (and move the relevant + end of the ecdf from 0/1), but NaNs and masked values are errors. + + weights : 1d array-like or None, default: None + The weights of the entries; must have the same shape as *x*. + Weights corresponding to NaN data points are dropped, and then the + remaining weights are normalized to sum to 1. If unset, all + entries have the same weight. + + complementary : bool, default: False + Whether to plot a cumulative distribution function, which increases + from 0 to 1 (the default), or a complementary cumulative + distribution function, which decreases from 1 to 0. + + orientation : {"vertical", "horizontal"}, default: "vertical" + Whether the entries are plotted along the x-axis ("vertical", the + default) or the y-axis ("horizontal"). This parameter takes the + same values as in `~.Axes.hist`. + + compress : bool, default: False + Whether multiple entries with the same values are grouped together + (with a summed weight) before plotting. This is mainly useful if + *x* contains many identical data points, to decrease the rendering + complexity of the plot. If *x* contains no duplicate points, this + has no effect and just uses some time and memory. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + Returns + ------- + `.Line2D` + + Notes + ----- + The ecdf plot can be thought of as a cumulative histogram with one bin + per data entry; i.e. it reports on the entire dataset without any + arbitrary binning. + + If *x* contains NaNs or masked entries, either remove them first from + the array (if they should not taken into account), or replace them by + -inf or +inf (if they should be sorted at the beginning or the end of + the array). + """ + _api.check_in_list(["horizontal", "vertical"], orientation=orientation) + if "drawstyle" in kwargs or "ds" in kwargs: + raise TypeError("Cannot pass 'drawstyle' or 'ds' to ecdf()") + if np.ma.getmask(x).any(): + raise ValueError("ecdf() does not support masked entries") + x = np.asarray(x) + if np.isnan(x).any(): + raise ValueError("ecdf() does not support NaNs") + argsort = np.argsort(x) + x = x[argsort] + if weights is None: + # Ensure that we end at exactly 1, avoiding floating point errors. + cum_weights = (1 + np.arange(len(x))) / len(x) + else: + weights = np.take(weights, argsort) # Reorder weights like we reordered x. + cum_weights = np.cumsum(weights / np.sum(weights)) + if compress: + # Get indices of unique x values. + compress_idxs = [0, *(x[:-1] != x[1:]).nonzero()[0] + 1] + x = x[compress_idxs] + cum_weights = cum_weights[compress_idxs] + if orientation == "vertical": + if not complementary: + line, = self.plot([x[0], *x], [0, *cum_weights], + drawstyle="steps-post", **kwargs) + else: + line, = self.plot([*x, x[-1]], [1, *1 - cum_weights], + drawstyle="steps-pre", **kwargs) + line.sticky_edges.y[:] = [0, 1] + else: # orientation == "horizontal": + if not complementary: + line, = self.plot([0, *cum_weights], [x[0], *x], + drawstyle="steps-pre", **kwargs) + else: + line, = self.plot([1, *1 - cum_weights], [*x, x[-1]], + drawstyle="steps-post", **kwargs) + line.sticky_edges.x[:] = [0, 1] + return line + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the power spectral density. + + The power spectral density :math:`P_{xx}` by Welch's average + periodogram method. The vector *x* is divided into *NFFT* length + segments. Each segment is detrended by function *detrend* and + windowed by function *window*. *noverlap* gives the length of + the overlap between segments. The :math:`|\mathrm{fft}(i)|^2` + of each segment :math:`i` are averaged to compute :math:`P_{xx}`, + with a scaling to correct for power loss due to windowing. + + If len(*x*) < *NFFT*, it will be zero padded to *NFFT*. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxx : 1-D array + The values for the power spectrum :math:`P_{xx}` before scaling + (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxx*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + specgram + Differs in the default overlap; in not returning the mean of the + segment periodograms; in returning the times of the segments; and + in plotting a colormap instead of a line. + magnitude_spectrum + Plots the magnitude spectrum. + csd + Plots the spectral density between two signals. + + Notes + ----- + For plotting, the power is plotted as + :math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + freqs += Fc + + if scale_by_freq in (None, True): + psd_units = 'dB/Hz' + else: + psd_units = 'dB' + + line = self.plot(freqs, 10 * np.log10(pxx), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Power Spectral Density (%s)' % psd_units) + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxx, freqs + else: + return pxx, freqs, line + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x", "y"], label_namer="y") + @_docstring.interpd + def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, pad_to=None, + sides=None, scale_by_freq=None, return_line=None, **kwargs): + r""" + Plot the cross-spectral density. + + The cross spectral density :math:`P_{xy}` by Welch's average + periodogram method. The vectors *x* and *y* are divided into + *NFFT* length segments. Each segment is detrended by function + *detrend* and windowed by function *window*. *noverlap* gives + the length of the overlap between segments. The product of + the direct FFTs of *x* and *y* are averaged over each segment + to compute :math:`P_{xy}`, with a scaling to correct for power + loss due to windowing. + + If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero + padded to *NFFT*. + + Parameters + ---------- + x, y : 1-D arrays or sequences + Arrays or sequences containing the data. + + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between segments. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + return_line : bool, default: False + Whether to include the line object plotted in the returned values. + + Returns + ------- + Pxy : 1-D array + The values for the cross spectrum :math:`P_{xy}` before scaling + (complex valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *Pxy*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + Only returned if *return_line* is True. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd : is equivalent to setting ``y = x``. + + Notes + ----- + For plotting, the power is plotted as + :math:`10 \log_{10}(P_{xy})` for decibels, though :math:`P_{xy}` itself + is returned. + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + if Fc is None: + Fc = 0 + + pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, pad_to=pad_to, + sides=sides, scale_by_freq=scale_by_freq) + # pxy is complex + freqs += Fc + + line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Cross Spectrum Magnitude (dB)') + self.grid(True) + + vmin, vmax = self.get_ybound() + step = max(10 * int(np.log10(vmax - vmin)), 1) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) + self.set_yticks(ticks) + + if return_line is None or not return_line: + return pxy, freqs + else: + return pxy, freqs, line + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, scale=None, + **kwargs): + """ + Plot the magnitude spectrum. + + Compute the magnitude spectrum of *x*. Data is padded to a + length of *pad_to* and the windowing function *window* is applied to + the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale, i.e., the dB amplitude + (20 * log10). 'default' is 'linear'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the magnitude spectrum before scaling (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + psd + Plots the power spectral density. + angle_spectrum + Plots the angles of the corresponding frequencies. + phase_spectrum + Plots the phase (unwrapped angle) of the corresponding frequencies. + specgram + Can plot the magnitude spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + yunits = _api.check_getitem( + {None: 'energy', 'default': 'energy', 'linear': 'energy', + 'dB': 'dB'}, + scale=scale) + if yunits == 'energy': + Z = spec + else: # yunits == 'dB' + Z = 20. * np.log10(spec) + + line, = self.plot(freqs, Z, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Magnitude (%s)' % yunits) + + return spec, freqs, line + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def angle_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the angle spectrum. + + Compute the angle spectrum (wrapped phase spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the angle spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + phase_spectrum + Plots the unwrapped version of this function. + specgram + Can plot the angle spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Angle (radians)') + + return spec, freqs, lines[0] + + @_api.make_keyword_only("3.10", "Fs") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def phase_spectrum(self, x, Fs=None, Fc=None, window=None, + pad_to=None, sides=None, **kwargs): + """ + Plot the phase spectrum. + + Compute the phase spectrum (unwrapped angle spectrum) of *x*. + Data is padded to a length of *pad_to* and the windowing function + *window* is applied to the signal. + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data + + %(Spectral)s + + %(Single_Spectrum)s + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + spectrum : 1-D array + The values for the phase spectrum in radians (real valued). + + freqs : 1-D array + The frequencies corresponding to the elements in *spectrum*. + + line : `~matplotlib.lines.Line2D` + The line created by this function. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + See Also + -------- + magnitude_spectrum + Plots the magnitudes of the corresponding frequencies. + angle_spectrum + Plots the wrapped version of this function. + specgram + Can plot the phase spectrum of segments within the signal in a + colormap. + """ + if Fc is None: + Fc = 0 + + spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window, + pad_to=pad_to, sides=sides) + freqs += Fc + + lines = self.plot(freqs, spec, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Phase (radians)') + + return spec, freqs, lines[0] + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x", "y"]) + @_docstring.interpd + def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, + window=mlab.window_hanning, noverlap=0, pad_to=None, + sides='default', scale_by_freq=None, **kwargs): + r""" + Plot the coherence between *x* and *y*. + + Coherence is the normalized cross spectral density: + + .. math:: + + C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}} + + Parameters + ---------- + %(Spectral)s + + %(PSD)s + + noverlap : int, default: 0 (no overlap) + The number of points of overlap between blocks. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + Returns + ------- + Cxy : 1-D array + The coherence vector. + + freqs : 1-D array + The frequencies for the elements in *Cxy*. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Keyword arguments control the `.Line2D` properties: + + %(Line2D:kwdoc)s + + References + ---------- + Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, + John Wiley & Sons (1986) + """ + cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, + window=window, noverlap=noverlap, + scale_by_freq=scale_by_freq, sides=sides, + pad_to=pad_to) + freqs += Fc + + self.plot(freqs, cxy, **kwargs) + self.set_xlabel('Frequency') + self.set_ylabel('Coherence') + self.grid(True) + + return cxy, freqs + + @_api.make_keyword_only("3.10", "NFFT") + @_preprocess_data(replace_names=["x"]) + @_docstring.interpd + def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, + window=None, noverlap=None, + cmap=None, xextent=None, pad_to=None, sides=None, + scale_by_freq=None, mode=None, scale=None, + vmin=None, vmax=None, **kwargs): + """ + Plot a spectrogram. + + Compute and plot a spectrogram of data in *x*. Data are split into + *NFFT* length segments and the spectrum of each section is + computed. The windowing function *window* is applied to each + segment, and the amount of overlap of each segment is + specified with *noverlap*. The spectrogram is plotted as a colormap + (using imshow). + + Parameters + ---------- + x : 1-D array or sequence + Array or sequence containing the data. + + %(Spectral)s + + %(PSD)s + + mode : {'default', 'psd', 'magnitude', 'angle', 'phase'} + What sort of spectrum to use. Default is 'psd', which takes the + power spectral density. 'magnitude' returns the magnitude + spectrum. 'angle' returns the phase spectrum without unwrapping. + 'phase' returns the phase spectrum with unwrapping. + + noverlap : int, default: 128 + The number of points of overlap between blocks. + + scale : {'default', 'linear', 'dB'} + The scaling of the values in the *spec*. 'linear' is no scaling. + 'dB' returns the values in dB scale. When *mode* is 'psd', + this is dB power (10 * log10). Otherwise, this is dB amplitude + (20 * log10). 'default' is 'dB' if *mode* is 'psd' or + 'magnitude' and 'linear' otherwise. This must be 'linear' + if *mode* is 'angle' or 'phase'. + + Fc : int, default: 0 + The center frequency of *x*, which offsets the x extents of the + plot to reflect the frequency range used when a signal is acquired + and then filtered and downsampled to baseband. + + cmap : `.Colormap`, default: :rc:`image.cmap` + + xextent : *None* or (xmin, xmax) + The image extent along the x-axis. The default sets *xmin* to the + left border of the first bin (*spectrum* column) and *xmax* to the + right border of the last bin. Note that for *noverlap>0* the width + of the bins is smaller than those of the segments. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + vmin, vmax : float, optional + vmin and vmax define the data range that the colormap covers. + By default, the colormap covers the complete value range of the + data. + + **kwargs + Additional keyword arguments are passed on to `~.axes.Axes.imshow` + which makes the specgram image. The origin keyword argument + is not supported. + + Returns + ------- + spectrum : 2D array + Columns are the periodograms of successive segments. + + freqs : 1-D array + The frequencies corresponding to the rows in *spectrum*. + + t : 1-D array + The times corresponding to midpoints of segments (i.e., the columns + in *spectrum*). + + im : `.AxesImage` + The image created by imshow containing the spectrogram. + + See Also + -------- + psd + Differs in the default overlap; in returning the mean of the + segment periodograms; in not returning times; and in generating a + line plot instead of colormap. + magnitude_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'magnitude'. Plots a line instead of a colormap. + angle_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'angle'. Plots a line instead of a colormap. + phase_spectrum + A single spectrum, similar to having a single segment when *mode* + is 'phase'. Plots a line instead of a colormap. + + Notes + ----- + The parameters *detrend* and *scale_by_freq* do only apply when *mode* + is set to 'psd'. + """ + if NFFT is None: + NFFT = 256 # same default as in mlab.specgram() + if Fc is None: + Fc = 0 # same default as in mlab._spectral_helper() + if noverlap is None: + noverlap = 128 # same default as in mlab.specgram() + if Fs is None: + Fs = 2 # same default as in mlab._spectral_helper() + + if mode == 'complex': + raise ValueError('Cannot plot a complex specgram') + + if scale is None or scale == 'default': + if mode in ['angle', 'phase']: + scale = 'linear' + else: + scale = 'dB' + elif mode in ['angle', 'phase'] and scale == 'dB': + raise ValueError('Cannot use dB scale with angle or phase mode') + + spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs, + detrend=detrend, window=window, + noverlap=noverlap, pad_to=pad_to, + sides=sides, + scale_by_freq=scale_by_freq, + mode=mode) + + if scale == 'linear': + Z = spec + elif scale == 'dB': + if mode is None or mode == 'default' or mode == 'psd': + Z = 10. * np.log10(spec) + else: + Z = 20. * np.log10(spec) + else: + raise ValueError(f'Unknown scale {scale!r}') + + Z = np.flipud(Z) + + if xextent is None: + # padding is needed for first and last segment: + pad_xextent = (NFFT-noverlap) / Fs / 2 + xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent + xmin, xmax = xextent + freqs += Fc + extent = xmin, xmax, freqs[0], freqs[-1] + + if 'origin' in kwargs: + raise _api.kwarg_error("specgram", "origin") + + im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax, + origin='upper', **kwargs) + self.axis('auto') + + return spec, freqs, t, im + + @_api.make_keyword_only("3.10", "precision") + @_docstring.interpd + def spy(self, Z, precision=0, marker=None, markersize=None, + aspect='equal', origin="upper", **kwargs): + """ + Plot the sparsity pattern of a 2D array. + + This visualizes the non-zero values of the array. + + Two plotting styles are available: image and marker. Both + are available for full arrays, but only the marker style + works for `scipy.sparse.spmatrix` instances. + + **Image style** + + If *marker* and *markersize* are *None*, `~.Axes.imshow` is used. Any + extra remaining keyword arguments are passed to this method. + + **Marker style** + + If *Z* is a `scipy.sparse.spmatrix` or *marker* or *markersize* are + *None*, a `.Line2D` object will be returned with the value of marker + determining the marker type, and any remaining keyword arguments + passed to `~.Axes.plot`. + + Parameters + ---------- + Z : (M, N) array-like + The array to be plotted. + + precision : float or 'present', default: 0 + If *precision* is 0, any non-zero value will be plotted. Otherwise, + values of :math:`|Z| > precision` will be plotted. + + For `scipy.sparse.spmatrix` instances, you can also + pass 'present'. In this case any value present in the array + will be plotted, even if it is identically zero. + + aspect : {'equal', 'auto', None} or float, default: 'equal' + The aspect ratio of the Axes. This parameter is particularly + relevant for images since it determines whether data pixels are + square. + + This parameter is a shortcut for explicitly calling + `.Axes.set_aspect`. See there for further details. + + - 'equal': Ensures an aspect ratio of 1. Pixels will be square. + - 'auto': The Axes is kept fixed and the aspect is adjusted so + that the data fit in the Axes. In general, this will result in + non-square pixels. + - *None*: Use :rc:`image.aspect`. + + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower left + corner of the Axes. The convention 'upper' is typically used for + matrices and images. + + Returns + ------- + `~matplotlib.image.AxesImage` or `.Line2D` + The return type depends on the plotting style (see above). + + Other Parameters + ---------------- + **kwargs + The supported additional parameters depend on the plotting style. + + For the image style, you can pass the following additional + parameters of `~.Axes.imshow`: + + - *cmap* + - *alpha* + - *url* + - any `.Artist` properties (passed on to the `.AxesImage`) + + For the marker style, you can pass any `.Line2D` property except + for *linestyle*: + + %(Line2D:kwdoc)s + """ + if marker is None and markersize is None and hasattr(Z, 'tocoo'): + marker = 's' + _api.check_in_list(["upper", "lower"], origin=origin) + if marker is None and markersize is None: + Z = np.asarray(Z) + mask = np.abs(Z) > precision + + if 'cmap' not in kwargs: + kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], + name='binary') + if 'interpolation' in kwargs: + raise _api.kwarg_error("spy", "interpolation") + if 'norm' not in kwargs: + kwargs['norm'] = mcolors.NoNorm() + ret = self.imshow(mask, interpolation='nearest', + aspect=aspect, origin=origin, + **kwargs) + else: + if hasattr(Z, 'tocoo'): + c = Z.tocoo() + if precision == 'present': + y = c.row + x = c.col + else: + nonzero = np.abs(c.data) > precision + y = c.row[nonzero] + x = c.col[nonzero] + else: + Z = np.asarray(Z) + nonzero = np.abs(Z) > precision + y, x = np.nonzero(nonzero) + if marker is None: + marker = 's' + if markersize is None: + markersize = 10 + if 'linestyle' in kwargs: + raise _api.kwarg_error("spy", "linestyle") + ret = mlines.Line2D( + x, y, linestyle='None', marker=marker, markersize=markersize, + **kwargs) + self.add_line(ret) + nr, nc = Z.shape + self.set_xlim(-0.5, nc - 0.5) + if origin == "upper": + self.set_ylim(nr - 0.5, -0.5) + else: + self.set_ylim(-0.5, nr - 0.5) + self.set_aspect(aspect) + self.title.set_y(1.05) + if origin == "upper": + self.xaxis.tick_top() + else: # lower + self.xaxis.tick_bottom() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return ret + + def matshow(self, Z, **kwargs): + """ + Plot the values of a 2D matrix or array as color-coded image. + + The matrix will be shown the way it would be printed, with the first + row at the top. Row and column numbering is zero-based. + + Parameters + ---------- + Z : (M, N) array-like + The matrix to be displayed. + + Returns + ------- + `~matplotlib.image.AxesImage` + + Other Parameters + ---------------- + **kwargs : `~matplotlib.axes.Axes.imshow` arguments + + See Also + -------- + imshow : More general function to plot data on a 2D regular raster. + + Notes + ----- + This is just a convenience function wrapping `.imshow` to set useful + defaults for displaying a matrix. In particular: + + - Set ``origin='upper'``. + - Set ``interpolation='nearest'``. + - Set ``aspect='equal'``. + - Ticks are placed to the left and above. + - Ticks are formatted to show integer indices. + + """ + Z = np.asanyarray(Z) + kw = {'origin': 'upper', + 'interpolation': 'nearest', + 'aspect': 'equal', # (already the imshow default) + **kwargs} + im = self.imshow(Z, **kw) + self.title.set_y(1.05) + self.xaxis.tick_top() + self.xaxis.set_ticks_position('both') + self.xaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + self.yaxis.set_major_locator( + mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) + return im + + @_api.make_keyword_only("3.10", "vert") + @_preprocess_data(replace_names=["dataset"]) + def violinplot(self, dataset, positions=None, vert=None, + orientation='vertical', widths=0.5, showmeans=False, + showextrema=True, showmedians=False, quantiles=None, + points=100, bw_method=None, side='both',): + """ + Make a violin plot. + + Make a violin plot for each column of *dataset* or each vector in + sequence *dataset*. Each filled area extends to represent the + entire data range, with optional lines at the mean, the median, + the minimum, the maximum, and user-specified quantiles. + + Parameters + ---------- + dataset : Array or a sequence of vectors. + The input data. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, optional + .. deprecated:: 3.10 + Use *orientation* instead. + + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the violins vertically. + If False, plots the violins horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the violins horizontally. + Otherwise, plots the violins vertically. + + .. versionadded:: 3.10 + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half the available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + quantiles : array-like, default: None + If not None, set a list of floats in interval [0, 1] for each violin, + which stands for the quantiles that will be rendered for that + violin. + + points : int, default: 100 + The number of points to evaluate each of the gaussian kernel density + estimations at. + + bw_method : {'scott', 'silverman'} or float or callable, default: 'scott' + The method used to calculate the estimator bandwidth. If a + float, this will be used directly as `kde.factor`. If a + callable, it should take a `matplotlib.mlab.GaussianKDE` instance as + its only parameter and return a float. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantile values of each of the violin's + distribution. + + See Also + -------- + .Axes.violin : Draw a violin from pre-computed statistics. + boxplot : Draw a box and whisker plot. + """ + + def _kde_method(X, coords): + # Unpack in case of e.g. Pandas or xarray object + X = cbook._unpack_to_numpy(X) + # fallback gracefully if the vector contains only one value + if np.all(X[0] == X): + return (X[0] == coords).astype(float) + kde = mlab.GaussianKDE(X, bw_method) + return kde.evaluate(coords) + + vpstats = cbook.violin_stats(dataset, _kde_method, points=points, + quantiles=quantiles) + return self.violin(vpstats, positions=positions, vert=vert, + orientation=orientation, widths=widths, + showmeans=showmeans, showextrema=showextrema, + showmedians=showmedians, side=side) + + @_api.make_keyword_only("3.10", "vert") + def violin(self, vpstats, positions=None, vert=None, + orientation='vertical', widths=0.5, showmeans=False, + showextrema=True, showmedians=False, side='both'): + """ + Draw a violin plot from pre-computed statistics. + + Draw a violin plot for each column of *vpstats*. Each filled area + extends to represent the entire data range, with optional lines at the + mean, the median, the minimum, the maximum, and the quantiles values. + + Parameters + ---------- + vpstats : list of dicts + A list of dictionaries containing stats for each violin plot. + Required keys are: + + - ``coords``: A list of scalars containing the coordinates that + the violin's kernel density estimate were evaluated at. + + - ``vals``: A list of scalars containing the values of the + kernel density estimate at each of the coordinates given + in *coords*. + + - ``mean``: The mean value for this violin's dataset. + + - ``median``: The median value for this violin's dataset. + + - ``min``: The minimum value for this violin's dataset. + + - ``max``: The maximum value for this violin's dataset. + + Optional keys are: + + - ``quantiles``: A list of scalars containing the quantile values + for this violin's dataset. + + positions : array-like, default: [1, 2, ..., n] + The positions of the violins; i.e. coordinates on the x-axis for + vertical violins (or y-axis for horizontal violins). + + vert : bool, optional + .. deprecated:: 3.10 + Use *orientation* instead. + + If this is given during the deprecation period, it overrides + the *orientation* parameter. + + If True, plots the violins vertically. + If False, plots the violins horizontally. + + orientation : {'vertical', 'horizontal'}, default: 'vertical' + If 'horizontal', plots the violins horizontally. + Otherwise, plots the violins vertically. + + .. versionadded:: 3.10 + + widths : float or array-like, default: 0.5 + The maximum width of each violin in units of the *positions* axis. + The default is 0.5, which is half available space when using default + *positions*. + + showmeans : bool, default: False + Whether to show the mean with a line. + + showextrema : bool, default: True + Whether to show extrema with a line. + + showmedians : bool, default: False + Whether to show the median with a line. + + side : {'both', 'low', 'high'}, default: 'both' + 'both' plots standard violins. 'low'/'high' only + plots the side below/above the positions value. + + Returns + ------- + dict + A dictionary mapping each component of the violinplot to a + list of the corresponding collection instances created. The + dictionary has the following keys: + + - ``bodies``: A list of the `~.collections.PolyCollection` + instances containing the filled area of each violin. + + - ``cmeans``: A `~.collections.LineCollection` instance that marks + the mean values of each of the violin's distribution. + + - ``cmins``: A `~.collections.LineCollection` instance that marks + the bottom of each violin's distribution. + + - ``cmaxes``: A `~.collections.LineCollection` instance that marks + the top of each violin's distribution. + + - ``cbars``: A `~.collections.LineCollection` instance that marks + the centers of each violin's distribution. + + - ``cmedians``: A `~.collections.LineCollection` instance that + marks the median values of each of the violin's distribution. + + - ``cquantiles``: A `~.collections.LineCollection` instance created + to identify the quantiles values of each of the violin's + distribution. + + See Also + -------- + violinplot : + Draw a violin plot from data instead of pre-computed statistics. + """ + + # Statistical quantities to be plotted on the violins + means = [] + mins = [] + maxes = [] + medians = [] + quantiles = [] + + qlens = [] # Number of quantiles in each dataset. + + artists = {} # Collections to be returned + + N = len(vpstats) + datashape_message = ("List of violinplot statistics and `{0}` " + "values must have the same length") + + # vert and orientation parameters are linked until vert's + # deprecation period expires. If both are selected, + # vert takes precedence. + if vert is not None: + _api.warn_deprecated( + "3.11", + name="vert: bool", + alternative="orientation: {'vertical', 'horizontal'}", + pending=True, + ) + orientation = 'vertical' if vert else 'horizontal' + _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) + + # Validate positions + if positions is None: + positions = range(1, N + 1) + elif len(positions) != N: + raise ValueError(datashape_message.format("positions")) + + # Validate widths + if np.isscalar(widths): + widths = [widths] * N + elif len(widths) != N: + raise ValueError(datashape_message.format("widths")) + + # Validate side + _api.check_in_list(["both", "low", "high"], side=side) + + # Calculate ranges for statistics lines (shape (2, N)). + line_ends = [[-0.25 if side in ['both', 'low'] else 0], + [0.25 if side in ['both', 'high'] else 0]] \ + * np.array(widths) + positions + + # Colors. + if mpl.rcParams['_internal.classic_mode']: + fillcolor = 'y' + linecolor = 'r' + else: + fillcolor = linecolor = self._get_lines.get_next_color() + + # Check whether we are rendering vertically or horizontally + if orientation == 'vertical': + fill = self.fill_betweenx + if side in ['low', 'high']: + perp_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.hlines, colors=linecolor) + par_lines = functools.partial(self.vlines, colors=linecolor) + else: + fill = self.fill_between + if side in ['low', 'high']: + perp_lines = functools.partial(self.vlines, colors=linecolor, + capstyle='projecting') + par_lines = functools.partial(self.hlines, colors=linecolor, + capstyle='projecting') + else: + perp_lines = functools.partial(self.vlines, colors=linecolor) + par_lines = functools.partial(self.hlines, colors=linecolor) + + # Render violins + bodies = [] + for stats, pos, width in zip(vpstats, positions, widths): + # The 0.5 factor reflects the fact that we plot from v-p to v+p. + vals = np.array(stats['vals']) + vals = 0.5 * width * vals / vals.max() + bodies += [fill(stats['coords'], + -vals + pos if side in ['both', 'low'] else pos, + vals + pos if side in ['both', 'high'] else pos, + facecolor=fillcolor, alpha=0.3)] + means.append(stats['mean']) + mins.append(stats['min']) + maxes.append(stats['max']) + medians.append(stats['median']) + q = stats.get('quantiles') # a list of floats, or None + if q is None: + q = [] + quantiles.extend(q) + qlens.append(len(q)) + artists['bodies'] = bodies + + if showmeans: # Render means + artists['cmeans'] = perp_lines(means, *line_ends) + if showextrema: # Render extrema + artists['cmaxes'] = perp_lines(maxes, *line_ends) + artists['cmins'] = perp_lines(mins, *line_ends) + artists['cbars'] = par_lines(positions, mins, maxes) + if showmedians: # Render medians + artists['cmedians'] = perp_lines(medians, *line_ends) + if quantiles: # Render quantiles: each width is repeated qlen times. + artists['cquantiles'] = perp_lines( + quantiles, *np.repeat(line_ends, qlens, axis=1)) + + return artists + + # Methods that are entirely implemented in other modules. + + table = _make_axes_method(mtable.table) + + # args can be either Y or y1, y2, ... and all should be replaced + stackplot = _preprocess_data()(_make_axes_method(mstack.stackplot)) + + streamplot = _preprocess_data( + replace_names=["x", "y", "u", "v", "start_points"])( + _make_axes_method(mstream.streamplot)) + + tricontour = _make_axes_method(mtri.tricontour) + tricontourf = _make_axes_method(mtri.tricontourf) + tripcolor = _make_axes_method(mtri.tripcolor) + triplot = _make_axes_method(mtri.triplot) + + def _get_aspect_ratio(self): + """ + Convenience method to calculate the aspect ratio of the Axes in + the display coordinate system. + """ + figure_size = self.get_figure().get_size_inches() + ll, ur = self.get_position() * figure_size + width, height = ur - ll + return height / (width * self.get_data_ratio()) diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_axes.pyi b/python_embeded/Lib/site-packages/matplotlib/axes/_axes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0c4be37b064b2a76ba89d5fd0a3a4c0e1cc91e93 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_axes.pyi @@ -0,0 +1,780 @@ +from matplotlib.axes._base import _AxesBase +from matplotlib.axes._secondary_axes import SecondaryAxis + +from matplotlib.artist import Artist +from matplotlib.backend_bases import RendererBase +from matplotlib.collections import ( + Collection, + FillBetweenPolyCollection, + LineCollection, + PathCollection, + PolyCollection, + EventCollection, + QuadMesh, +) +from matplotlib.colorizer import Colorizer +from matplotlib.colors import Colormap, Normalize +from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer +from matplotlib.contour import ContourSet, QuadContourSet +from matplotlib.image import AxesImage, PcolorImage +from matplotlib.inset import InsetIndicator +from matplotlib.legend import Legend +from matplotlib.legend_handler import HandlerBase +from matplotlib.lines import Line2D, AxLine +from matplotlib.mlab import GaussianKDE +from matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge +from matplotlib.quiver import Quiver, QuiverKey, Barbs +from matplotlib.text import Annotation, Text +from matplotlib.transforms import Transform +from matplotlib.typing import CoordsType +import matplotlib.tri as mtri +import matplotlib.table as mtable +import matplotlib.stackplot as mstack +import matplotlib.streamplot as mstream + +import datetime +import PIL.Image +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, overload +import numpy as np +from numpy.typing import ArrayLike +from matplotlib.typing import ColorType, MarkerType, LineStyleType + +class Axes(_AxesBase): + def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ... + def set_title( + self, + label: str, + fontdict: dict[str, Any] | None = ..., + loc: Literal["left", "center", "right"] | None = ..., + pad: float | None = ..., + *, + y: float | None = ..., + **kwargs + ) -> Text: ... + def get_legend_handles_labels( + self, legend_handler_map: dict[type, HandlerBase] | None = ... + ) -> tuple[list[Artist], list[Any]]: ... + legend_: Legend | None + + @overload + def legend(self) -> Legend: ... + @overload + def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ... + @overload + def legend(self, labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, **kwargs) -> Legend: ... + + def inset_axes( + self, + bounds: tuple[float, float, float, float], + *, + transform: Transform | None = ..., + zorder: float = ..., + **kwargs + ) -> Axes: ... + def indicate_inset( + self, + bounds: tuple[float, float, float, float] | None = ..., + inset_ax: Axes | None = ..., + *, + transform: Transform | None = ..., + facecolor: ColorType = ..., + edgecolor: ColorType = ..., + alpha: float = ..., + zorder: float | None = ..., + **kwargs + ) -> InsetIndicator: ... + def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> InsetIndicator: ... + def secondary_xaxis( + self, + location: Literal["top", "bottom"] | float, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform + | None = ..., + *, + transform: Transform | None = ..., + **kwargs + ) -> SecondaryAxis: ... + def secondary_yaxis( + self, + location: Literal["left", "right"] | float, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform + | None = ..., + *, + transform: Transform | None = ..., + **kwargs + ) -> SecondaryAxis: ... + def text( + self, + x: float, + y: float, + s: str, + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> Text: ... + def annotate( + self, + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = ..., + xycoords: CoordsType = ..., + textcoords: CoordsType | None = ..., + arrowprops: dict[str, Any] | None = ..., + annotation_clip: bool | None = ..., + **kwargs + ) -> Annotation: ... + def axhline( + self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs + ) -> Line2D: ... + def axvline( + self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs + ) -> Line2D: ... + + # TODO: Could separate the xy2 and slope signatures + def axline( + self, + xy1: tuple[float, float], + xy2: tuple[float, float] | None = ..., + *, + slope: float | None = ..., + **kwargs + ) -> AxLine: ... + def axhspan( + self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs + ) -> Rectangle: ... + def axvspan( + self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs + ) -> Rectangle: ... + def hlines( + self, + y: float | ArrayLike, + xmin: float | ArrayLike, + xmax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = ..., + linestyles: LineStyleType = ..., + *, + label: str = ..., + data=..., + **kwargs + ) -> LineCollection: ... + def vlines( + self, + x: float | ArrayLike, + ymin: float | ArrayLike, + ymax: float | ArrayLike, + colors: ColorType | Sequence[ColorType] | None = ..., + linestyles: LineStyleType = ..., + *, + label: str = ..., + data=..., + **kwargs + ) -> LineCollection: ... + def eventplot( + self, + positions: ArrayLike | Sequence[ArrayLike], + *, + orientation: Literal["horizontal", "vertical"] = ..., + lineoffsets: float | Sequence[float] = ..., + linelengths: float | Sequence[float] = ..., + linewidths: float | Sequence[float] | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + alpha: float | Sequence[float] | None = ..., + linestyles: LineStyleType | Sequence[LineStyleType] = ..., + data=..., + **kwargs + ) -> EventCollection: ... + def plot( + self, + *args: float | ArrayLike | str, + scalex: bool = ..., + scaley: bool = ..., + data=..., + **kwargs + ) -> list[Line2D]: ... + def plot_date( + self, + x: ArrayLike, + y: ArrayLike, + fmt: str = ..., + tz: str | datetime.tzinfo | None = ..., + xdate: bool = ..., + ydate: bool = ..., + *, + data=..., + **kwargs + ) -> list[Line2D]: ... + def loglog(self, *args, **kwargs) -> list[Line2D]: ... + def semilogx(self, *args, **kwargs) -> list[Line2D]: ... + def semilogy(self, *args, **kwargs) -> list[Line2D]: ... + def acorr( + self, x: ArrayLike, *, data=..., **kwargs + ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ... + def xcorr( + self, + x: ArrayLike, + y: ArrayLike, + *, + normed: bool = ..., + detrend: Callable[[ArrayLike], ArrayLike] = ..., + usevlines: bool = ..., + maxlags: int = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ... + def step( + self, + x: ArrayLike, + y: ArrayLike, + *args, + where: Literal["pre", "post", "mid"] = ..., + data=..., + **kwargs + ) -> list[Line2D]: ... + def bar( + self, + x: float | ArrayLike, + height: float | ArrayLike, + width: float | ArrayLike = ..., + bottom: float | ArrayLike | None = ..., + *, + align: Literal["center", "edge"] = ..., + data=..., + **kwargs + ) -> BarContainer: ... + def barh( + self, + y: float | ArrayLike, + width: float | ArrayLike, + height: float | ArrayLike = ..., + left: float | ArrayLike | None = ..., + *, + align: Literal["center", "edge"] = ..., + data=..., + **kwargs + ) -> BarContainer: ... + def bar_label( + self, + container: BarContainer, + labels: ArrayLike | None = ..., + *, + fmt: str | Callable[[float], str] = ..., + label_type: Literal["center", "edge"] = ..., + padding: float = ..., + **kwargs + ) -> list[Annotation]: ... + def broken_barh( + self, + xranges: Sequence[tuple[float, float]], + yrange: tuple[float, float], + *, + data=..., + **kwargs + ) -> PolyCollection: ... + def stem( + self, + *args: ArrayLike | str, + linefmt: str | None = ..., + markerfmt: str | None = ..., + basefmt: str | None = ..., + bottom: float = ..., + label: str | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + data=..., + ) -> StemContainer: ... + + # TODO: data kwarg preprocessor? + def pie( + self, + x: ArrayLike, + *, + explode: ArrayLike | None = ..., + labels: Sequence[str] | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + autopct: str | Callable[[float], str] | None = ..., + pctdistance: float = ..., + shadow: bool = ..., + labeldistance: float | None = ..., + startangle: float = ..., + radius: float = ..., + counterclock: bool = ..., + wedgeprops: dict[str, Any] | None = ..., + textprops: dict[str, Any] | None = ..., + center: tuple[float, float] = ..., + frame: bool = ..., + rotatelabels: bool = ..., + normalize: bool = ..., + hatch: str | Sequence[str] | None = ..., + data=..., + ) -> tuple[list[Wedge], list[Text]] | tuple[ + list[Wedge], list[Text], list[Text] + ]: ... + def errorbar( + self, + x: float | ArrayLike, + y: float | ArrayLike, + yerr: float | ArrayLike | None = ..., + xerr: float | ArrayLike | None = ..., + fmt: str = ..., + *, + ecolor: ColorType | None = ..., + elinewidth: float | None = ..., + capsize: float | None = ..., + barsabove: bool = ..., + lolims: bool | ArrayLike = ..., + uplims: bool | ArrayLike = ..., + xlolims: bool | ArrayLike = ..., + xuplims: bool | ArrayLike = ..., + errorevery: int | tuple[int, int] = ..., + capthick: float | None = ..., + data=..., + **kwargs + ) -> ErrorbarContainer: ... + def boxplot( + self, + x: ArrayLike | Sequence[ArrayLike], + *, + notch: bool | None = ..., + sym: str | None = ..., + vert: bool | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + whis: float | tuple[float, float] | None = ..., + positions: ArrayLike | None = ..., + widths: float | ArrayLike | None = ..., + patch_artist: bool | None = ..., + bootstrap: int | None = ..., + usermedians: ArrayLike | None = ..., + conf_intervals: ArrayLike | None = ..., + meanline: bool | None = ..., + showmeans: bool | None = ..., + showcaps: bool | None = ..., + showbox: bool | None = ..., + showfliers: bool | None = ..., + boxprops: dict[str, Any] | None = ..., + tick_labels: Sequence[str] | None = ..., + flierprops: dict[str, Any] | None = ..., + medianprops: dict[str, Any] | None = ..., + meanprops: dict[str, Any] | None = ..., + capprops: dict[str, Any] | None = ..., + whiskerprops: dict[str, Any] | None = ..., + manage_ticks: bool = ..., + autorange: bool = ..., + zorder: float | None = ..., + capwidths: float | ArrayLike | None = ..., + label: Sequence[str] | None = ..., + data=..., + ) -> dict[str, Any]: ... + def bxp( + self, + bxpstats: Sequence[dict[str, Any]], + positions: ArrayLike | None = ..., + *, + widths: float | ArrayLike | None = ..., + vert: bool | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + patch_artist: bool = ..., + shownotches: bool = ..., + showmeans: bool = ..., + showcaps: bool = ..., + showbox: bool = ..., + showfliers: bool = ..., + boxprops: dict[str, Any] | None = ..., + whiskerprops: dict[str, Any] | None = ..., + flierprops: dict[str, Any] | None = ..., + medianprops: dict[str, Any] | None = ..., + capprops: dict[str, Any] | None = ..., + meanprops: dict[str, Any] | None = ..., + meanline: bool = ..., + manage_ticks: bool = ..., + zorder: float | None = ..., + capwidths: float | ArrayLike | None = ..., + label: Sequence[str] | None = ..., + ) -> dict[str, Any]: ... + def scatter( + self, + x: float | ArrayLike, + y: float | ArrayLike, + s: float | ArrayLike | None = ..., + c: ArrayLike | Sequence[ColorType] | ColorType | None = ..., + *, + marker: MarkerType | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + alpha: float | None = ..., + linewidths: float | Sequence[float] | None = ..., + edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ..., + colorizer: Colorizer | None = ..., + plotnonfinite: bool = ..., + data=..., + **kwargs + ) -> PathCollection: ... + def hexbin( + self, + x: ArrayLike, + y: ArrayLike, + C: ArrayLike | None = ..., + *, + gridsize: int | tuple[int, int] = ..., + bins: Literal["log"] | int | Sequence[float] | None = ..., + xscale: Literal["linear", "log"] = ..., + yscale: Literal["linear", "log"] = ..., + extent: tuple[float, float, float, float] | None = ..., + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + alpha: float | None = ..., + linewidths: float | None = ..., + edgecolors: Literal["face", "none"] | ColorType = ..., + reduce_C_function: Callable[[np.ndarray | list[float]], float] = ..., + mincnt: int | None = ..., + marginals: bool = ..., + colorizer: Colorizer | None = ..., + data=..., + **kwargs + ) -> PolyCollection: ... + def arrow( + self, x: float, y: float, dx: float, dy: float, **kwargs + ) -> FancyArrow: ... + def quiverkey( + self, Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs + ) -> QuiverKey: ... + def quiver(self, *args, data=..., **kwargs) -> Quiver: ... + def barbs(self, *args, data=..., **kwargs) -> Barbs: ... + def fill(self, *args, data=..., **kwargs) -> list[Polygon]: ... + def fill_between( + self, + x: ArrayLike, + y1: ArrayLike | float, + y2: ArrayLike | float = ..., + where: Sequence[bool] | None = ..., + interpolate: bool = ..., + step: Literal["pre", "post", "mid"] | None = ..., + *, + data=..., + **kwargs + ) -> FillBetweenPolyCollection: ... + def fill_betweenx( + self, + y: ArrayLike, + x1: ArrayLike | float, + x2: ArrayLike | float = ..., + where: Sequence[bool] | None = ..., + step: Literal["pre", "post", "mid"] | None = ..., + interpolate: bool = ..., + *, + data=..., + **kwargs + ) -> FillBetweenPolyCollection: ... + def imshow( + self, + X: ArrayLike | PIL.Image.Image, + cmap: str | Colormap | None = ..., + norm: str | Normalize | None = ..., + *, + aspect: Literal["equal", "auto"] | float | None = ..., + interpolation: str | None = ..., + alpha: float | ArrayLike | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + colorizer: Colorizer | None = ..., + origin: Literal["upper", "lower"] | None = ..., + extent: tuple[float, float, float, float] | None = ..., + interpolation_stage: Literal["data", "rgba", "auto"] | None = ..., + filternorm: bool = ..., + filterrad: float = ..., + resample: bool | None = ..., + url: str | None = ..., + data=..., + **kwargs + ) -> AxesImage: ... + def pcolor( + self, + *args: ArrayLike, + shading: Literal["flat", "nearest", "auto"] | None = ..., + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + colorizer: Colorizer | None = ..., + data=..., + **kwargs + ) -> Collection: ... + def pcolormesh( + self, + *args: ArrayLike, + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + colorizer: Colorizer | None = ..., + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ..., + antialiased: bool = ..., + data=..., + **kwargs + ) -> QuadMesh: ... + def pcolorfast( + self, + *args: ArrayLike | tuple[float, float], + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + colorizer: Colorizer | None = ..., + data=..., + **kwargs + ) -> AxesImage | PcolorImage | QuadMesh: ... + def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ... + def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ... + def clabel( + self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs + ) -> list[Text]: ... + def hist( + self, + x: ArrayLike | Sequence[ArrayLike], + bins: int | Sequence[float] | str | None = ..., + *, + range: tuple[float, float] | None = ..., + density: bool = ..., + weights: ArrayLike | None = ..., + cumulative: bool | float = ..., + bottom: ArrayLike | float | None = ..., + histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ..., + align: Literal["left", "mid", "right"] = ..., + orientation: Literal["vertical", "horizontal"] = ..., + rwidth: float | None = ..., + log: bool = ..., + color: ColorType | Sequence[ColorType] | None = ..., + label: str | Sequence[str] | None = ..., + stacked: bool = ..., + data=..., + **kwargs + ) -> tuple[ + np.ndarray | list[np.ndarray], + np.ndarray, + BarContainer | Polygon | list[BarContainer | Polygon], + ]: ... + def stairs( + self, + values: ArrayLike, + edges: ArrayLike | None = ..., + *, + orientation: Literal["vertical", "horizontal"] = ..., + baseline: float | ArrayLike | None = ..., + fill: bool = ..., + data=..., + **kwargs + ) -> StepPatch: ... + def hist2d( + self, + x: ArrayLike, + y: ArrayLike, + bins: None + | int + | tuple[int, int] + | ArrayLike + | tuple[ArrayLike, ArrayLike] = ..., + *, + range: ArrayLike | None = ..., + density: bool = ..., + weights: ArrayLike | None = ..., + cmin: float | None = ..., + cmax: float | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ... + def ecdf( + self, + x: ArrayLike, + weights: ArrayLike | None = ..., + *, + complementary: bool=..., + orientation: Literal["vertical", "horizontal"]=..., + compress: bool=..., + data=..., + **kwargs + ) -> Line2D: ... + def psd( + self, + x: ArrayLike, + *, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + return_line: bool | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ... + def csd( + self, + x: ArrayLike, + y: ArrayLike, + *, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + return_line: bool | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ... + def magnitude_spectrum( + self, + x: ArrayLike, + *, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale: Literal["default", "linear", "dB"] | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def angle_spectrum( + self, + x: ArrayLike, + *, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def phase_spectrum( + self, + x: ArrayLike, + *, + Fs: float | None = ..., + Fc: int | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, Line2D]: ... + def cohere( + self, + x: ArrayLike, + y: ArrayLike, + *, + NFFT: int = ..., + Fs: float = ..., + Fc: int = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ..., + noverlap: int = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] = ..., + scale_by_freq: bool | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray]: ... + def specgram( + self, + x: ArrayLike, + *, + NFFT: int | None = ..., + Fs: float | None = ..., + Fc: int | None = ..., + detrend: Literal["none", "mean", "linear"] + | Callable[[ArrayLike], ArrayLike] + | None = ..., + window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ..., + noverlap: int | None = ..., + cmap: str | Colormap | None = ..., + xextent: tuple[float, float] | None = ..., + pad_to: int | None = ..., + sides: Literal["default", "onesided", "twosided"] | None = ..., + scale_by_freq: bool | None = ..., + mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ..., + scale: Literal["default", "linear", "dB"] | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + data=..., + **kwargs + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ... + def spy( + self, + Z: ArrayLike, + *, + precision: float | Literal["present"] = ..., + marker: str | None = ..., + markersize: float | None = ..., + aspect: Literal["equal", "auto"] | float | None = ..., + origin: Literal["upper", "lower"] = ..., + **kwargs + ) -> AxesImage: ... + def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ... + def violinplot( + self, + dataset: ArrayLike | Sequence[ArrayLike], + positions: ArrayLike | None = ..., + *, + vert: bool | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + widths: float | ArrayLike = ..., + showmeans: bool = ..., + showextrema: bool = ..., + showmedians: bool = ..., + quantiles: Sequence[float | Sequence[float]] | None = ..., + points: int = ..., + bw_method: Literal["scott", "silverman"] + | float + | Callable[[GaussianKDE], float] + | None = ..., + side: Literal["both", "low", "high"] = ..., + data=..., + ) -> dict[str, Collection]: ... + def violin( + self, + vpstats: Sequence[dict[str, Any]], + positions: ArrayLike | None = ..., + *, + vert: bool | None = ..., + orientation: Literal["vertical", "horizontal"] = ..., + widths: float | ArrayLike = ..., + showmeans: bool = ..., + showextrema: bool = ..., + showmedians: bool = ..., + side: Literal["both", "low", "high"] = ..., + ) -> dict[str, Collection]: ... + + table = mtable.table + stackplot = mstack.stackplot + streamplot = mstream.streamplot + tricontour = mtri.tricontour + tricontourf = mtri.tricontourf + tripcolor = mtri.tripcolor + triplot = mtri.triplot diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_base.py b/python_embeded/Lib/site-packages/matplotlib/axes/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0078b799b159b5d493c5a189c8f3c0bc7e077367 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_base.py @@ -0,0 +1,4836 @@ +from collections.abc import Iterable, Sequence +from contextlib import ExitStack +import functools +import inspect +import logging +from numbers import Real +from operator import attrgetter +import re +import types + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _docstring, offsetbox +import matplotlib.artist as martist +import matplotlib.axis as maxis +from matplotlib.cbook import _OrderedSet, _check_1d, index_of +import matplotlib.collections as mcoll +import matplotlib.colors as mcolors +import matplotlib.font_manager as font_manager +from matplotlib.gridspec import SubplotSpec +import matplotlib.image as mimage +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +from matplotlib.rcsetup import cycler, validate_axisbelow +import matplotlib.spines as mspines +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms + +_log = logging.getLogger(__name__) + + +class _axis_method_wrapper: + """ + Helper to generate Axes methods wrapping Axis methods. + + After :: + + get_foo = _axis_method_wrapper("xaxis", "get_bar") + + (in the body of a class) ``get_foo`` is a method that forwards it arguments + to the ``get_bar`` method of the ``xaxis`` attribute, and gets its + signature and docstring from ``Axis.get_bar``. + + The docstring of ``get_foo`` is built by replacing "this Axis" by "the + {attr_name}" (i.e., "the xaxis", "the yaxis") in the wrapped method's + dedented docstring; additional replacements can be given in *doc_sub*. + """ + + def __init__(self, attr_name, method_name, *, doc_sub=None): + self.attr_name = attr_name + self.method_name = method_name + # Immediately put the docstring in ``self.__doc__`` so that docstring + # manipulations within the class body work as expected. + doc = inspect.getdoc(getattr(maxis.Axis, method_name)) + self._missing_subs = [] + if doc: + doc_sub = {"this Axis": f"the {self.attr_name}", **(doc_sub or {})} + for k, v in doc_sub.items(): + if k not in doc: # Delay raising error until we know qualname. + self._missing_subs.append(k) + doc = doc.replace(k, v) + self.__doc__ = doc + + def __set_name__(self, owner, name): + # This is called at the end of the class body as + # ``self.__set_name__(cls, name_under_which_self_is_assigned)``; we + # rely on that to give the wrapper the correct __name__/__qualname__. + get_method = attrgetter(f"{self.attr_name}.{self.method_name}") + + def wrapper(self, *args, **kwargs): + return get_method(self)(*args, **kwargs) + + wrapper.__module__ = owner.__module__ + wrapper.__name__ = name + wrapper.__qualname__ = f"{owner.__qualname__}.{name}" + wrapper.__doc__ = self.__doc__ + # Manually copy the signature instead of using functools.wraps because + # displaying the Axis method source when asking for the Axes method + # source would be confusing. + wrapper.__signature__ = inspect.signature( + getattr(maxis.Axis, self.method_name)) + + if self._missing_subs: + raise ValueError( + "The definition of {} expected that the docstring of Axis.{} " + "contains {!r} as substrings".format( + wrapper.__qualname__, self.method_name, + ", ".join(map(repr, self._missing_subs)))) + + setattr(owner, name, wrapper) + + +class _TransformedBoundsLocator: + """ + Axes locator for `.Axes.inset_axes` and similarly positioned Axes. + + The locator is a callable object used in `.Axes.set_aspect` to compute the + Axes location depending on the renderer. + """ + + def __init__(self, bounds, transform): + """ + *bounds* (a ``[l, b, w, h]`` rectangle) and *transform* together + specify the position of the inset Axes. + """ + self._bounds = bounds + self._transform = transform + + def __call__(self, ax, renderer): + # Subtracting transSubfigure will typically rely on inverted(), + # freezing the transform; thus, this needs to be delayed until draw + # time as transSubfigure may otherwise change after this is evaluated. + return mtransforms.TransformedBbox( + mtransforms.Bbox.from_bounds(*self._bounds), + self._transform - ax.get_figure(root=False).transSubfigure) + + +def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False): + """ + Convert a MATLAB style color/line style format string to a (*linestyle*, + *marker*, *color*) tuple. + + Example format strings include: + + * 'ko': black circles + * '.b': blue dots + * 'r--': red dashed lines + * 'C2--': the third color in the color cycle, dashed lines + + The format is absolute in the sense that if a linestyle or marker is not + defined in *fmt*, there is no line or marker. This is expressed by + returning 'None' for the respective quantity. + + See Also + -------- + matplotlib.Line2D.lineStyles, matplotlib.colors.cnames + All possible styles and color format strings. + """ + + linestyle = None + marker = None + color = None + + # First check whether fmt is just a colorspec, but specifically exclude the + # grayscale string "1" (not "1.0"), which is interpreted as the tri_down + # marker "1". The grayscale string "0" could be unambiguously understood + # as a color (black) but also excluded for consistency. + if fmt not in ["0", "1"]: + try: + color = mcolors.to_rgba(fmt) + return linestyle, marker, color + except ValueError: + pass + + errfmt = ("{!r} is neither a data key nor a valid format string ({})" + if ambiguous_fmt_datakey else + "{!r} is not a valid format string ({})") + + i = 0 + while i < len(fmt): + c = fmt[i] + if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles. + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = fmt[i:i+2] + i += 2 + elif c in mlines.lineStyles: + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = c + i += 1 + elif c in mlines.lineMarkers: + if marker is not None: + raise ValueError(errfmt.format(fmt, "two marker symbols")) + marker = c + i += 1 + elif c in mcolors.get_named_colors_mapping(): + if color is not None: + raise ValueError(errfmt.format(fmt, "two color symbols")) + color = c + i += 1 + elif c == "C": + cn_color = re.match(r"C\d+", fmt[i:]) + if not cn_color: + raise ValueError(errfmt.format(fmt, "'C' must be followed by a number")) + color = mcolors.to_rgba(cn_color[0]) + i += len(cn_color[0]) + else: + raise ValueError(errfmt.format(fmt, f"unrecognized character {c!r}")) + + if linestyle is None and marker is None: + linestyle = mpl.rcParams['lines.linestyle'] + if linestyle is None: + linestyle = 'None' + if marker is None: + marker = 'None' + + return linestyle, marker, color + + +class _process_plot_var_args: + """ + Process variable length arguments to `~.Axes.plot`, to support :: + + plot(t, s) + plot(t1, s1, t2, s2) + plot(t1, s1, 'ko', t2, s2) + plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3) + + an arbitrary number of *x*, *y*, *fmt* are allowed + """ + + def __init__(self, output='Line2D'): + _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=output) + self.output = output + self.set_prop_cycle(None) + + def set_prop_cycle(self, cycler): + if cycler is None: + cycler = mpl.rcParams['axes.prop_cycle'] + self._idx = 0 + self._cycler_items = [*cycler] + + def __call__(self, axes, *args, data=None, return_kwargs=False, **kwargs): + axes._process_unit_info(kwargs=kwargs) + + for pos_only in "xy": + if pos_only in kwargs: + raise _api.kwarg_error(inspect.stack()[1].function, pos_only) + + if not args: + return + + if data is None: # Process dict views + args = [cbook.sanitize_sequence(a) for a in args] + else: # Process the 'data' kwarg. + replaced = [mpl._replacer(data, arg) for arg in args] + if len(args) == 1: + label_namer_idx = 0 + elif len(args) == 2: # Can be x, y or y, c. + # Figure out what the second argument is. + # 1) If the second argument cannot be a format shorthand, the + # second argument is the label_namer. + # 2) Otherwise (it could have been a format shorthand), + # a) if we did perform a substitution, emit a warning, and + # use it as label_namer. + # b) otherwise, it is indeed a format shorthand; use the + # first argument as label_namer. + try: + _process_plot_format(args[1]) + except ValueError: # case 1) + label_namer_idx = 1 + else: + if replaced[1] is not args[1]: # case 2a) + _api.warn_external( + f"Second argument {args[1]!r} is ambiguous: could " + f"be a format string but is in 'data'; using as " + f"data. If it was intended as data, set the " + f"format string to an empty string to suppress " + f"this warning. If it was intended as a format " + f"string, explicitly pass the x-values as well. " + f"Alternatively, rename the entry in 'data'.", + RuntimeWarning) + label_namer_idx = 1 + else: # case 2b) + label_namer_idx = 0 + elif len(args) == 3: + label_namer_idx = 1 + else: + raise ValueError( + "Using arbitrary long args with data is not supported due " + "to ambiguity of arguments; use multiple plotting calls " + "instead") + if kwargs.get("label") is None: + kwargs["label"] = mpl._label_from_arg( + replaced[label_namer_idx], args[label_namer_idx]) + args = replaced + ambiguous_fmt_datakey = data is not None and len(args) == 2 + + if len(args) >= 4 and not cbook.is_scalar_or_string( + kwargs.get("label")): + raise ValueError("plot() with multiple groups of data (i.e., " + "pairs of x and y) does not support multiple " + "labels") + + # Repeatedly grab (x, y) or (x, y, format) from the front of args and + # massage them into arguments to plot() or fill(). + + while args: + this, args = args[:2], args[2:] + if args and isinstance(args[0], str): + this += args[0], + args = args[1:] + yield from self._plot_args( + axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey, + return_kwargs=return_kwargs + ) + + def get_next_color(self): + """Return the next color in the cycle.""" + entry = self._cycler_items[self._idx] + if "color" in entry: + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + return entry["color"] + else: + return "k" + + def _getdefaults(self, kw, ignore=frozenset()): + """ + If some keys in the property cycle (excluding those in the set + *ignore*) are absent or set to None in the dict *kw*, return a copy + of the next entry in the property cycle, excluding keys in *ignore*. + Otherwise, don't advance the property cycle, and return an empty dict. + """ + defaults = self._cycler_items[self._idx] + if any(kw.get(k, None) is None for k in {*defaults} - ignore): + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + # Return a new dict to avoid exposing _cycler_items entries to mutation. + return {k: v for k, v in defaults.items() if k not in ignore} + else: + return {} + + def _setdefaults(self, defaults, kw): + """ + Add to the dict *kw* the entries in the dict *default* that are absent + or set to None in *kw*. + """ + for k in defaults: + if kw.get(k, None) is None: + kw[k] = defaults[k] + + def _make_line(self, axes, x, y, kw, kwargs): + kw = {**kw, **kwargs} # Don't modify the original kw. + self._setdefaults(self._getdefaults(kw), kw) + seg = mlines.Line2D(x, y, **kw) + return seg, kw + + def _make_coordinates(self, axes, x, y, kw, kwargs): + kw = {**kw, **kwargs} # Don't modify the original kw. + self._setdefaults(self._getdefaults(kw), kw) + return (x, y), kw + + def _make_polygon(self, axes, x, y, kw, kwargs): + # Polygon doesn't directly support unitized inputs. + x = axes.convert_xunits(x) + y = axes.convert_yunits(y) + + kw = kw.copy() # Don't modify the original kw. + kwargs = kwargs.copy() + + # Ignore 'marker'-related properties as they aren't Polygon + # properties, but they are Line2D properties, and so they are + # likely to appear in the default cycler construction. + # This is done here to the defaults dictionary as opposed to the + # other two dictionaries because we do want to capture when a + # *user* explicitly specifies a marker which should be an error. + # We also want to prevent advancing the cycler if there are no + # defaults needed after ignoring the given properties. + ignores = ({'marker', 'markersize', 'markeredgecolor', + 'markerfacecolor', 'markeredgewidth'} + # Also ignore anything provided by *kwargs*. + | {k for k, v in kwargs.items() if v is not None}) + + # Only using the first dictionary to use as basis + # for getting defaults for back-compat reasons. + # Doing it with both seems to mess things up in + # various places (probably due to logic bugs elsewhere). + default_dict = self._getdefaults(kw, ignores) + self._setdefaults(default_dict, kw) + + # Looks like we don't want "color" to be interpreted to + # mean both facecolor and edgecolor for some reason. + # So the "kw" dictionary is thrown out, and only its + # 'color' value is kept and translated as a 'facecolor'. + # This design should probably be revisited as it increases + # complexity. + facecolor = kw.get('color', None) + + # Throw out 'color' as it is now handled as a facecolor + default_dict.pop('color', None) + + # To get other properties set from the cycler + # modify the kwargs dictionary. + self._setdefaults(default_dict, kwargs) + + seg = mpatches.Polygon(np.column_stack((x, y)), + facecolor=facecolor, + fill=kwargs.get('fill', True), + closed=kw['closed']) + seg.set(**kwargs) + return seg, kwargs + + def _plot_args(self, axes, tup, kwargs, *, + return_kwargs=False, ambiguous_fmt_datakey=False): + """ + Process the arguments of ``plot([x], y, [fmt], **kwargs)`` calls. + + This processes a single set of ([x], y, [fmt]) parameters; i.e. for + ``plot(x, y, x2, y2)`` it will be called twice. Once for (x, y) and + once for (x2, y2). + + x and y may be 2D and thus can still represent multiple datasets. + + For multiple datasets, if the keyword argument *label* is a list, this + will unpack the list and assign the individual labels to the datasets. + + Parameters + ---------- + tup : tuple + A tuple of the positional parameters. This can be one of + + - (y,) + - (x, y) + - (y, fmt) + - (x, y, fmt) + + kwargs : dict + The keyword arguments passed to ``plot()``. + + return_kwargs : bool + Whether to also return the effective keyword arguments after label + unpacking as well. + + ambiguous_fmt_datakey : bool + Whether the format string in *tup* could also have been a + misspelled data key. + + Returns + ------- + result + If *return_kwargs* is false, a list of Artists representing the + dataset(s). + If *return_kwargs* is true, a list of (Artist, effective_kwargs) + representing the dataset(s). See *return_kwargs*. + The Artist is either `.Line2D` (if called from ``plot()``) or + `.Polygon` otherwise. + """ + if len(tup) > 1 and isinstance(tup[-1], str): + # xy is tup with fmt stripped (could still be (y,) only) + *xy, fmt = tup + linestyle, marker, color = _process_plot_format( + fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey) + elif len(tup) == 3: + raise ValueError('third arg must be a format string') + else: + xy = tup + linestyle, marker, color = None, None, None + + # Don't allow any None value; these would be up-converted to one + # element array of None which causes problems downstream. + if any(v is None for v in tup): + raise ValueError("x, y, and format string must not be None") + + kw = {} + for prop_name, val in zip(('linestyle', 'marker', 'color'), + (linestyle, marker, color)): + if val is not None: + # check for conflicts between fmt and kwargs + if (fmt.lower() != 'none' + and prop_name in kwargs + and val != 'None'): + # Technically ``plot(x, y, 'o', ls='--')`` is a conflict + # because 'o' implicitly unsets the linestyle + # (linestyle='None'). + # We'll gracefully not warn in this case because an + # explicit set via kwargs can be seen as intention to + # override an implicit unset. + # Note: We don't val.lower() != 'none' because val is not + # necessarily a string (can be a tuple for colors). This + # is safe, because *val* comes from _process_plot_format() + # which only returns 'None'. + _api.warn_external( + f"{prop_name} is redundantly defined by the " + f"'{prop_name}' keyword argument and the fmt string " + f'"{fmt}" (-> {prop_name}={val!r}). The keyword ' + f"argument will take precedence.") + kw[prop_name] = val + + if len(xy) == 2: + x = _check_1d(xy[0]) + y = _check_1d(xy[1]) + else: + x, y = index_of(xy[-1]) + + if axes.xaxis is not None: + axes.xaxis.update_units(x) + if axes.yaxis is not None: + axes.yaxis.update_units(y) + + if x.shape[0] != y.shape[0]: + raise ValueError(f"x and y must have same first dimension, but " + f"have shapes {x.shape} and {y.shape}") + if x.ndim > 2 or y.ndim > 2: + raise ValueError(f"x and y can be no greater than 2D, but have " + f"shapes {x.shape} and {y.shape}") + if x.ndim == 1: + x = x[:, np.newaxis] + if y.ndim == 1: + y = y[:, np.newaxis] + + if self.output == 'Line2D': + make_artist = self._make_line + elif self.output == 'Polygon': + kw['closed'] = kwargs.get('closed', True) + make_artist = self._make_polygon + elif self.output == 'coordinates': + make_artist = self._make_coordinates + else: + _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=self.output) + + ncx, ncy = x.shape[1], y.shape[1] + if ncx > 1 and ncy > 1 and ncx != ncy: + raise ValueError(f"x has {ncx} columns but y has {ncy} columns") + if ncx == 0 or ncy == 0: + return [] + + label = kwargs.get('label') + n_datasets = max(ncx, ncy) + + if cbook.is_scalar_or_string(label): + labels = [label] * n_datasets + elif len(label) == n_datasets: + labels = label + elif n_datasets == 1: + msg = (f'Passing label as a length {len(label)} sequence when ' + 'plotting a single dataset is deprecated in Matplotlib 3.9 ' + 'and will error in 3.11. To keep the current behavior, ' + 'cast the sequence to string before passing.') + _api.warn_deprecated('3.9', message=msg) + labels = [label] + else: + raise ValueError( + f"label must be scalar or have the same length as the input " + f"data, but found {len(label)} for {n_datasets} datasets.") + + result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw, + {**kwargs, 'label': label}) + for j, label in enumerate(labels)) + + if return_kwargs: + return list(result) + else: + return [l[0] for l in result] + + +@_api.define_aliases({"facecolor": ["fc"]}) +class _AxesBase(martist.Artist): + name = "rectilinear" + + # axis names are the prefixes for the attributes that contain the + # respective axis; e.g. 'x' <-> self.xaxis, containing an XAxis. + # Note that PolarAxes uses these attributes as well, so that we have + # 'x' <-> self.xaxis, containing a ThetaAxis. In particular we do not + # have 'theta' in _axis_names. + # In practice, this is ('x', 'y') for all 2D Axes and ('x', 'y', 'z') + # for Axes3D. + _axis_names = ("x", "y") + _shared_axes = {name: cbook.Grouper() for name in _axis_names} + _twinned_axes = cbook.Grouper() + + _subclass_uses_cla = False + + dataLim: mtransforms.Bbox + """The bounding `.Bbox` enclosing all data displayed in the Axes.""" + + spines: mspines.Spines + """ + The `.Spines` container for the Axes' spines, i.e. the lines denoting the + data area boundaries. + """ + + xaxis: maxis.XAxis + """ + The `.XAxis` instance. + + Common axis-related configuration can be achieved through high-level wrapper + methods on Axes; e.g. `ax.set_xticks <.Axes.set_xticks>` is a shortcut for + `ax.xaxis.set_ticks <.Axis.set_ticks>`. The *xaxis* attribute gives direct + direct access to the underlying `~.axis.Axis` if you need more control. + + See also + + - :ref:`Axis wrapper methods on Axes ` + - :doc:`Axis API ` + """ + + yaxis: maxis.YAxis + """ + The `.YAxis` instance. + + Common axis-related configuration can be achieved through high-level wrapper + methods on Axes; e.g. `ax.set_yticks <.Axes.set_yticks>` is a shortcut for + `ax.yaxis.set_ticks <.Axis.set_ticks>`. The *yaxis* attribute gives direct + access to the underlying `~.axis.Axis` if you need more control. + + See also + + - :ref:`Axis wrapper methods on Axes ` + - :doc:`Axis API ` + """ + + @property + def _axis_map(self): + """A mapping of axis names, e.g. 'x', to `Axis` instances.""" + return {name: getattr(self, f"{name}axis") + for name in self._axis_names} + + def __str__(self): + return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format( + type(self).__name__, self._position.bounds) + + def __init__(self, fig, + *args, + facecolor=None, # defaults to rc axes.facecolor + frameon=True, + sharex=None, # use Axes instance's xaxis info + sharey=None, # use Axes instance's yaxis info + label='', + xscale=None, + yscale=None, + box_aspect=None, + forward_navigation_events="auto", + **kwargs + ): + """ + Build an Axes in a figure. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The Axes is built in the `.Figure` *fig*. + + *args + ``*args`` can be a single ``(left, bottom, width, height)`` + rectangle or a single `.Bbox`. This specifies the rectangle (in + figure coordinates) where the Axes is positioned. + + ``*args`` can also consist of three numbers or a single three-digit + number; in the latter case, the digits are considered as + independent numbers. The numbers are interpreted as ``(nrows, + ncols, index)``: ``(nrows, ncols)`` specifies the size of an array + of subplots, and ``index`` is the 1-based index of the subplot + being created. Finally, ``*args`` can also directly be a + `.SubplotSpec` instance. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + The x- or y-`~.matplotlib.axis` is shared with the x- or y-axis in + the input `~.axes.Axes`. Note that it is not possible to unshare + axes. + + frameon : bool, default: True + Whether the Axes frame is visible. + + box_aspect : float, optional + Set a fixed aspect for the Axes box, i.e. the ratio of height to + width. See `~.axes.Axes.set_box_aspect` for details. + + forward_navigation_events : bool or "auto", default: "auto" + Control whether pan/zoom events are passed through to Axes below + this one. "auto" is *True* for axes with an invisible patch and + *False* otherwise. + + **kwargs + Other optional keyword arguments: + + %(Axes:kwdoc)s + + Returns + ------- + `~.axes.Axes` + The new `~.axes.Axes` object. + """ + + super().__init__() + if "rect" in kwargs: + if args: + raise TypeError( + "'rect' cannot be used together with positional arguments") + rect = kwargs.pop("rect") + _api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect) + args = (rect,) + subplotspec = None + if len(args) == 1 and isinstance(args[0], mtransforms.Bbox): + self._position = args[0].frozen() + elif len(args) == 1 and np.iterable(args[0]): + self._position = mtransforms.Bbox.from_bounds(*args[0]) + else: + self._position = self._originalPosition = mtransforms.Bbox.unit() + subplotspec = SubplotSpec._from_subplot_args(fig, args) + if self._position.width < 0 or self._position.height < 0: + raise ValueError('Width and height specified must be non-negative') + self._originalPosition = self._position.frozen() + self.axes = self + self._aspect = 'auto' + self._adjustable = 'box' + self._anchor = 'C' + self._stale_viewlims = dict.fromkeys(self._axis_names, False) + self._forward_navigation_events = forward_navigation_events + self._sharex = sharex + self._sharey = sharey + self.set_label(label) + self.set_figure(fig) + # The subplotspec needs to be set after the figure (so that + # figure-level subplotpars are taken into account), but the figure + # needs to be set after self._position is initialized. + if subplotspec: + self.set_subplotspec(subplotspec) + else: + self._subplotspec = None + self.set_box_aspect(box_aspect) + self._axes_locator = None # Optionally set via update(kwargs). + + self._children = [] + + # placeholder for any colorbars added that use this Axes. + # (see colorbar.py): + self._colorbars = [] + self.spines = mspines.Spines.from_dict(self._gen_axes_spines()) + + # this call may differ for non-sep axes, e.g., polar + self._init_axis() + if facecolor is None: + facecolor = mpl.rcParams['axes.facecolor'] + self._facecolor = facecolor + self._frameon = frameon + self.set_axisbelow(mpl.rcParams['axes.axisbelow']) + + self._rasterization_zorder = None + self.clear() + + # funcs used to format x and y - fall back on major formatters + self.fmt_xdata = None + self.fmt_ydata = None + + self.set_navigate(True) + self.set_navigate_mode(None) + + if xscale: + self.set_xscale(xscale) + if yscale: + self.set_yscale(yscale) + + self._internal_update(kwargs) + + for name, axis in self._axis_map.items(): + axis.callbacks._connect_picklable( + 'units', self._unit_change_handler(name)) + + rcParams = mpl.rcParams + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.minor.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.minor.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.minor.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.minor.left'], + right=rcParams['ytick.right'] and rcParams['ytick.minor.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.minor.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.minor.right']), + which='minor') + + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.major.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.major.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.major.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.major.left'], + right=rcParams['ytick.right'] and rcParams['ytick.major.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.major.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.major.right']), + which='major') + + def __init_subclass__(cls, **kwargs): + parent_uses_cla = super(cls, cls)._subclass_uses_cla + if 'cla' in cls.__dict__: + _api.warn_deprecated( + '3.6', + pending=True, + message=f'Overriding `Axes.cla` in {cls.__qualname__} is ' + 'pending deprecation in %(since)s and will be fully ' + 'deprecated in favor of `Axes.clear` in the future. ' + 'Please report ' + f'this to the {cls.__module__!r} author.') + cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla + super().__init_subclass__(**kwargs) + + def __getstate__(self): + state = super().__getstate__() + # Prune the sharing & twinning info to only contain the current group. + state["_shared_axes"] = { + name: self._shared_axes[name].get_siblings(self) + for name in self._axis_names if self in self._shared_axes[name]} + state["_twinned_axes"] = (self._twinned_axes.get_siblings(self) + if self in self._twinned_axes else None) + return state + + def __setstate__(self, state): + # Merge the grouping info back into the global groupers. + shared_axes = state.pop("_shared_axes") + for name, shared_siblings in shared_axes.items(): + self._shared_axes[name].join(*shared_siblings) + twinned_siblings = state.pop("_twinned_axes") + if twinned_siblings: + self._twinned_axes.join(*twinned_siblings) + self.__dict__ = state + self._stale = True + + def __repr__(self): + fields = [] + if self.get_label(): + fields += [f"label={self.get_label()!r}"] + if hasattr(self, "get_title"): + titles = {} + for k in ["left", "center", "right"]: + title = self.get_title(loc=k) + if title: + titles[k] = title + if titles: + fields += [f"title={titles}"] + for name, axis in self._axis_map.items(): + if axis.label and axis.label.get_text(): + fields += [f"{name}label={axis.label.get_text()!r}"] + return f"<{self.__class__.__name__}: " + ", ".join(fields) + ">" + + def get_subplotspec(self): + """Return the `.SubplotSpec` associated with the subplot, or None.""" + return self._subplotspec + + def set_subplotspec(self, subplotspec): + """Set the `.SubplotSpec`. associated with the subplot.""" + self._subplotspec = subplotspec + self._set_position(subplotspec.get_position(self.get_figure(root=False))) + + def get_gridspec(self): + """Return the `.GridSpec` associated with the subplot, or None.""" + return self._subplotspec.get_gridspec() if self._subplotspec else None + + def get_window_extent(self, renderer=None): + """ + Return the Axes bounding box in display space. + + This bounding box does not include the spines, ticks, ticklabels, + or other labels. For a bounding box including these elements use + `~matplotlib.axes.Axes.get_tightbbox`. + + See Also + -------- + matplotlib.axes.Axes.get_tightbbox + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + return self.bbox + + def _init_axis(self): + # This is moved out of __init__ because non-separable axes don't use it + self.xaxis = maxis.XAxis(self, clear=False) + self.spines.bottom.register_axis(self.xaxis) + self.spines.top.register_axis(self.xaxis) + self.yaxis = maxis.YAxis(self, clear=False) + self.spines.left.register_axis(self.yaxis) + self.spines.right.register_axis(self.yaxis) + + def set_figure(self, fig): + # docstring inherited + super().set_figure(fig) + + self.bbox = mtransforms.TransformedBbox(self._position, + fig.transSubfigure) + # these will be updated later as data is added + self.dataLim = mtransforms.Bbox.null() + self._viewLim = mtransforms.Bbox.unit() + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + self._set_lim_and_transforms() + + def _unstale_viewLim(self): + # We should arrange to store this information once per share-group + # instead of on every axis. + need_scale = { + name: any(ax._stale_viewlims[name] + for ax in self._shared_axes[name].get_siblings(self)) + for name in self._axis_names} + if any(need_scale.values()): + for name in need_scale: + for ax in self._shared_axes[name].get_siblings(self): + ax._stale_viewlims[name] = False + self.autoscale_view(**{f"scale{name}": scale + for name, scale in need_scale.items()}) + + @property + def viewLim(self): + """The view limits as `.Bbox` in data coordinates.""" + self._unstale_viewLim() + return self._viewLim + + def _request_autoscale_view(self, axis="all", tight=None): + """ + Mark a single axis, or all of them, as stale wrt. autoscaling. + + No computation is performed until the next autoscaling; thus, separate + calls to control individual axises incur negligible performance cost. + + Parameters + ---------- + axis : str, default: "all" + Either an element of ``self._axis_names``, or "all". + tight : bool or None, default: None + """ + axis_names = _api.check_getitem( + {**{k: [k] for k in self._axis_names}, "all": self._axis_names}, + axis=axis) + for name in axis_names: + self._stale_viewlims[name] = True + if tight is not None: + self._tight = tight + + def _set_lim_and_transforms(self): + """ + Set the *_xaxis_transform*, *_yaxis_transform*, *transScale*, + *transData*, *transLimits* and *transAxes* transformations. + + .. note:: + + This method is primarily used by rectilinear projections of the + `~matplotlib.axes.Axes` class, and is meant to be overridden by + new kinds of projection Axes that need different transformations + and limits. (See `~matplotlib.projections.polar.PolarAxes` for an + example.) + """ + self.transAxes = mtransforms.BboxTransformTo(self.bbox) + + # Transforms the x and y axis separately by a scale factor. + # It is assumed that this part will have non-linear components + # (e.g., for a log scale). + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + # An affine transformation on the data, generally to limit the + # range of the axes + self.transLimits = mtransforms.BboxTransformFrom( + mtransforms.TransformedBbox(self._viewLim, self.transScale)) + + # The parentheses are important for efficiency here -- they + # group the last two (which are usually affines) separately + # from the first (which, with log-scaling can be non-affine). + self.transData = self.transScale + (self.transLimits + self.transAxes) + + self._xaxis_transform = mtransforms.blended_transform_factory( + self.transData, self.transAxes) + self._yaxis_transform = mtransforms.blended_transform_factory( + self.transAxes, self.transData) + + def get_xaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing x-axis labels, ticks + and gridlines. The x-direction is in data coordinates and the + y-direction is in axis coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._xaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.bottom.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.top.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_xaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing x-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in data coordinates and the y-direction is in + axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick1') + + mtransforms.ScaledTranslation( + 0, -1 * pad_points / 72, + self.get_figure(root=False).dpi_scale_trans), + "top", labels_align) + + def get_xaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondary x-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in data coordinates and the y-direction + is in axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick2') + + mtransforms.ScaledTranslation( + 0, pad_points / 72, + self.get_figure(root=False).dpi_scale_trans), + "bottom", labels_align) + + def get_yaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing y-axis labels, ticks + and gridlines. The x-direction is in axis coordinates and the + y-direction is in data coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._yaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.left.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.right.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_yaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing y-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in axis coordinates and the y-direction is in + data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick1') + + mtransforms.ScaledTranslation( + -1 * pad_points / 72, 0, + self.get_figure(root=False).dpi_scale_trans), + labels_align, "right") + + def get_yaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondart y-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in axis coordinates and the y-direction + is in data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick2') + + mtransforms.ScaledTranslation( + pad_points / 72, 0, + self.get_figure(root=False).dpi_scale_trans), + labels_align, "left") + + def _update_transScale(self): + self.transScale.set( + mtransforms.blended_transform_factory( + self.xaxis.get_transform(), self.yaxis.get_transform())) + + def get_position(self, original=False): + """ + Return the position of the Axes within the figure as a `.Bbox`. + + Parameters + ---------- + original : bool + If ``True``, return the original position. Otherwise, return the + active position. For an explanation of the positions see + `.set_position`. + + Returns + ------- + `.Bbox` + + """ + if original: + return self._originalPosition.frozen() + else: + locator = self.get_axes_locator() + if not locator: + self.apply_aspect() + return self._position.frozen() + + def set_position(self, pos, which='both'): + """ + Set the Axes position. + + Axes have two position attributes. The 'original' position is the + position allocated for the Axes. The 'active' position is the + position the Axes is actually drawn at. These positions are usually + the same unless a fixed aspect is set to the Axes. See + `.Axes.set_aspect` for details. + + Parameters + ---------- + pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox` + The new position of the Axes in `.Figure` coordinates. + + which : {'both', 'active', 'original'}, default: 'both' + Determines which position variables to change. + + See Also + -------- + matplotlib.transforms.Bbox.from_bounds + matplotlib.transforms.Bbox.from_extents + """ + self._set_position(pos, which=which) + # because this is being called externally to the library we + # don't let it be in the layout. + self.set_in_layout(False) + + def _set_position(self, pos, which='both'): + """ + Private version of set_position. + + Call this internally to get the same functionality of `set_position`, + but not to take the axis out of the constrained_layout hierarchy. + """ + if not isinstance(pos, mtransforms.BboxBase): + pos = mtransforms.Bbox.from_bounds(*pos) + for ax in self._twinned_axes.get_siblings(self): + if which in ('both', 'active'): + ax._position.set(pos) + if which in ('both', 'original'): + ax._originalPosition.set(pos) + self.stale = True + + def reset_position(self): + """ + Reset the active position to the original position. + + This undoes changes to the active position (as defined in + `.set_position`) which may have been performed to satisfy fixed-aspect + constraints. + """ + for ax in self._twinned_axes.get_siblings(self): + pos = ax.get_position(original=True) + ax.set_position(pos, which='active') + + def set_axes_locator(self, locator): + """ + Set the Axes locator. + + Parameters + ---------- + locator : Callable[[Axes, Renderer], Bbox] + """ + self._axes_locator = locator + self.stale = True + + def get_axes_locator(self): + """ + Return the axes_locator. + """ + return self._axes_locator + + def _set_artist_props(self, a): + """Set the boilerplate props for artists added to Axes.""" + a.set_figure(self.get_figure(root=False)) + if not a.is_transform_set(): + a.set_transform(self.transData) + + a.axes = self + if a.get_mouseover(): + self._mouseover_set.add(a) + + def _gen_axes_patch(self): + """ + Returns + ------- + Patch + The patch used to draw the background of the Axes. It is also used + as the clipping path for any data elements on the Axes. + + In the standard Axes, this is a rectangle, but in other projections + it may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0) + + def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): + """ + Returns + ------- + dict + Mapping of spine names to `.Line2D` or `.Patch` instances that are + used to draw Axes spines. + + In the standard Axes, spines are single line segments, but in other + projections they may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return {side: mspines.Spine.linear_spine(self, side) + for side in ['left', 'right', 'bottom', 'top']} + + def sharex(self, other): + """ + Share the x-axis with *other*. + + This is equivalent to passing ``sharex=other`` when constructing the + Axes, and cannot be used if the x-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharex is not None and other is not self._sharex: + raise ValueError("x-axis is already shared") + self._shared_axes["x"].join(self, other) + self._sharex = other + self.xaxis.major = other.xaxis.major # Ticker instances holding + self.xaxis.minor = other.xaxis.minor # locator and formatter. + x0, x1 = other.get_xlim() + self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on()) + self.xaxis._scale = other.xaxis._scale + + def sharey(self, other): + """ + Share the y-axis with *other*. + + This is equivalent to passing ``sharey=other`` when constructing the + Axes, and cannot be used if the y-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharey is not None and other is not self._sharey: + raise ValueError("y-axis is already shared") + self._shared_axes["y"].join(self, other) + self._sharey = other + self.yaxis.major = other.yaxis.major # Ticker instances holding + self.yaxis.minor = other.yaxis.minor # locator and formatter. + y0, y1 = other.get_ylim() + self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on()) + self.yaxis._scale = other.yaxis._scale + + def __clear(self): + """Clear the Axes.""" + # The actual implementation of clear() as long as clear() has to be + # an adapter delegating to the correct implementation. + # The implementation can move back into clear() when the + # deprecation on cla() subclassing expires. + + # stash the current visibility state + if hasattr(self, 'patch'): + patch_visible = self.patch.get_visible() + else: + patch_visible = True + + xaxis_visible = self.xaxis.get_visible() + yaxis_visible = self.yaxis.get_visible() + + for axis in self._axis_map.values(): + axis.clear() # Also resets the scale to linear. + for spine in self.spines.values(): + spine._clear() # Use _clear to not clear Axis again + + self.ignore_existing_data_limits = True + self.callbacks = cbook.CallbackRegistry( + signals=["xlim_changed", "ylim_changed", "zlim_changed"]) + + # update the minor locator for x and y axis based on rcParams + if mpl.rcParams['xtick.minor.visible']: + self.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + if mpl.rcParams['ytick.minor.visible']: + self.yaxis.set_minor_locator(mticker.AutoMinorLocator()) + + self._xmargin = mpl.rcParams['axes.xmargin'] + self._ymargin = mpl.rcParams['axes.ymargin'] + self._tight = None + self._use_sticky_edges = True + + self._get_lines = _process_plot_var_args() + self._get_patches_for_fill = _process_plot_var_args('Polygon') + + self._gridOn = mpl.rcParams['axes.grid'] + # Swap children to minimize time we spend in an invalid state + old_children, self._children = self._children, [] + for chld in old_children: + chld._remove_method = None + chld._parent_figure = None + chld.axes = None + # Use list.clear to break the `artist._remove_method` reference cycle + old_children.clear() + self._mouseover_set = _OrderedSet() + self.child_axes = [] + self._current_image = None # strictly for pyplot via _sci, _gci + self._projection_init = None # strictly for pyplot.subplot + self.legend_ = None + self.containers = [] + + self.grid(False) # Disable grid on init to use rcParameter + self.grid(self._gridOn, which=mpl.rcParams['axes.grid.which'], + axis=mpl.rcParams['axes.grid.axis']) + props = font_manager.FontProperties( + size=mpl.rcParams['axes.titlesize'], + weight=mpl.rcParams['axes.titleweight']) + + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + self._autotitlepos = True + else: + self._autotitlepos = False + + self.title = mtext.Text( + x=0.5, y=y, text='', + fontproperties=props, + verticalalignment='baseline', + horizontalalignment='center', + ) + self._left_title = mtext.Text( + x=0.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='left', ) + self._right_title = mtext.Text( + x=1.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='right', + ) + title_offset_points = mpl.rcParams['axes.titlepad'] + # refactor this out so it can be called in ax.set_title if + # pad argument used... + self._set_title_offset_trans(title_offset_points) + + for _title in (self.title, self._left_title, self._right_title): + self._set_artist_props(_title) + + # The patch draws the background of the Axes. We want this to be below + # the other artists. We use the frame to draw the edges so we are + # setting the edgecolor to None. + self.patch = self._gen_axes_patch() + self.patch.set_figure(self.get_figure(root=False)) + self.patch.set_facecolor(self._facecolor) + self.patch.set_edgecolor('none') + self.patch.set_linewidth(0) + self.patch.set_transform(self.transAxes) + + self.set_axis_on() + + self.xaxis.set_clip_path(self.patch) + self.yaxis.set_clip_path(self.patch) + + if self._sharex is not None: + self.xaxis.set_visible(xaxis_visible) + self.patch.set_visible(patch_visible) + if self._sharey is not None: + self.yaxis.set_visible(yaxis_visible) + self.patch.set_visible(patch_visible) + + # This comes last, as the call to _set_lim may trigger an autoscale (in + # case of shared axes), requiring children to be already set up. + for name, axis in self._axis_map.items(): + share = getattr(self, f"_share{name}") + if share is not None: + getattr(self, f"share{name}")(share) + else: + # Although the scale was set to linear as part of clear, + # polar requires that _set_scale is called again + if self.name == "polar": + axis._set_scale("linear") + axis._set_lim(0, 1, auto=True) + self._update_transScale() + + self.stale = True + + def clear(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.cla() + else: + self.__clear() + + def cla(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.__clear() + else: + self.clear() + + class ArtistList(Sequence): + """ + A sublist of Axes children based on their type. + + The type-specific children sublists were made immutable in Matplotlib + 3.7. In the future these artist lists may be replaced by tuples. Use + as if this is a tuple already. + """ + def __init__(self, axes, prop_name, + valid_types=None, invalid_types=None): + """ + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The Axes from which this sublist will pull the children + Artists. + prop_name : str + The property name used to access this sublist from the Axes; + used to generate deprecation warnings. + valid_types : list of type, optional + A list of types that determine which children will be returned + by this sublist. If specified, then the Artists in the sublist + must be instances of any of these types. If unspecified, then + any type of Artist is valid (unless limited by + *invalid_types*.) + invalid_types : tuple, optional + A list of types that determine which children will *not* be + returned by this sublist. If specified, then Artists in the + sublist will never be an instance of these types. Otherwise, no + types will be excluded. + """ + self._axes = axes + self._prop_name = prop_name + self._type_check = lambda artist: ( + (not valid_types or isinstance(artist, valid_types)) and + (not invalid_types or not isinstance(artist, invalid_types)) + ) + + def __repr__(self): + return f'' + + def __len__(self): + return sum(self._type_check(artist) + for artist in self._axes._children) + + def __iter__(self): + for artist in list(self._axes._children): + if self._type_check(artist): + yield artist + + def __getitem__(self, key): + return [artist + for artist in self._axes._children + if self._type_check(artist)][key] + + def __add__(self, other): + if isinstance(other, (list, _AxesBase.ArtistList)): + return [*self, *other] + if isinstance(other, (tuple, _AxesBase.ArtistList)): + return (*self, *other) + return NotImplemented + + def __radd__(self, other): + if isinstance(other, list): + return other + list(self) + if isinstance(other, tuple): + return other + tuple(self) + return NotImplemented + + @property + def artists(self): + return self.ArtistList(self, 'artists', invalid_types=( + mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch, + mtable.Table, mtext.Text)) + + @property + def collections(self): + return self.ArtistList(self, 'collections', + valid_types=mcoll.Collection) + + @property + def images(self): + return self.ArtistList(self, 'images', valid_types=mimage.AxesImage) + + @property + def lines(self): + return self.ArtistList(self, 'lines', valid_types=mlines.Line2D) + + @property + def patches(self): + return self.ArtistList(self, 'patches', valid_types=mpatches.Patch) + + @property + def tables(self): + return self.ArtistList(self, 'tables', valid_types=mtable.Table) + + @property + def texts(self): + return self.ArtistList(self, 'texts', valid_types=mtext.Text) + + def get_facecolor(self): + """Get the facecolor of the Axes.""" + return self.patch.get_facecolor() + + def set_facecolor(self, color): + """ + Set the facecolor of the Axes. + + Parameters + ---------- + color : :mpltype:`color` + """ + self._facecolor = color + self.stale = True + return self.patch.set_facecolor(color) + + def _set_title_offset_trans(self, title_offset_points): + """ + Set the offset for the title either from :rc:`axes.titlepad` + or from set_title kwarg ``pad``. + """ + self.titleOffsetTrans = mtransforms.ScaledTranslation( + 0.0, title_offset_points / 72, + self.get_figure(root=False).dpi_scale_trans) + for _title in (self.title, self._left_title, self._right_title): + _title.set_transform(self.transAxes + self.titleOffsetTrans) + _title.set_clip_box(None) + + def set_prop_cycle(self, *args, **kwargs): + """ + Set the property cycle of the Axes. + + The property cycle controls the style properties such as color, + marker and linestyle of future plot commands. The style properties + of data already added to the Axes are not modified. + + Call signatures:: + + set_prop_cycle(cycler) + set_prop_cycle(label=values, label2=values2, ...) + set_prop_cycle(label, values) + + Form 1 sets given `~cycler.Cycler` object. + + Form 2 creates a `~cycler.Cycler` which cycles over one or more + properties simultaneously and set it as the property cycle of the + Axes. If multiple properties are given, their value lists must have + the same length. This is just a shortcut for explicitly creating a + cycler and passing it to the function, i.e. it's short for + ``set_prop_cycle(cycler(label=values, label2=values2, ...))``. + + Form 3 creates a `~cycler.Cycler` for a single property and set it + as the property cycle of the Axes. This form exists for compatibility + with the original `cycler.cycler` interface. Its use is discouraged + in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``. + + Parameters + ---------- + cycler : `~cycler.Cycler` or ``None`` + Set the given Cycler. *None* resets to the cycle defined by the + current style. + + .. ACCEPTS: `~cycler.Cycler` + + label : str + The property key. Must be a valid `.Artist` property. + For example, 'color' or 'linestyle'. Aliases are allowed, + such as 'c' for 'color' and 'lw' for 'linewidth'. + + values : iterable + Finite-length iterable of the property values. These values + are validated and will raise a ValueError if invalid. + + See Also + -------- + matplotlib.rcsetup.cycler + Convenience function for creating validated cyclers for properties. + cycler.cycler + The original function for creating unvalidated cyclers. + + Examples + -------- + Setting the property cycle for a single property: + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue']) + + Setting the property cycle for simultaneously cycling over multiple + properties (e.g. red circle, green plus, blue cross): + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue'], + ... marker=['o', '+', 'x']) + + """ + if args and kwargs: + raise TypeError("Cannot supply both positional and keyword " + "arguments to this method.") + # Can't do `args == (None,)` as that crashes cycler. + if len(args) == 1 and args[0] is None: + prop_cycle = None + else: + prop_cycle = cycler(*args, **kwargs) + self._get_lines.set_prop_cycle(prop_cycle) + self._get_patches_for_fill.set_prop_cycle(prop_cycle) + + def get_aspect(self): + """ + Return the aspect ratio of the Axes scaling. + + This is either "auto" or a float giving the ratio of y/x-scale. + """ + return self._aspect + + def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): + """ + Set the aspect ratio of the Axes scaling, i.e. y/x-scale. + + Parameters + ---------- + aspect : {'auto', 'equal'} or float + Possible values: + + - 'auto': fill the position rectangle with data. + - 'equal': same as ``aspect=1``, i.e. same scaling for x and y. + - *float*: The displayed size of 1 unit in y-data coordinates will + be *aspect* times the displayed size of 1 unit in x-data + coordinates; e.g. for ``aspect=2`` a square in data coordinates + will be rendered with a height of twice its width. + + adjustable : None or {'box', 'datalim'}, optional + If not ``None``, this defines which parameter will be adjusted to + meet the required aspect. See `.set_adjustable` for further + details. + + anchor : None or str or (float, float), optional + If not ``None``, this defines where the Axes will be drawn if there + is extra space due to aspect constraints. The most common way + to specify the anchor are abbreviations of cardinal directions: + + ===== ===================== + value description + ===== ===================== + 'C' centered + 'SW' lower left corner + 'S' middle of bottom edge + 'SE' lower right corner + etc. + ===== ===================== + + See `~.Axes.set_anchor` for further details. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + """ + if cbook._str_equal(aspect, 'equal'): + aspect = 1 + if not cbook._str_equal(aspect, 'auto'): + aspect = float(aspect) # raise ValueError if necessary + if aspect <= 0 or not np.isfinite(aspect): + raise ValueError("aspect must be finite and positive ") + + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + + for ax in axes: + ax._aspect = aspect + + if adjustable is None: + adjustable = self._adjustable + self.set_adjustable(adjustable, share=share) # Handle sharing. + + if anchor is not None: + self.set_anchor(anchor, share=share) + self.stale = True + + def get_adjustable(self): + """ + Return whether the Axes will adjust its physical dimension ('box') or + its data limits ('datalim') to achieve the desired aspect ratio. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + """ + return self._adjustable + + def set_adjustable(self, adjustable, share=False): + """ + Set how the Axes adjusts to achieve the required aspect ratio. + + Parameters + ---------- + adjustable : {'box', 'datalim'} + If 'box', change the physical dimensions of the Axes. + If 'datalim', change the ``x`` or ``y`` data limits. This + may ignore explicitly defined axis limits. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + + Notes + ----- + Shared Axes (of which twinned Axes are a special case) + impose restrictions on how aspect ratios can be imposed. + For twinned Axes, use 'datalim'. For Axes that share both + x and y, use 'box'. Otherwise, either 'datalim' or 'box' + may be used. These limitations are partly a requirement + to avoid over-specification, and partly a result of the + particular implementation we are currently using, in + which the adjustments for aspect ratios are done sequentially + and independently on each Axes as it is drawn. + """ + _api.check_in_list(["box", "datalim"], adjustable=adjustable) + if share: + axs = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axs = [self] + if (adjustable == "datalim" + and any(getattr(ax.get_data_ratio, "__func__", None) + != _AxesBase.get_data_ratio + for ax in axs)): + # Limits adjustment by apply_aspect assumes that the axes' aspect + # ratio can be computed from the data limits and scales. + raise ValueError("Cannot set Axes adjustable to 'datalim' for " + "Axes which override 'get_data_ratio'") + for ax in axs: + ax._adjustable = adjustable + self.stale = True + + def get_box_aspect(self): + """ + Return the Axes box aspect, i.e. the ratio of height to width. + + The box aspect is ``None`` (i.e. chosen depending on the available + figure space) unless explicitly specified. + + See Also + -------- + matplotlib.axes.Axes.set_box_aspect + for a description of box aspect. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._box_aspect + + def set_box_aspect(self, aspect=None): + """ + Set the Axes box aspect, i.e. the ratio of height to width. + + This defines the aspect of the Axes in figure space and is not to be + confused with the data aspect (see `~.Axes.set_aspect`). + + Parameters + ---------- + aspect : float or None + Changes the physical dimensions of the Axes, such that the ratio + of the Axes height to the Axes width in physical units is equal to + *aspect*. Defining a box aspect will change the *adjustable* + property to 'datalim' (see `~.Axes.set_adjustable`). + + *None* will disable a fixed box aspect so that height and width + of the Axes are chosen independently. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + axs = {*self._twinned_axes.get_siblings(self), + *self._twinned_axes.get_siblings(self)} + + if aspect is not None: + aspect = float(aspect) + # when box_aspect is set to other than ´None`, + # adjustable must be "datalim" + for ax in axs: + ax.set_adjustable("datalim") + + for ax in axs: + ax._box_aspect = aspect + ax.stale = True + + def get_anchor(self): + """ + Get the anchor location. + + See Also + -------- + matplotlib.axes.Axes.set_anchor + for a description of the anchor. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._anchor + + def set_anchor(self, anchor, share=False): + """ + Define the anchor location. + + The actual drawing area (active position) of the Axes may be smaller + than the Bbox (original position) when a fixed aspect is required. The + anchor defines where the drawing area will be located within the + available space. + + Parameters + ---------- + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} + Either an (*x*, *y*) pair of relative coordinates (0 is left or + bottom, 1 is right or top), 'C' (center), or a cardinal direction + ('SW', southwest, is bottom left, etc.). str inputs are shorthands + for (*x*, *y*) coordinates, as shown in the following diagram:: + + ┌─────────────────┬─────────────────┬─────────────────┐ + │ 'NW' (0.0, 1.0) │ 'N' (0.5, 1.0) │ 'NE' (1.0, 1.0) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'W' (0.0, 0.5) │ 'C' (0.5, 0.5) │ 'E' (1.0, 0.5) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'SW' (0.0, 0.0) │ 'S' (0.5, 0.0) │ 'SE' (1.0, 0.0) │ + └─────────────────┴─────────────────┴─────────────────┘ + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2): + raise ValueError('argument must be among %s' % + ', '.join(mtransforms.Bbox.coefs)) + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + for ax in axes: + ax._anchor = anchor + + self.stale = True + + def get_data_ratio(self): + """ + Return the aspect ratio of the scaled data. + + Notes + ----- + This method is intended to be overridden by new projection types. + """ + txmin, txmax = self.xaxis.get_transform().transform(self.get_xbound()) + tymin, tymax = self.yaxis.get_transform().transform(self.get_ybound()) + xsize = max(abs(txmax - txmin), 1e-30) + ysize = max(abs(tymax - tymin), 1e-30) + return ysize / xsize + + def apply_aspect(self, position=None): + """ + Adjust the Axes for a specified data aspect ratio. + + Depending on `.get_adjustable` this will modify either the + Axes box (position) or the view limits. In the former case, + `~matplotlib.axes.Axes.get_anchor` will affect the position. + + Parameters + ---------- + position : None or .Bbox + + .. note:: + This parameter exists for historic reasons and is considered + internal. End users should not use it. + + If not ``None``, this defines the position of the + Axes within the figure as a Bbox. See `~.Axes.get_position` + for further details. + + Notes + ----- + This is called automatically when each Axes is drawn. You may need + to call it yourself if you need to update the Axes position and/or + view limits before the Figure is drawn. + + An alternative with a broader scope is `.Figure.draw_without_rendering`, + which updates all stale components of a figure, not only the positioning / + view limits of a single Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect ratio handling. + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + matplotlib.figure.Figure.draw_without_rendering + Update all stale components of a figure. + + Examples + -------- + A typical usage example would be the following. `~.Axes.imshow` sets the + aspect to 1, but adapting the Axes position and extent to reflect this is + deferred until rendering for performance reasons. If you want to know the + Axes size before, you need to call `.apply_aspect` to get the correct + values. + + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.zeros((3, 3))) + >>> ax.bbox.width, ax.bbox.height + (496.0, 369.59999999999997) + >>> ax.apply_aspect() + >>> ax.bbox.width, ax.bbox.height + (369.59999999999997, 369.59999999999997) + """ + if position is None: + position = self.get_position(original=True) + + aspect = self.get_aspect() + + if aspect == 'auto' and self._box_aspect is None: + self._set_position(position, which='active') + return + + trans = self.get_figure(root=False).transSubfigure + bb = mtransforms.Bbox.unit().transformed(trans) + # this is the physical aspect of the panel (or figure): + fig_aspect = bb.height / bb.width + + if self._adjustable == 'box': + if self in self._twinned_axes: + raise RuntimeError("Adjustable 'box' is not allowed in a " + "twinned Axes; use 'datalim' instead") + box_aspect = aspect * self.get_data_ratio() + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + return + + # The following is only seen if self._adjustable == 'datalim' + if self._box_aspect is not None: + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(self._box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + if aspect == "auto": + return + + # reset active to original in case it had been changed by prior use + # of 'box' + if self._box_aspect is None: + self._set_position(position, which='active') + else: + position = pb1.anchored(self.get_anchor(), pb) + + x_trf = self.xaxis.get_transform() + y_trf = self.yaxis.get_transform() + xmin, xmax = x_trf.transform(self.get_xbound()) + ymin, ymax = y_trf.transform(self.get_ybound()) + xsize = max(abs(xmax - xmin), 1e-30) + ysize = max(abs(ymax - ymin), 1e-30) + + box_aspect = fig_aspect * (position.height / position.width) + data_ratio = box_aspect / aspect + + y_expander = data_ratio * xsize / ysize - 1 + # If y_expander > 0, the dy/dx viewLim ratio needs to increase + if abs(y_expander) < 0.005: + return + + dL = self.dataLim + x0, x1 = x_trf.transform(dL.intervalx) + y0, y1 = y_trf.transform(dL.intervaly) + xr = 1.05 * (x1 - x0) + yr = 1.05 * (y1 - y0) + + xmarg = xsize - xr + ymarg = ysize - yr + Ysize = data_ratio * xsize + Xsize = ysize / data_ratio + Xmarg = Xsize - xr + Ymarg = Ysize - yr + # Setting these targets to, e.g., 0.05*xr does not seem to help. + xm = 0 + ym = 0 + + shared_x = self in self._shared_axes["x"] + shared_y = self in self._shared_axes["y"] + + if shared_x and shared_y: + raise RuntimeError("set_aspect(..., adjustable='datalim') or " + "axis('equal') are not allowed when both axes " + "are shared. Try set_aspect(..., " + "adjustable='box').") + + # If y is shared, then we are only allowed to change x, etc. + if shared_y: + adjust_y = False + else: + if xmarg > xm and ymarg > ym: + adjy = ((Ymarg > 0 and y_expander < 0) or + (Xmarg < 0 and y_expander > 0)) + else: + adjy = y_expander > 0 + adjust_y = shared_x or adjy # (Ymarg > xmarg) + + if adjust_y: + yc = 0.5 * (ymin + ymax) + y0 = yc - Ysize / 2.0 + y1 = yc + Ysize / 2.0 + if not self.get_autoscaley_on(): + _log.warning("Ignoring fixed y limits to fulfill fixed data aspect " + "with adjustable data limits.") + self.set_ybound(y_trf.inverted().transform([y0, y1])) + else: + xc = 0.5 * (xmin + xmax) + x0 = xc - Xsize / 2.0 + x1 = xc + Xsize / 2.0 + if not self.get_autoscalex_on(): + _log.warning("Ignoring fixed x limits to fulfill fixed data aspect " + "with adjustable data limits.") + self.set_xbound(x_trf.inverted().transform([x0, x1])) + + def axis(self, arg=None, /, *, emit=True, **kwargs): + """ + Convenience method to get or set some axis properties. + + Call signatures:: + + xmin, xmax, ymin, ymax = axis() + xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax]) + xmin, xmax, ymin, ymax = axis(option) + xmin, xmax, ymin, ymax = axis(**kwargs) + + Parameters + ---------- + xmin, xmax, ymin, ymax : float, optional + The axis limits to be set. This can also be achieved using :: + + ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax)) + + option : bool or str + If a bool, turns axis lines and labels on or off. If a string, + possible values are: + + ================ =========================================================== + Value Description + ================ =========================================================== + 'off' or `False` Hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_off()`. + 'on' or `True` Do not hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_on()`. + 'equal' Set equal scaling (i.e., make circles circular) by + changing the axis limits. This is the same as + ``ax.set_aspect('equal', adjustable='datalim')``. + Explicit data limits may not be respected in this case. + 'scaled' Set equal scaling (i.e., make circles circular) by + changing dimensions of the plot box. This is the same as + ``ax.set_aspect('equal', adjustable='box', anchor='C')``. + Additionally, further autoscaling will be disabled. + 'tight' Set limits just large enough to show all data, then + disable further autoscaling. + 'auto' Automatic scaling (fill plot box with data). + 'image' 'scaled' with axis limits equal to data limits. + 'square' Square plot; similar to 'scaled', but initially forcing + ``xmax-xmin == ymax-ymin``. + ================ =========================================================== + + emit : bool, default: True + Whether observers are notified of the axis limit change. + This option is passed on to `~.Axes.set_xlim` and + `~.Axes.set_ylim`. + + Returns + ------- + xmin, xmax, ymin, ymax : float + The axis limits. + + See Also + -------- + matplotlib.axes.Axes.set_xlim + matplotlib.axes.Axes.set_ylim + + Notes + ----- + For 3D Axes, this method additionally takes *zmin*, *zmax* as + parameters and likewise returns them. + """ + if isinstance(arg, (str, bool)): + if arg is True: + arg = 'on' + if arg is False: + arg = 'off' + arg = arg.lower() + if arg == 'on': + self.set_axis_on() + elif arg == 'off': + self.set_axis_off() + elif arg in [ + 'equal', 'tight', 'scaled', 'auto', 'image', 'square']: + self.set_autoscale_on(True) + self.set_aspect('auto') + self.autoscale_view(tight=False) + if arg == 'equal': + self.set_aspect('equal', adjustable='datalim') + elif arg == 'scaled': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) # Req. by Mark Bakker + elif arg == 'tight': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + elif arg == 'image': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + self.set_aspect('equal', adjustable='box', anchor='C') + elif arg == 'square': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) + xlim = self.get_xlim() + ylim = self.get_ylim() + edge_size = max(np.diff(xlim), np.diff(ylim))[0] + self.set_xlim([xlim[0], xlim[0] + edge_size], + emit=emit, auto=False) + self.set_ylim([ylim[0], ylim[0] + edge_size], + emit=emit, auto=False) + else: + raise ValueError(f"Unrecognized string {arg!r} to axis; " + "try 'on' or 'off'") + else: + if arg is not None: + if len(arg) != 2*len(self._axis_names): + raise TypeError( + "The first argument to axis() must be an iterable of the form " + "[{}]".format(", ".join( + f"{name}min, {name}max" for name in self._axis_names))) + limits = { + name: arg[2*i:2*(i+1)] + for i, name in enumerate(self._axis_names) + } + else: + limits = {} + for name in self._axis_names: + ax_min = kwargs.pop(f'{name}min', None) + ax_max = kwargs.pop(f'{name}max', None) + limits[name] = (ax_min, ax_max) + for name, (ax_min, ax_max) in limits.items(): + ax_auto = (None # Keep autoscale state as is. + if ax_min is None and ax_max is None + else False) # Turn off autoscale. + set_ax_lim = getattr(self, f'set_{name}lim') + set_ax_lim(ax_min, ax_max, emit=emit, auto=ax_auto) + if kwargs: + raise _api.kwarg_error("axis", kwargs) + lims = () + for name in self._axis_names: + get_ax_lim = getattr(self, f'get_{name}lim') + lims += get_ax_lim() + return lims + + def get_legend(self): + """Return the `.Legend` instance, or None if no legend is defined.""" + return self.legend_ + + def get_images(self): + r"""Return a list of `.AxesImage`\s contained by the Axes.""" + return cbook.silent_list('AxesImage', self.images) + + def get_lines(self): + """Return a list of lines contained by the Axes.""" + return cbook.silent_list('Line2D', self.lines) + + def get_xaxis(self): + """ + [*Discouraged*] Return the XAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute `~.Axes.xaxis`. + """ + return self.xaxis + + def get_yaxis(self): + """ + [*Discouraged*] Return the YAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute `~.Axes.yaxis`. + """ + return self.yaxis + + get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines") + get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines") + get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines") + get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines") + + # Adding and tracking artists + + def _sci(self, im): + """ + Set the current image. + + This image will be the target of colormap functions like + ``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The + current image is an attribute of the current Axes. + """ + _api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im) + if im not in self._children: + raise ValueError("Argument must be an image or collection in this Axes") + self._current_image = im + + def _gci(self): + """Helper for `~matplotlib.pyplot.gci`; do not use elsewhere.""" + return self._current_image + + def has_data(self): + """ + Return whether any artists have been added to the Axes. + + This should not be used to determine whether the *dataLim* + need to be updated, and may not actually be useful for + anything. + """ + return any(isinstance(a, (mcoll.Collection, mimage.AxesImage, + mlines.Line2D, mpatches.Patch)) + for a in self._children) + + def add_artist(self, a): + """ + Add an `.Artist` to the Axes; return the artist. + + Use `add_artist` only for artists for which there is no dedicated + "add" method; and if necessary, use a method such as `update_datalim` + to manually update the `~.Axes.dataLim` if the artist is to be included + in autoscaling. + + If no ``transform`` has been specified when creating the artist (e.g. + ``artist.get_transform() == None``) then the transform is set to + ``ax.transData``. + """ + a.axes = self + self._children.append(a) + a._remove_method = self._children.remove + self._set_artist_props(a) + if a.get_clip_path() is None: + a.set_clip_path(self.patch) + self.stale = True + return a + + def add_child_axes(self, ax): + """ + Add an `.Axes` to the Axes' children; return the child Axes. + + This is the lowlevel version. See `.axes.Axes.inset_axes`. + """ + + # normally Axes have themselves as the Axes, but these need to have + # their parent... + # Need to bypass the getter... + ax._axes = self + ax.stale_callback = martist._stale_axes_callback + + self.child_axes.append(ax) + ax._remove_method = functools.partial( + self.get_figure(root=False)._remove_axes, owners=[self.child_axes]) + self.stale = True + return ax + + def add_collection(self, collection, autolim=True): + """ + Add a `.Collection` to the Axes; return the collection. + """ + _api.check_isinstance(mcoll.Collection, collection=collection) + if not collection.get_label(): + collection.set_label(f'_child{len(self._children)}') + self._children.append(collection) + collection._remove_method = self._children.remove + self._set_artist_props(collection) + + if collection.get_clip_path() is None: + collection.set_clip_path(self.patch) + + if autolim: + # Make sure viewLim is not stale (mostly to match + # pre-lazy-autoscale behavior, which is not really better). + self._unstale_viewLim() + datalim = collection.get_datalim(self.transData) + points = datalim.get_points() + if not np.isinf(datalim.minpos).all(): + # By definition, if minpos (minimum positive value) is set + # (i.e., non-inf), then min(points) <= minpos <= max(points), + # and minpos would be superfluous. However, we add minpos to + # the call so that self.dataLim will update its own minpos. + # This ensures that log scales see the correct minimum. + points = np.concatenate([points, [datalim.minpos]]) + self.update_datalim(points) + + self.stale = True + return collection + + def add_image(self, image): + """ + Add an `.AxesImage` to the Axes; return the image. + """ + _api.check_isinstance(mimage.AxesImage, image=image) + self._set_artist_props(image) + if not image.get_label(): + image.set_label(f'_child{len(self._children)}') + self._children.append(image) + image._remove_method = self._children.remove + self.stale = True + return image + + def _update_image_limits(self, image): + xmin, xmax, ymin, ymax = image.get_extent() + self.axes.update_datalim(((xmin, ymin), (xmax, ymax))) + + def add_line(self, line): + """ + Add a `.Line2D` to the Axes; return the line. + """ + _api.check_isinstance(mlines.Line2D, line=line) + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + + self._update_line_limits(line) + if not line.get_label(): + line.set_label(f'_child{len(self._children)}') + self._children.append(line) + line._remove_method = self._children.remove + self.stale = True + return line + + def _add_text(self, txt): + """ + Add a `.Text` to the Axes; return the text. + """ + _api.check_isinstance(mtext.Text, txt=txt) + self._set_artist_props(txt) + self._children.append(txt) + txt._remove_method = self._children.remove + self.stale = True + return txt + + def _update_line_limits(self, line): + """ + Figures out the data limit of the given line, updating `.Axes.dataLim`. + """ + path = line.get_path() + if path.vertices.size == 0: + return + + line_trf = line.get_transform() + + if line_trf == self.transData: + data_path = path + elif any(line_trf.contains_branch_seperately(self.transData)): + # Compute the transform from line coordinates to data coordinates. + trf_to_data = line_trf - self.transData + # If transData is affine we can use the cached non-affine component + # of line's path (since the non-affine part of line_trf is + # entirely encapsulated in trf_to_data). + if self.transData.is_affine: + line_trans_path = line._get_transformed_path() + na_path, _ = line_trans_path.get_transformed_path_and_affine() + data_path = trf_to_data.transform_path_affine(na_path) + else: + data_path = trf_to_data.transform_path(path) + else: + # For backwards compatibility we update the dataLim with the + # coordinate range of the given path, even though the coordinate + # systems are completely different. This may occur in situations + # such as when ax.transAxes is passed through for absolute + # positioning. + data_path = path + + if not data_path.vertices.size: + return + + updatex, updatey = line_trf.contains_branch_seperately(self.transData) + if self.name != "rectilinear": + # This block is mostly intended to handle axvline in polar plots, + # for which updatey would otherwise be True. + if updatex and line_trf == self.get_yaxis_transform(): + updatex = False + if updatey and line_trf == self.get_xaxis_transform(): + updatey = False + self.dataLim.update_from_path(data_path, + self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def add_patch(self, p): + """ + Add a `.Patch` to the Axes; return the patch. + """ + _api.check_isinstance(mpatches.Patch, p=p) + self._set_artist_props(p) + if p.get_clip_path() is None: + p.set_clip_path(self.patch) + self._update_patch_limits(p) + self._children.append(p) + p._remove_method = self._children.remove + return p + + def _update_patch_limits(self, patch): + """Update the data limits for the given patch.""" + # hist can add zero height Rectangles, which is useful to keep + # the bins, counts and patches lined up, but it throws off log + # scaling. We'll ignore rects with zero height or width in + # the auto-scaling + + # cannot check for '==0' since unitized data may not compare to zero + # issue #2150 - we update the limits if patch has non zero width + # or height. + if (isinstance(patch, mpatches.Rectangle) and + ((not patch.get_width()) and (not patch.get_height()))): + return + p = patch.get_path() + # Get all vertices on the path + # Loop through each segment to get extrema for Bezier curve sections + vertices = [] + for curve, code in p.iter_bezier(simplify=False): + # Get distance along the curve of any extrema + _, dzeros = curve.axis_aligned_extrema() + # Calculate vertices of start, end and any extrema in between + vertices.append(curve([0, *dzeros, 1])) + + if len(vertices): + vertices = np.vstack(vertices) + + patch_trf = patch.get_transform() + updatex, updatey = patch_trf.contains_branch_seperately(self.transData) + if not (updatex or updatey): + return + if self.name != "rectilinear": + # As in _update_line_limits, but for axvspan. + if updatex and patch_trf == self.get_yaxis_transform(): + updatex = False + if updatey and patch_trf == self.get_xaxis_transform(): + updatey = False + trf_to_data = patch_trf - self.transData + xys = trf_to_data.transform(vertices) + self.update_datalim(xys, updatex=updatex, updatey=updatey) + + def add_table(self, tab): + """ + Add a `.Table` to the Axes; return the table. + """ + _api.check_isinstance(mtable.Table, tab=tab) + self._set_artist_props(tab) + self._children.append(tab) + if tab.get_clip_path() is None: + tab.set_clip_path(self.patch) + tab._remove_method = self._children.remove + return tab + + def add_container(self, container): + """ + Add a `.Container` to the Axes' containers; return the container. + """ + label = container.get_label() + if not label: + container.set_label('_container%d' % len(self.containers)) + self.containers.append(container) + container._remove_method = self.containers.remove + return container + + def _unit_change_handler(self, axis_name, event=None): + """ + Process axis units changes: requests updates to data and view limits. + """ + if event is None: # Allow connecting `self._unit_change_handler(name)` + return functools.partial( + self._unit_change_handler, axis_name, event=object()) + _api.check_in_list(self._axis_map, axis_name=axis_name) + for line in self.lines: + line.recache_always() + self.relim() + self._request_autoscale_view(axis_name) + + def relim(self, visible_only=False): + """ + Recompute the data limits based on current artists. + + At present, `.Collection` instances are not supported. + + Parameters + ---------- + visible_only : bool, default: False + Whether to exclude invisible artists. + """ + # Collections are deliberately not supported (yet); see + # the TODO note in artists.py. + self.dataLim.ignore(True) + self.dataLim.set_points(mtransforms.Bbox.null().get_points()) + self.ignore_existing_data_limits = True + + for artist in self._children: + if not visible_only or artist.get_visible(): + if isinstance(artist, mlines.Line2D): + self._update_line_limits(artist) + elif isinstance(artist, mpatches.Patch): + self._update_patch_limits(artist) + elif isinstance(artist, mimage.AxesImage): + self._update_image_limits(artist) + + def update_datalim(self, xys, updatex=True, updatey=True): + """ + Extend the `~.Axes.dataLim` Bbox to include the given points. + + If no data is set currently, the Bbox will ignore its limits and set + the bound to be the bounds of the xydata (*xys*). Otherwise, it will + compute the bounds of the union of its current data and the data in + *xys*. + + Parameters + ---------- + xys : 2D array-like + The points to include in the data limits Bbox. This can be either + a list of (x, y) tuples or a (N, 2) array. + + updatex, updatey : bool, default: True + Whether to update the x/y limits. + """ + xys = np.asarray(xys) + if not np.any(np.isfinite(xys)): + return + self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True): + """ + Set axis units based on *datasets* and *kwargs*, and optionally apply + unit conversions to *datasets*. + + Parameters + ---------- + datasets : list + List of (axis_name, dataset) pairs (where the axis name is defined + as in `._axis_map`). Individual datasets can also be None + (which gets passed through). + kwargs : dict + Other parameters from which unit info (i.e., the *xunits*, + *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for + polar) entries) is popped, if present. Note that this dict is + mutated in-place! + convert : bool, default: True + Whether to return the original datasets or the converted ones. + + Returns + ------- + list + Either the original datasets if *convert* is False, or the + converted ones if *convert* is True (the default). + """ + # The API makes datasets a list of pairs rather than an axis_name to + # dataset mapping because it is sometimes necessary to process multiple + # datasets for a single axis, and concatenating them may be tricky + # (e.g. if some are scalars, etc.). + datasets = datasets or [] + kwargs = kwargs or {} + axis_map = self._axis_map + for axis_name, data in datasets: + try: + axis = axis_map[axis_name] + except KeyError: + raise ValueError(f"Invalid axis name: {axis_name!r}") from None + # Update from data if axis is already set but no unit is set yet. + if axis is not None and data is not None and not axis.have_units(): + axis.update_units(data) + for axis_name, axis in axis_map.items(): + # Return if no axis is set. + if axis is None: + continue + # Check for units in the kwargs, and if present update axis. + units = kwargs.pop(f"{axis_name}units", axis.units) + if self.name == "polar": + # Special case: polar supports "thetaunits"/"runits". + polar_units = {"x": "thetaunits", "y": "runits"} + units = kwargs.pop(polar_units[axis_name], units) + if units != axis.units and units is not None: + axis.set_units(units) + # If the units being set imply a different converter, + # we need to update again. + for dataset_axis_name, data in datasets: + if dataset_axis_name == axis_name and data is not None: + axis.update_units(data) + return [axis_map[axis_name].convert_units(data) + if convert and data is not None else data + for axis_name, data in datasets] + + def in_axes(self, mouseevent): + """ + Return whether the given event (in display coords) is in the Axes. + """ + return self.patch.contains(mouseevent)[0] + + get_autoscalex_on = _axis_method_wrapper("xaxis", "_get_autoscale_on") + get_autoscaley_on = _axis_method_wrapper("yaxis", "_get_autoscale_on") + set_autoscalex_on = _axis_method_wrapper("xaxis", "_set_autoscale_on") + set_autoscaley_on = _axis_method_wrapper("yaxis", "_set_autoscale_on") + + def get_autoscale_on(self): + """Return True if each axis is autoscaled, False otherwise.""" + return all(axis._get_autoscale_on() + for axis in self._axis_map.values()) + + def set_autoscale_on(self, b): + """ + Set whether autoscaling is applied to each axis on the next draw or + call to `.Axes.autoscale_view`. + + Parameters + ---------- + b : bool + """ + for axis in self._axis_map.values(): + axis._set_autoscale_on(b) + + @property + def use_sticky_edges(self): + """ + When autoscaling, whether to obey all `.Artist.sticky_edges`. + + Default is ``True``. + + Setting this to ``False`` ensures that the specified margins + will be applied, even if the plot includes an image, for + example, which would otherwise force a view limit to coincide + with its data limit. + + The changing this property does not change the plot until + `autoscale` or `autoscale_view` is called. + """ + return self._use_sticky_edges + + @use_sticky_edges.setter + def use_sticky_edges(self, b): + self._use_sticky_edges = bool(b) + # No effect until next autoscaling, which will mark the Axes as stale. + + def get_xmargin(self): + """ + Retrieve autoscaling margin of the x-axis. + + .. versionadded:: 3.9 + + Returns + ------- + xmargin : float + + See Also + -------- + matplotlib.axes.Axes.set_xmargin + """ + return self._xmargin + + def get_ymargin(self): + """ + Retrieve autoscaling margin of the y-axis. + + .. versionadded:: 3.9 + + Returns + ------- + ymargin : float + + See Also + -------- + matplotlib.axes.Axes.set_ymargin + """ + return self._ymargin + + def set_xmargin(self, m): + """ + Set padding of X data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._xmargin = m + self._request_autoscale_view("x") + self.stale = True + + def set_ymargin(self, m): + """ + Set padding of Y data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._ymargin = m + self._request_autoscale_view("y") + self.stale = True + + def margins(self, *margins, x=None, y=None, tight=True): + """ + Set or retrieve margins around the data for autoscaling axis limits. + + This allows to configure the padding around the data without having to + set explicit limits using `~.Axes.set_xlim` / `~.Axes.set_ylim`. + + Autoscaling determines the axis limits by adding *margin* times the + data interval as padding around the data. See the following illustration: + + .. plot:: _embedded_plots/axes_margins.py + + All input parameters must be floats greater than -0.5. Passing both + positional and keyword arguments is invalid and will raise a TypeError. + If no arguments (positional or otherwise) are provided, the current + margins will remain unchanged and simply be returned. + + The default margins are :rc:`axes.xmargin` and :rc:`axes.ymargin`. + + Parameters + ---------- + *margins : float, optional + If a single positional argument is provided, it specifies + both margins of the x-axis and y-axis limits. If two + positional arguments are provided, they will be interpreted + as *xmargin*, *ymargin*. If setting the margin on a single + axis is desired, use the keyword arguments described below. + + x, y : float, optional + Specific margin values for the x-axis and y-axis, + respectively. These cannot be used with positional + arguments, but can be used individually to alter on e.g., + only the y-axis. + + tight : bool or None, default: True + The *tight* parameter is passed to `~.axes.Axes.autoscale_view`, + which is executed after a margin is changed; the default + here is *True*, on the assumption that when margins are + specified, no additional padding to match tick marks is + usually desired. Setting *tight* to *None* preserves + the previous setting. + + Returns + ------- + xmargin, ymargin : float + + Notes + ----- + If a previously used Axes method such as :meth:`pcolor` has set + `~.Axes.use_sticky_edges` to `True`, only the limits not set by + the "sticky artists" will be modified. To force all + margins to be set, set `~.Axes.use_sticky_edges` to `False` + before calling :meth:`margins`. + + See Also + -------- + .Axes.set_xmargin, .Axes.set_ymargin + """ + + if margins and (x is not None or y is not None): + raise TypeError('Cannot pass both positional and keyword ' + 'arguments for x and/or y.') + elif len(margins) == 1: + x = y = margins[0] + elif len(margins) == 2: + x, y = margins + elif margins: + raise TypeError('Must pass a single positional argument for all ' + 'margins, or one for each margin (x, y).') + + if x is None and y is None: + if tight is not True: + _api.warn_external(f'ignoring tight={tight!r} in get mode') + return self._xmargin, self._ymargin + + if tight is not None: + self._tight = tight + if x is not None: + self.set_xmargin(x) + if y is not None: + self.set_ymargin(y) + + def set_rasterization_zorder(self, z): + """ + Set the zorder threshold for rasterization for vector graphics output. + + All artists with a zorder below the given value will be rasterized if + they support rasterization. + + This setting is ignored for pixel-based output. + + See also :doc:`/gallery/misc/rasterization_demo`. + + Parameters + ---------- + z : float or None + The zorder below which artists are rasterized. + If ``None`` rasterization based on zorder is deactivated. + """ + self._rasterization_zorder = z + self.stale = True + + def get_rasterization_zorder(self): + """Return the zorder value below which artists will be rasterized.""" + return self._rasterization_zorder + + def autoscale(self, enable=True, axis='both', tight=None): + """ + Autoscale the axis view to the data (toggle). + + Convenience method for simple axis view autoscaling. + It turns autoscaling on or off, and then, + if autoscaling for either axis is on, it performs + the autoscaling on the specified axis or Axes. + + Parameters + ---------- + enable : bool or None, default: True + True turns autoscaling on, False turns it off. + None leaves the autoscaling state unchanged. + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be set + to 'z', and 'both' refers to all three Axes.) + tight : bool or None, default: None + If True, first set the margins to zero. Then, this argument is + forwarded to `~.axes.Axes.autoscale_view` (regardless of + its value); see the description of its behavior there. + """ + if enable is None: + scalex = True + scaley = True + else: + if axis in ['x', 'both']: + self.set_autoscalex_on(bool(enable)) + scalex = self.get_autoscalex_on() + else: + scalex = False + if axis in ['y', 'both']: + self.set_autoscaley_on(bool(enable)) + scaley = self.get_autoscaley_on() + else: + scaley = False + if tight and scalex: + self._xmargin = 0 + if tight and scaley: + self._ymargin = 0 + if scalex: + self._request_autoscale_view("x", tight=tight) + if scaley: + self._request_autoscale_view("y", tight=tight) + + def autoscale_view(self, tight=None, scalex=True, scaley=True): + """ + Autoscale the view limits using the data limits. + + Parameters + ---------- + tight : bool or None + If *True*, only expand the axis limits using the margins. Note + that unlike for `autoscale`, ``tight=True`` does *not* set the + margins to zero. + + If *False* and :rc:`axes.autolimit_mode` is 'round_numbers', then + after expansion by the margins, further expand the axis limits + using the axis major locator. + + If None (the default), reuse the value set in the previous call to + `autoscale_view` (the initial value is False, but the default style + sets :rc:`axes.autolimit_mode` to 'data', in which case this + behaves like True). + + scalex : bool, default: True + Whether to autoscale the x-axis. + + scaley : bool, default: True + Whether to autoscale the y-axis. + + Notes + ----- + The autoscaling preserves any preexisting axis direction reversal. + + The data limits are not updated automatically when artist data are + changed after the artist has been added to an Axes instance. In that + case, use :meth:`matplotlib.axes.Axes.relim` prior to calling + autoscale_view. + + If the views of the Axes are fixed, e.g. via `set_xlim`, they will + not be changed by autoscale_view(). + See :meth:`matplotlib.axes.Axes.autoscale` for an alternative. + """ + if tight is not None: + self._tight = bool(tight) + + x_stickies = y_stickies = np.array([]) + if self.use_sticky_edges: + if self._xmargin and scalex and self.get_autoscalex_on(): + x_stickies = np.sort(np.concatenate([ + artist.sticky_edges.x + for ax in self._shared_axes["x"].get_siblings(self) + for artist in ax.get_children()])) + if self._ymargin and scaley and self.get_autoscaley_on(): + y_stickies = np.sort(np.concatenate([ + artist.sticky_edges.y + for ax in self._shared_axes["y"].get_siblings(self) + for artist in ax.get_children()])) + if self.get_xscale() == 'log': + x_stickies = x_stickies[x_stickies > 0] + if self.get_yscale() == 'log': + y_stickies = y_stickies[y_stickies > 0] + + def handle_single_axis( + scale, shared_axes, name, axis, margin, stickies, set_bound): + + if not (scale and axis._get_autoscale_on()): + return # nothing to do... + + shared = shared_axes.get_siblings(self) + # Base autoscaling on finite data limits when there is at least one + # finite data limit among all the shared_axes and intervals. + values = [val for ax in shared + for val in getattr(ax.dataLim, f"interval{name}") + if np.isfinite(val)] + if values: + x0, x1 = (min(values), max(values)) + elif getattr(self._viewLim, f"mutated{name}")(): + # No data, but explicit viewLims already set: + # in mutatedx or mutatedy. + return + else: + x0, x1 = (-np.inf, np.inf) + # If x0 and x1 are nonfinite, get default limits from the locator. + locator = axis.get_major_locator() + x0, x1 = locator.nonsingular(x0, x1) + # Find the minimum minpos for use in the margin calculation. + minimum_minpos = min( + getattr(ax.dataLim, f"minpos{name}") for ax in shared) + + # Prevent margin addition from crossing a sticky value. A small + # tolerance must be added due to floating point issues with + # streamplot; it is defined relative to x1-x0 but has + # no absolute term (e.g. "+1e-8") to avoid issues when working with + # datasets where all values are tiny (less than 1e-8). + tol = 1e-5 * abs(x1 - x0) + # Index of largest element < x0 + tol, if any. + i0 = stickies.searchsorted(x0 + tol) - 1 + x0bound = stickies[i0] if i0 != -1 else None + # Index of smallest element > x1 - tol, if any. + i1 = stickies.searchsorted(x1 - tol) + x1bound = stickies[i1] if i1 != len(stickies) else None + + # Add the margin in figure space and then transform back, to handle + # non-linear scales. + transform = axis.get_transform() + inverse_trans = transform.inverted() + x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos) + x0t, x1t = transform.transform([x0, x1]) + delta = (x1t - x0t) * margin + if not np.isfinite(delta): + delta = 0 # If a bound isn't finite, set margin to zero. + x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta]) + + # Apply sticky bounds. + if x0bound is not None: + x0 = max(x0, x0bound) + if x1bound is not None: + x1 = min(x1, x1bound) + + if not self._tight: + x0, x1 = locator.view_limits(x0, x1) + set_bound(x0, x1) + # End of definition of internal function 'handle_single_axis'. + + handle_single_axis( + scalex, self._shared_axes["x"], 'x', self.xaxis, self._xmargin, + x_stickies, self.set_xbound) + handle_single_axis( + scaley, self._shared_axes["y"], 'y', self.yaxis, self._ymargin, + y_stickies, self.set_ybound) + + def _update_title_position(self, renderer): + """ + Update the title position based on the bounding box enclosing + all the ticklabels and x-axis spine and xlabel... + """ + if self._autotitlepos is not None and not self._autotitlepos: + _log.debug('title position was updated manually, not adjusting') + return + + titles = (self.title, self._left_title, self._right_title) + + if not any(title.get_text() for title in titles): + # If the titles are all empty, there is no need to update their positions. + return + + # Need to check all our twins too, aligned axes, and all the children + # as well. + axs = set() + axs.update(self.child_axes) + axs.update(self._twinned_axes.get_siblings(self)) + axs.update( + self.get_figure(root=False)._align_label_groups['title'].get_siblings(self)) + + for ax in self.child_axes: # Child positions must be updated first. + locator = ax.get_axes_locator() + ax.apply_aspect(locator(self, renderer) if locator else None) + + top = -np.inf + for ax in axs: + bb = None + if (ax.xaxis.get_ticks_position() in ['top', 'unknown'] or + ax.xaxis.get_label_position() == 'top'): + bb = ax.xaxis.get_tightbbox(renderer) + if bb is None: + # Extent of the outline for colorbars, of the axes otherwise. + bb = ax.spines.get("outline", ax).get_window_extent() + top = max(top, bb.ymax) + + for title in titles: + x, _ = title.get_position() + # need to start again in case of window resizing + title.set_position((x, 1.0)) + if title.get_text(): + for ax in axs: + ax.yaxis.get_tightbbox(renderer) # update offsetText + if ax.yaxis.offsetText.get_text(): + bb = ax.yaxis.offsetText.get_tightbbox(renderer) + if bb.intersection(title.get_tightbbox(renderer), bb): + top = bb.ymax + if top < 0: + # the top of Axes is not even on the figure, so don't try and + # automatically place it. + _log.debug('top of Axes not in the figure, so title not moved') + return + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform((0, top)) + title.set_position((x, y)) + # empirically, this doesn't always get the min to top, + # so we need to adjust again. + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform( + (0., 2 * top - title.get_window_extent(renderer).ymin)) + title.set_position((x, y)) + + ymax = max(title.get_position()[1] for title in titles) + for title in titles: + # now line up all the titles at the highest baseline. + x, _ = title.get_position() + title.set_position((x, ymax)) + + # Drawing + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + if renderer is None: + raise RuntimeError('No renderer defined') + if not self.get_visible(): + return + self._unstale_viewLim() + + renderer.open_group('axes', gid=self.get_gid()) + + # prevent triggering call backs during the draw process + self._stale = True + + # loop over self and child Axes... + locator = self.get_axes_locator() + self.apply_aspect(locator(self, renderer) if locator else None) + + artists = self.get_children() + artists.remove(self.patch) + + # the frame draws the edges around the Axes patch -- we + # decouple these so the patch can be in the background and the + # frame in the foreground. Do this before drawing the axis + # objects so that the spine has the opportunity to update them. + if not (self.axison and self._frameon): + for spine in self.spines.values(): + artists.remove(spine) + + self._update_title_position(renderer) + + if not self.axison: + for _axis in self._axis_map.values(): + artists.remove(_axis) + + if not self.get_figure(root=True).canvas.is_saving(): + artists = [ + a for a in artists + if not a.get_animated() or isinstance(a, mimage.AxesImage)] + artists = sorted(artists, key=attrgetter('zorder')) + + # rasterize artists with negative zorder + # if the minimum zorder is negative, start rasterization + rasterization_zorder = self._rasterization_zorder + + if (rasterization_zorder is not None and + artists and artists[0].zorder < rasterization_zorder): + split_index = np.searchsorted( + [art.zorder for art in artists], + rasterization_zorder, side='right' + ) + artists_rasterized = artists[:split_index] + artists = artists[split_index:] + else: + artists_rasterized = [] + + if self.axison and self._frameon: + if artists_rasterized: + artists_rasterized = [self.patch] + artists_rasterized + else: + artists = [self.patch] + artists + + if artists_rasterized: + _draw_rasterized(self.get_figure(root=True), artists_rasterized, renderer) + + mimage._draw_list_compositing_images( + renderer, self, artists, self.get_figure(root=True).suppressComposite) + + renderer.close_group('axes') + self.stale = False + + def draw_artist(self, a): + """ + Efficiently redraw a single artist. + """ + a.draw(self.get_figure(root=True).canvas.get_renderer()) + + def redraw_in_frame(self): + """ + Efficiently redraw Axes data, but not axis ticks, labels, etc. + """ + with ExitStack() as stack: + for artist in [*self._axis_map.values(), + self.title, self._left_title, self._right_title]: + stack.enter_context(artist._cm_set(visible=False)) + self.draw(self.get_figure(root=True).canvas.get_renderer()) + + # Axes rectangle characteristics + + def get_frame_on(self): + """Get whether the Axes rectangle patch is drawn.""" + return self._frameon + + def set_frame_on(self, b): + """ + Set whether the Axes rectangle patch is drawn. + + Parameters + ---------- + b : bool + """ + self._frameon = b + self.stale = True + + def get_axisbelow(self): + """ + Get whether axis ticks and gridlines are above or below most artists. + + Returns + ------- + bool or 'line' + + See Also + -------- + set_axisbelow + """ + return self._axisbelow + + def set_axisbelow(self, b): + """ + Set whether axis ticks and gridlines are above or below most artists. + + This controls the zorder of the ticks and gridlines. For more + information on the zorder see :doc:`/gallery/misc/zorder_demo`. + + Parameters + ---------- + b : bool or 'line' + Possible values: + + - *True* (zorder = 0.5): Ticks and gridlines are below patches and + lines, though still above images. + - 'line' (zorder = 1.5): Ticks and gridlines are above patches + (e.g. rectangles, with default zorder = 1) but still below lines + and markers (with their default zorder = 2). + - *False* (zorder = 2.5): Ticks and gridlines are above patches + and lines / markers. + + Notes + ----- + For more control, call the `~.Artist.set_zorder` method of each axis. + + See Also + -------- + get_axisbelow + """ + # Check that b is True, False or 'line' + self._axisbelow = axisbelow = validate_axisbelow(b) + zorder = { + True: 0.5, + 'line': 1.5, + False: 2.5, + }[axisbelow] + for axis in self._axis_map.values(): + axis.set_zorder(zorder) + self.stale = True + + @_docstring.interpd + def grid(self, visible=None, which='major', axis='both', **kwargs): + """ + Configure the grid lines. + + Parameters + ---------- + visible : bool or None, optional + Whether to show the grid lines. If any *kwargs* are supplied, it + is assumed you want the grid on and *visible* will be set to True. + + If *visible* is *None* and there are no *kwargs*, this toggles the + visibility of the lines. + + which : {'major', 'minor', 'both'}, optional + The grid lines to apply the changes on. + + axis : {'both', 'x', 'y'}, optional + The axis to apply the changes on. + + **kwargs : `~matplotlib.lines.Line2D` properties + Define the line properties of the grid, e.g.:: + + grid(color='r', linestyle='-', linewidth=2) + + Valid keyword arguments are: + + %(Line2D:kwdoc)s + + Notes + ----- + The axis is drawn as a unit, so the effective zorder for drawing the + grid is determined by the zorder of each axis, not by the zorder of the + `.Line2D` objects comprising the grid. Therefore, to set grid zorder, + use `.set_axisbelow` or, for more control, call the + `~.Artist.set_zorder` method of each axis. + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + self.xaxis.grid(visible, which=which, **kwargs) + if axis in ['y', 'both']: + self.yaxis.grid(visible, which=which, **kwargs) + + def ticklabel_format(self, *, axis='both', style=None, scilimits=None, + useOffset=None, useLocale=None, useMathText=None): + r""" + Configure the `.ScalarFormatter` used by default for linear Axes. + + If a parameter is not set, the corresponding property of the formatter + is left unchanged. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to configure. Only major ticks are affected. + + style : {'sci', 'scientific', 'plain'} + Whether to use scientific notation. + The formatter default is to use scientific notation. + 'sci' is equivalent to 'scientific'. + + scilimits : pair of ints (m, n) + Scientific notation is used only for numbers outside the range + 10\ :sup:`m` to 10\ :sup:`n` (and only if the formatter is + configured to use scientific notation at all). Use (0, 0) to + include all numbers. Use (m, m) where m != 0 to fix the order of + magnitude to 10\ :sup:`m`. + The formatter default is :rc:`axes.formatter.limits`. + + useOffset : bool or float + If True, the offset is calculated as needed. + If False, no offset is used. + If a numeric value, it sets the offset. + The formatter default is :rc:`axes.formatter.useoffset`. + + useLocale : bool + Whether to format the number using the current locale or using the + C (English) locale. This affects e.g. the decimal separator. The + formatter default is :rc:`axes.formatter.use_locale`. + + useMathText : bool + Render the offset and scientific notation in mathtext. + The formatter default is :rc:`axes.formatter.use_mathtext`. + + Raises + ------ + AttributeError + If the current formatter is not a `.ScalarFormatter`. + """ + if isinstance(style, str): + style = style.lower() + axis = axis.lower() + if scilimits is not None: + try: + m, n = scilimits + m + n + 1 # check that both are numbers + except (ValueError, TypeError) as err: + raise ValueError("scilimits must be a sequence of 2 integers" + ) from err + STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None, None: None} + # The '' option is included for backwards-compatibility. + is_sci_style = _api.check_getitem(STYLES, style=style) + axis_map = {**{k: [v] for k, v in self._axis_map.items()}, + 'both': list(self._axis_map.values())} + axises = _api.check_getitem(axis_map, axis=axis) + try: + for axis in axises: + if is_sci_style is not None: + axis.major.formatter.set_scientific(is_sci_style) + if scilimits is not None: + axis.major.formatter.set_powerlimits(scilimits) + if useOffset is not None: + axis.major.formatter.set_useOffset(useOffset) + if useLocale is not None: + axis.major.formatter.set_useLocale(useLocale) + if useMathText is not None: + axis.major.formatter.set_useMathText(useMathText) + except AttributeError as err: + raise AttributeError( + "This method only works with the ScalarFormatter") from err + + def locator_params(self, axis='both', tight=None, **kwargs): + """ + Control behavior of major tick locators. + + Because the locator is involved in autoscaling, `~.Axes.autoscale_view` + is called automatically after the parameters are changed. + + Parameters + ---------- + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be + set to 'z', and 'both' refers to all three axes.) + tight : bool or None, optional + Parameter passed to `~.Axes.autoscale_view`. + Default is None, for no change. + + Other Parameters + ---------------- + **kwargs + Remaining keyword arguments are passed to directly to the + ``set_params()`` method of the locator. Supported keywords depend + on the type of the locator. See for example + `~.ticker.MaxNLocator.set_params` for the `.ticker.MaxNLocator` + used by default for linear. + + Examples + -------- + When plotting small subplots, one might want to reduce the maximum + number of ticks and use tight bounds, for example:: + + ax.locator_params(tight=True, nbins=4) + + """ + _api.check_in_list([*self._axis_names, "both"], axis=axis) + for name in self._axis_names: + if axis in [name, "both"]: + loc = self._axis_map[name].get_major_locator() + loc.set_params(**kwargs) + self._request_autoscale_view(name, tight=tight) + self.stale = True + + def tick_params(self, axis='both', **kwargs): + """ + Change the appearance of ticks, tick labels, and gridlines. + + Tick properties that are not explicitly set using the keyword + arguments remain unchanged unless *reset* is True. For the current + style settings, see `.Axis.get_tick_params`. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to which the parameters are applied. + which : {'major', 'minor', 'both'}, default: 'major' + The group of ticks to which the parameters are applied. + reset : bool, default: False + Whether to reset the ticks to defaults before updating them. + + Other Parameters + ---------------- + direction : {'in', 'out', 'inout'} + Puts ticks inside the Axes, outside the Axes, or both. + length : float + Tick length in points. + width : float + Tick width in points. + color : :mpltype:`color` + Tick color. + pad : float + Distance in points between tick and label. + labelsize : float or str + Tick label font size in points or as a string (e.g., 'large'). + labelcolor : :mpltype:`color` + Tick label color. + labelfontfamily : str + Tick label font. + colors : :mpltype:`color` + Tick color and label color. + zorder : float + Tick and label zorder. + bottom, top, left, right : bool + Whether to draw the respective ticks. + labelbottom, labeltop, labelleft, labelright : bool + Whether to draw the respective tick labels. + labelrotation : float + Tick label rotation + grid_color : :mpltype:`color` + Gridline color. + grid_alpha : float + Transparency of gridlines: 0 (transparent) to 1 (opaque). + grid_linewidth : float + Width of gridlines in points. + grid_linestyle : str + Any valid `.Line2D` line style spec. + + Examples + -------- + :: + + ax.tick_params(direction='out', length=6, width=2, colors='r', + grid_color='r', grid_alpha=0.5) + + This will make all major ticks be red, pointing out of the box, + and with dimensions 6 points by 2 points. Tick labels will + also be red. Gridlines will be red and translucent. + + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + xkw = dict(kwargs) + xkw.pop('left', None) + xkw.pop('right', None) + xkw.pop('labelleft', None) + xkw.pop('labelright', None) + self.xaxis.set_tick_params(**xkw) + if axis in ['y', 'both']: + ykw = dict(kwargs) + ykw.pop('top', None) + ykw.pop('bottom', None) + ykw.pop('labeltop', None) + ykw.pop('labelbottom', None) + self.yaxis.set_tick_params(**ykw) + + def set_axis_off(self): + """ + Hide all visual components of the x- and y-axis. + + This sets a flag to suppress drawing of all axis decorations, i.e. + axis labels, axis spines, and the axis tick component (tick markers, + tick labels, and grid lines). Individual visibility settings of these + components are ignored as long as `set_axis_off()` is in effect. + """ + self.axison = False + self.stale = True + + def set_axis_on(self): + """ + Do not hide all visual components of the x- and y-axis. + + This reverts the effect of a prior `.set_axis_off()` call. Whether the + individual axis decorations are drawn is controlled by their respective + visibility settings. + + This is on by default. + """ + self.axison = True + self.stale = True + + # data limits, ticks, tick labels, and formatting + + def get_xlabel(self): + """ + Get the xlabel text string. + """ + label = self.xaxis.label + return label.get_text() + + def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the x-axis. + + Parameters + ---------- + xlabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *x* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.xaxis.labelpad = labelpad + protected_kw = ['x', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['xaxis.labellocation']) + _api.check_in_list(('left', 'center', 'right'), loc=loc) + + x = { + 'left': 0, + 'center': 0.5, + 'right': 1, + }[loc] + kwargs.update(x=x, horizontalalignment=loc) + + return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) + + def invert_xaxis(self): + """ + Invert the x-axis. + + See Also + -------- + xaxis_inverted + get_xlim, set_xlim + get_xbound, set_xbound + """ + self.xaxis.set_inverted(not self.xaxis.get_inverted()) + + xaxis_inverted = _axis_method_wrapper("xaxis", "get_inverted") + + def get_xbound(self): + """ + Return the lower and upper x-axis bounds, in increasing order. + + See Also + -------- + set_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + left, right = self.get_xlim() + if left < right: + return left, right + else: + return right, left + + def set_xbound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the x-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscalex_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_xbound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_xlim(sorted((lower, upper), + reverse=bool(self.xaxis_inverted())), + auto=None) + + def get_xlim(self): + """ + Return the x-axis view limits. + + Returns + ------- + left, right : (float, float) + The current x-axis limits in data coordinates. + + See Also + -------- + .Axes.set_xlim + .Axes.set_xbound, .Axes.get_xbound + .Axes.invert_xaxis, .Axes.xaxis_inverted + + Notes + ----- + The x-axis may be inverted, in which case the *left* value will + be greater than the *right* value. + """ + return tuple(self.viewLim.intervalx) + + def _validate_converted_limits(self, limit, convert): + """ + Raise ValueError if converted limits are non-finite. + + Note that this function also accepts None as a limit argument. + + Returns + ------- + The limit value after call to convert(), or None if limit is None. + """ + if limit is not None: + converted_limit = convert(limit) + if isinstance(converted_limit, np.ndarray): + converted_limit = converted_limit.squeeze() + if (isinstance(converted_limit, Real) + and not np.isfinite(converted_limit)): + raise ValueError("Axis limits cannot be NaN or Inf") + return converted_limit + + def set_xlim(self, left=None, right=None, *, emit=True, auto=False, + xmin=None, xmax=None): + """ + Set the x-axis view limits. + + Parameters + ---------- + left : float, optional + The left xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + The left and right xlims may also be passed as the tuple + (*left*, *right*) as the first positional argument (or as + the *left* keyword argument). + + .. ACCEPTS: (left: float, right: float) + + right : float, optional + The right xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. True turns on, + False turns off, None leaves unchanged. + + xmin, xmax : float, optional + They are equivalent to left and right respectively, and it is an + error to pass both *xmin* and *left* or *xmax* and *right*. + + Returns + ------- + left, right : (float, float) + The new x-axis limits in data coordinates. + + See Also + -------- + get_xlim + set_xbound, get_xbound + invert_xaxis, xaxis_inverted + + Notes + ----- + The *left* value may be greater than the *right* value, in which + case the x-axis values will decrease from left to right. + + Examples + -------- + >>> set_xlim(left, right) + >>> set_xlim((left, right)) + >>> left, right = set_xlim(left, right) + + One limit may be left unchanged. + + >>> set_xlim(right=right_lim) + + Limits may be passed in reverse order to flip the direction of + the x-axis. For example, suppose *x* represents the number of + years before present. The x-axis limits might be set like the + following so 5000 years ago is on the left of the plot and the + present is on the right. + + >>> set_xlim(5000, 0) + """ + if right is None and np.iterable(left): + left, right = left + if xmin is not None: + if left is not None: + raise TypeError("Cannot pass both 'left' and 'xmin'") + left = xmin + if xmax is not None: + if right is not None: + raise TypeError("Cannot pass both 'right' and 'xmax'") + right = xmax + return self.xaxis._set_lim(left, right, emit=emit, auto=auto) + + get_xscale = _axis_method_wrapper("xaxis", "get_scale") + set_xscale = _axis_method_wrapper("xaxis", "_set_axes_scale") + get_xticks = _axis_method_wrapper("xaxis", "get_ticklocs") + set_xticks = _axis_method_wrapper("xaxis", "set_ticks", + doc_sub={'set_ticks': 'set_xticks'}) + get_xmajorticklabels = _axis_method_wrapper("xaxis", "get_majorticklabels") + get_xminorticklabels = _axis_method_wrapper("xaxis", "get_minorticklabels") + get_xticklabels = _axis_method_wrapper("xaxis", "get_ticklabels") + set_xticklabels = _axis_method_wrapper( + "xaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_xticks"}) + + def get_ylabel(self): + """ + Get the ylabel text string. + """ + label = self.yaxis.label + return label.get_text() + + def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the y-axis. + + Parameters + ---------- + ylabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *y* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.yaxis.labelpad = labelpad + protected_kw = ['y', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['yaxis.labellocation']) + _api.check_in_list(('bottom', 'center', 'top'), loc=loc) + + y, ha = { + 'bottom': (0, 'left'), + 'center': (0.5, 'center'), + 'top': (1, 'right') + }[loc] + kwargs.update(y=y, horizontalalignment=ha) + + return self.yaxis.set_label_text(ylabel, fontdict, **kwargs) + + def invert_yaxis(self): + """ + Invert the y-axis. + + See Also + -------- + yaxis_inverted + get_ylim, set_ylim + get_ybound, set_ybound + """ + self.yaxis.set_inverted(not self.yaxis.get_inverted()) + + yaxis_inverted = _axis_method_wrapper("yaxis", "get_inverted") + + def get_ybound(self): + """ + Return the lower and upper y-axis bounds, in increasing order. + + See Also + -------- + set_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + bottom, top = self.get_ylim() + if bottom < top: + return bottom, top + else: + return top, bottom + + def set_ybound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the y-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscaley_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_ybound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_ylim(sorted((lower, upper), + reverse=bool(self.yaxis_inverted())), + auto=None) + + def get_ylim(self): + """ + Return the y-axis view limits. + + Returns + ------- + bottom, top : (float, float) + The current y-axis limits in data coordinates. + + See Also + -------- + .Axes.set_ylim + .Axes.set_ybound, .Axes.get_ybound + .Axes.invert_yaxis, .Axes.yaxis_inverted + + Notes + ----- + The y-axis may be inverted, in which case the *bottom* value + will be greater than the *top* value. + """ + return tuple(self.viewLim.intervaly) + + def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, + ymin=None, ymax=None): + """ + Set the y-axis view limits. + + Parameters + ---------- + bottom : float, optional + The bottom ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + The bottom and top ylims may also be passed as the tuple + (*bottom*, *top*) as the first positional argument (or as + the *bottom* keyword argument). + + .. ACCEPTS: (bottom: float, top: float) + + top : float, optional + The top ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the y-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + ymin, ymax : float, optional + They are equivalent to bottom and top respectively, and it is an + error to pass both *ymin* and *bottom* or *ymax* and *top*. + + Returns + ------- + bottom, top : (float, float) + The new y-axis limits in data coordinates. + + See Also + -------- + get_ylim + set_ybound, get_ybound + invert_yaxis, yaxis_inverted + + Notes + ----- + The *bottom* value may be greater than the *top* value, in which + case the y-axis values will decrease from *bottom* to *top*. + + Examples + -------- + >>> set_ylim(bottom, top) + >>> set_ylim((bottom, top)) + >>> bottom, top = set_ylim(bottom, top) + + One limit may be left unchanged. + + >>> set_ylim(top=top_lim) + + Limits may be passed in reverse order to flip the direction of + the y-axis. For example, suppose ``y`` represents depth of the + ocean in m. The y-axis limits might be set like the following + so 5000 m depth is at the bottom of the plot and the surface, + 0 m, is at the top. + + >>> set_ylim(5000, 0) + """ + if top is None and np.iterable(bottom): + bottom, top = bottom + if ymin is not None: + if bottom is not None: + raise TypeError("Cannot pass both 'bottom' and 'ymin'") + bottom = ymin + if ymax is not None: + if top is not None: + raise TypeError("Cannot pass both 'top' and 'ymax'") + top = ymax + return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto) + + get_yscale = _axis_method_wrapper("yaxis", "get_scale") + set_yscale = _axis_method_wrapper("yaxis", "_set_axes_scale") + get_yticks = _axis_method_wrapper("yaxis", "get_ticklocs") + set_yticks = _axis_method_wrapper("yaxis", "set_ticks", + doc_sub={'set_ticks': 'set_yticks'}) + get_ymajorticklabels = _axis_method_wrapper("yaxis", "get_majorticklabels") + get_yminorticklabels = _axis_method_wrapper("yaxis", "get_minorticklabels") + get_yticklabels = _axis_method_wrapper("yaxis", "get_ticklabels") + set_yticklabels = _axis_method_wrapper( + "yaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_yticks"}) + + xaxis_date = _axis_method_wrapper("xaxis", "axis_date") + yaxis_date = _axis_method_wrapper("yaxis", "axis_date") + + def format_xdata(self, x): + """ + Return *x* formatted as an x-value. + + This function will use the `.fmt_xdata` attribute if it is not None, + else will fall back on the xaxis major formatter. + """ + return (self.fmt_xdata if self.fmt_xdata is not None + else self.xaxis.get_major_formatter().format_data_short)(x) + + def format_ydata(self, y): + """ + Return *y* formatted as a y-value. + + This function will use the `.fmt_ydata` attribute if it is not None, + else will fall back on the yaxis major formatter. + """ + return (self.fmt_ydata if self.fmt_ydata is not None + else self.yaxis.get_major_formatter().format_data_short)(y) + + def format_coord(self, x, y): + """Return a format string formatting the *x*, *y* coordinates.""" + twins = self._twinned_axes.get_siblings(self) + if len(twins) == 1: + return "(x, y) = ({}, {})".format( + "???" if x is None else self.format_xdata(x), + "???" if y is None else self.format_ydata(y)) + screen_xy = self.transData.transform((x, y)) + xy_strs = [] + # Retrieve twins in the order of self.figure.axes to sort tied zorders (which is + # the common case) by the order in which they are added to the figure. + for ax in sorted(twins, key=attrgetter("zorder")): + data_x, data_y = ax.transData.inverted().transform(screen_xy) + xy_strs.append( + "({}, {})".format(ax.format_xdata(data_x), ax.format_ydata(data_y))) + return "(x, y) = {}".format(" | ".join(xy_strs)) + + def minorticks_on(self): + """ + Display minor ticks on the Axes. + + Displaying minor ticks may reduce performance; you may turn them off + using `minorticks_off()` if drawing speed is a problem. + """ + self.xaxis.minorticks_on() + self.yaxis.minorticks_on() + + def minorticks_off(self): + """Remove minor ticks from the Axes.""" + self.xaxis.minorticks_off() + self.yaxis.minorticks_off() + + # Interactive manipulation + + def can_zoom(self): + """ + Return whether this Axes supports the zoom box button functionality. + """ + return True + + def can_pan(self): + """ + Return whether this Axes supports any pan/zoom button functionality. + """ + return True + + def get_navigate(self): + """ + Get whether the Axes responds to navigation commands. + """ + return self._navigate + + def set_navigate(self, b): + """ + Set whether the Axes responds to navigation toolbar commands. + + Parameters + ---------- + b : bool + + See Also + -------- + matplotlib.axes.Axes.set_forward_navigation_events + + """ + self._navigate = b + + def get_navigate_mode(self): + """ + Get the navigation toolbar button status: 'PAN', 'ZOOM', or None. + """ + return self._navigate_mode + + def set_navigate_mode(self, b): + """ + Set the navigation toolbar button status. + + .. warning:: + This is not a user-API function. + + """ + self._navigate_mode = b + + def _get_view(self): + """ + Save information required to reproduce the current view. + + This method is called before a view is changed, such as during a pan or zoom + initiated by the user. It returns an opaque object that describes the current + view, in a format compatible with :meth:`_set_view`. + + The default implementation saves the view limits and autoscaling state. + Subclasses may override this as needed, as long as :meth:`_set_view` is also + adjusted accordingly. + """ + return { + "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(), + "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(), + } + + def _set_view(self, view): + """ + Apply a previously saved view. + + This method is called when restoring a view (with the return value of + :meth:`_get_view` as argument), such as with the navigation buttons. + + Subclasses that override :meth:`_get_view` also need to override this method + accordingly. + """ + self.set(**view) + + def _prepare_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Helper function to prepare the new bounds from a bbox. + + This helper function returns the new x and y bounds from the zoom + bbox. This a convenience method to abstract the bbox logic + out of the base setter. + """ + if len(bbox) == 3: + xp, yp, scl = bbox # Zooming code + if scl == 0: # Should not happen + scl = 1. + if scl > 1: + direction = 'in' + else: + direction = 'out' + scl = 1/scl + # get the limits of the axes + (xmin, ymin), (xmax, ymax) = self.transData.transform( + np.transpose([self.get_xlim(), self.get_ylim()])) + # set the range + xwidth = xmax - xmin + ywidth = ymax - ymin + xcen = (xmax + xmin)*.5 + ycen = (ymax + ymin)*.5 + xzc = (xp*(scl - 1) + xcen)/scl + yzc = (yp*(scl - 1) + ycen)/scl + bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl, + xzc + xwidth/2./scl, yzc + ywidth/2./scl] + elif len(bbox) != 4: + # should be len 3 or 4 but nothing else + _api.warn_external( + "Warning in _set_view_from_bbox: bounding box is not a tuple " + "of length 3 or 4. Ignoring the view change.") + return + + # Original limits. + xmin0, xmax0 = self.get_xbound() + ymin0, ymax0 = self.get_ybound() + # The zoom box in screen coords. + startx, starty, stopx, stopy = bbox + # Convert to data coords. + (startx, starty), (stopx, stopy) = self.transData.inverted().transform( + [(startx, starty), (stopx, stopy)]) + # Clip to axes limits. + xmin, xmax = np.clip(sorted([startx, stopx]), xmin0, xmax0) + ymin, ymax = np.clip(sorted([starty, stopy]), ymin0, ymax0) + # Don't double-zoom twinned axes or if zooming only the other axis. + if twinx or mode == "y": + xmin, xmax = xmin0, xmax0 + if twiny or mode == "x": + ymin, ymax = ymin0, ymax0 + + if direction == "in": + new_xbound = xmin, xmax + new_ybound = ymin, ymax + + elif direction == "out": + x_trf = self.xaxis.get_transform() + sxmin0, sxmax0, sxmin, sxmax = x_trf.transform( + [xmin0, xmax0, xmin, xmax]) # To screen space. + factor = (sxmax0 - sxmin0) / (sxmax - sxmin) # Unzoom factor. + # Move original bounds away by + # (factor) x (distance between unzoom box and Axes bbox). + sxmin1 = sxmin0 - factor * (sxmin - sxmin0) + sxmax1 = sxmax0 + factor * (sxmax0 - sxmax) + # And back to data space. + new_xbound = x_trf.inverted().transform([sxmin1, sxmax1]) + + y_trf = self.yaxis.get_transform() + symin0, symax0, symin, symax = y_trf.transform( + [ymin0, ymax0, ymin, ymax]) + factor = (symax0 - symin0) / (symax - symin) + symin1 = symin0 - factor * (symin - symin0) + symax1 = symax0 + factor * (symax0 - symax) + new_ybound = y_trf.inverted().transform([symin1, symax1]) + + return new_xbound, new_ybound + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Update view from a selection bbox. + + .. note:: + + Intended to be overridden by new projection types, but if not, the + default implementation sets the view limits to the bbox directly. + + Parameters + ---------- + bbox : 4-tuple or 3 tuple + * If bbox is a 4 tuple, it is the selected bounding box limits, + in *display* coordinates. + * If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where + (xp, yp) is the center of zooming and scl the scale factor to + zoom by. + + direction : str + The direction to apply the bounding box. + * `'in'` - The bounding box describes the view directly, i.e., + it zooms in. + * `'out'` - The bounding box describes the size to make the + existing view, i.e., it zooms out. + + mode : str or None + The selection mode, whether to apply the bounding box in only the + `'x'` direction, `'y'` direction or both (`None`). + + twinx : bool + Whether this axis is twinned in the *x*-direction. + + twiny : bool + Whether this axis is twinned in the *y*-direction. + """ + new_xbound, new_ybound = self._prepare_view_from_bbox( + bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) + if not twinx and mode != "y": + self.set_xbound(new_xbound) + self.set_autoscalex_on(False) + if not twiny and mode != "x": + self.set_ybound(new_ybound) + self.set_autoscaley_on(False) + + def start_pan(self, x, y, button): + """ + Called when a pan operation has started. + + Parameters + ---------- + x, y : float + The mouse coordinates in display coords. + button : `.MouseButton` + The pressed mouse button. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + self._pan_start = types.SimpleNamespace( + lim=self.viewLim.frozen(), + trans=self.transData.frozen(), + trans_inverse=self.transData.inverted().frozen(), + bbox=self.bbox.frozen(), + x=x, + y=y) + + def end_pan(self): + """ + Called when a pan operation completes (when the mouse button is up.) + + Notes + ----- + This is intended to be overridden by new projection types. + """ + del self._pan_start + + def _get_pan_points(self, button, key, x, y): + """ + Helper function to return the new points after a pan. + + This helper function returns the points on the axis after a pan has + occurred. This is a convenience method to abstract the pan logic + out of the base setter. + """ + def format_deltas(key, dx, dy): + if key == 'control': + if abs(dx) > abs(dy): + dy = dx + else: + dx = dy + elif key == 'x': + dy = 0 + elif key == 'y': + dx = 0 + elif key == 'shift': + if 2 * abs(dx) < abs(dy): + dx = 0 + elif 2 * abs(dy) < abs(dx): + dy = 0 + elif abs(dx) > abs(dy): + dy = dy / abs(dy) * abs(dx) + else: + dx = dx / abs(dx) * abs(dy) + return dx, dy + + p = self._pan_start + dx = x - p.x + dy = y - p.y + if dx == dy == 0: + return + if button == 1: + dx, dy = format_deltas(key, dx, dy) + result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse) + elif button == 3: + try: + dx = -dx / self.bbox.width + dy = -dy / self.bbox.height + dx, dy = format_deltas(key, dx, dy) + if self.get_aspect() != 'auto': + dx = dy = 0.5 * (dx + dy) + alpha = np.power(10.0, (dx, dy)) + start = np.array([p.x, p.y]) + oldpoints = p.lim.transformed(p.trans) + newpoints = start + alpha * (oldpoints - start) + result = (mtransforms.Bbox(newpoints) + .transformed(p.trans_inverse)) + except OverflowError: + _api.warn_external('Overflow while panning') + return + else: + return + + valid = np.isfinite(result.transformed(p.trans)) + points = result.get_points().astype(object) + # Just ignore invalid limits (typically, underflow in log-scale). + points[~valid] = None + return points + + def drag_pan(self, button, key, x, y): + """ + Called when the mouse moves during a pan operation. + + Parameters + ---------- + button : `.MouseButton` + The pressed mouse button. + key : str or None + The pressed key, if any. + x, y : float + The mouse coordinates in display coords. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + points = self._get_pan_points(button, key, x, y) + if points is not None: + self.set_xlim(points[:, 0]) + self.set_ylim(points[:, 1]) + + def get_children(self): + # docstring inherited. + return [ + *self._children, + *self.spines.values(), + *self._axis_map.values(), + self.title, self._left_title, self._right_title, + *self.child_axes, + *([self.legend_] if self.legend_ is not None else []), + self.patch, + ] + + def contains(self, mouseevent): + # docstring inherited. + return self.patch.contains(mouseevent) + + def contains_point(self, point): + """ + Return whether *point* (pair of pixel coordinates) is inside the Axes + patch. + """ + return self.patch.contains_point(point, radius=1.0) + + def get_default_bbox_extra_artists(self): + """ + Return a default list of artists that are used for the bounding box + calculation. + + Artists are excluded either by not being visible or + ``artist.set_in_layout(False)``. + """ + + artists = self.get_children() + + for axis in self._axis_map.values(): + # axis tight bboxes are calculated separately inside + # Axes.get_tightbbox() using for_layout_only=True + artists.remove(axis) + if not (self.axison and self._frameon): + # don't do bbox on spines if frame not on. + for spine in self.spines.values(): + artists.remove(spine) + + artists.remove(self.title) + artists.remove(self._left_title) + artists.remove(self._right_title) + + # always include types that do not internally implement clipping + # to Axes. may have clip_on set to True and clip_box equivalent + # to ax.bbox but then ignore these properties during draws. + noclip = (_AxesBase, maxis.Axis, + offsetbox.AnnotationBbox, offsetbox.OffsetBox) + return [a for a in artists if a.get_visible() and a.get_in_layout() + and (isinstance(a, noclip) or not a._fully_clipped_to_axes())] + + def get_tightbbox(self, renderer=None, *, call_axes_locator=True, + bbox_extra_artists=None, for_layout_only=False): + """ + Return the tight bounding box of the Axes, including axis and their + decorators (xlabel, title, etc). + + Artists that have ``artist.set_in_layout(False)`` are not included + in the bbox. + + Parameters + ---------- + renderer : `.RendererBase` subclass + renderer that will be used to draw the figures (i.e. + ``fig.canvas.get_renderer()``) + + bbox_extra_artists : list of `.Artist` or ``None`` + List of artists to include in the tight bounding box. If + ``None`` (default), then all artist children of the Axes are + included in the tight bounding box. + + call_axes_locator : bool, default: True + If *call_axes_locator* is ``False``, it does not call the + ``_axes_locator`` attribute, which is necessary to get the correct + bounding box. ``call_axes_locator=False`` can be used if the + caller is only interested in the relative size of the tightbbox + compared to the Axes bbox. + + for_layout_only : default: False + The bounding box will *not* include the x-extent of the title and + the xlabel, or the y-extent of the ylabel. + + Returns + ------- + `.BboxBase` + Bounding box in figure pixel coordinates. + + See Also + -------- + matplotlib.axes.Axes.get_window_extent + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + + bb = [] + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + if not self.get_visible(): + return None + + locator = self.get_axes_locator() + self.apply_aspect( + locator(self, renderer) if locator and call_axes_locator else None) + + for axis in self._axis_map.values(): + if self.axison and axis.get_visible(): + ba = martist._get_tightbbox_for_layout_only(axis, renderer) + if ba: + bb.append(ba) + self._update_title_position(renderer) + axbbox = self.get_window_extent(renderer) + bb.append(axbbox) + + for title in [self.title, self._left_title, self._right_title]: + if title.get_visible(): + bt = title.get_window_extent(renderer) + if for_layout_only and bt.width > 0: + # make the title bbox 1 pixel wide so its width + # is not accounted for in bbox calculations in + # tight/constrained_layout + bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5 + bt.x1 = bt.x0 + 1.0 + bb.append(bt) + + bbox_artists = bbox_extra_artists + if bbox_artists is None: + bbox_artists = self.get_default_bbox_extra_artists() + + for a in bbox_artists: + bbox = a.get_tightbbox(renderer) + if (bbox is not None + and 0 < bbox.width < np.inf + and 0 < bbox.height < np.inf): + bb.append(bbox) + return mtransforms.Bbox.union( + [b for b in bb if b.width != 0 or b.height != 0]) + + def _make_twin_axes(self, *args, **kwargs): + """Make a twinx Axes of self. This is used for twinx and twiny.""" + if 'sharex' in kwargs and 'sharey' in kwargs: + # The following line is added in v2.2 to avoid breaking Seaborn, + # which currently uses this internal API. + if kwargs["sharex"] is not self and kwargs["sharey"] is not self: + raise ValueError("Twinned Axes may share only one axis") + ss = self.get_subplotspec() + if ss: + twin = self.get_figure(root=False).add_subplot(ss, *args, **kwargs) + else: + twin = self.get_figure(root=False).add_axes( + self.get_position(True), *args, **kwargs, + axes_locator=_TransformedBoundsLocator( + [0, 0, 1, 1], self.transAxes)) + self.set_adjustable('datalim') + twin.set_adjustable('datalim') + twin.set_zorder(self.zorder) + + self._twinned_axes.join(self, twin) + return twin + + def twinx(self): + """ + Create a twin Axes sharing the xaxis. + + Create a new Axes with an invisible x-axis and an independent + y-axis positioned opposite to the original one (i.e. at right). The + x-axis autoscale setting will be inherited from the original + Axes. To ensure that the tick marks of both y-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twinx, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharex=self) + ax2.yaxis.tick_right() + ax2.yaxis.set_label_position('right') + ax2.yaxis.set_offset_position('right') + ax2.set_autoscalex_on(self.get_autoscalex_on()) + self.yaxis.tick_left() + ax2.xaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.xaxis.units = self.xaxis.units + return ax2 + + def twiny(self): + """ + Create a twin Axes sharing the yaxis. + + Create a new Axes with an invisible y-axis and an independent + x-axis positioned opposite to the original one (i.e. at top). The + y-axis autoscale setting will be inherited from the original Axes. + To ensure that the tick marks of both x-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twiny, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharey=self) + ax2.xaxis.tick_top() + ax2.xaxis.set_label_position('top') + ax2.set_autoscaley_on(self.get_autoscaley_on()) + self.xaxis.tick_bottom() + ax2.yaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.yaxis.units = self.yaxis.units + return ax2 + + def get_shared_x_axes(self): + """Return an immutable view on the shared x-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["x"]) + + def get_shared_y_axes(self): + """Return an immutable view on the shared y-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["y"]) + + def label_outer(self, remove_inner_ticks=False): + """ + Only show "outer" labels and tick labels. + + x-labels are only kept for subplots on the last row (or first row, if + labels are on the top side); y-labels only for subplots on the first + column (or last column, if labels are on the right side). + + Parameters + ---------- + remove_inner_ticks : bool, default: False + If True, remove the inner ticks as well (not only tick labels). + + .. versionadded:: 3.8 + """ + self._label_outer_xaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + self._label_outer_yaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + + def _label_outer_xaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self.get_subplotspec() + if not ss: + return + label_position = self.xaxis.get_label_position() + if not ss.is_first_row(): # Remove top label/ticklabels/offsettext. + if label_position == "top": + self.set_xlabel("") + top_kw = {'top': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labeltop=False, **top_kw) + if self.xaxis.offsetText.get_position()[1] == 1: + self.xaxis.offsetText.set_visible(False) + if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext. + if label_position == "bottom": + self.set_xlabel("") + bottom_kw = {'bottom': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labelbottom=False, **bottom_kw) + if self.xaxis.offsetText.get_position()[1] == 0: + self.xaxis.offsetText.set_visible(False) + + def _label_outer_yaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self.get_subplotspec() + if not ss: + return + label_position = self.yaxis.get_label_position() + if not ss.is_first_col(): # Remove left label/ticklabels/offsettext. + if label_position == "left": + self.set_ylabel("") + left_kw = {'left': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelleft=False, **left_kw) + if self.yaxis.offsetText.get_position()[0] == 0: + self.yaxis.offsetText.set_visible(False) + if not ss.is_last_col(): # Remove right label/ticklabels/offsettext. + if label_position == "right": + self.set_ylabel("") + right_kw = {'right': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelright=False, **right_kw) + if self.yaxis.offsetText.get_position()[0] == 1: + self.yaxis.offsetText.set_visible(False) + + def set_forward_navigation_events(self, forward): + """ + Set how pan/zoom events are forwarded to Axes below this one. + + Parameters + ---------- + forward : bool or "auto" + Possible values: + + - True: Forward events to other axes with lower or equal zorder. + - False: Events are only executed on this axes. + - "auto": Default behaviour (*True* for axes with an invisible + patch and *False* otherwise) + + See Also + -------- + matplotlib.axes.Axes.set_navigate + + """ + self._forward_navigation_events = forward + + def get_forward_navigation_events(self): + """Get how pan/zoom events are forwarded to Axes below this one.""" + return self._forward_navigation_events + + +def _draw_rasterized(figure, artists, renderer): + """ + A helper function for rasterizing the list of artists. + + The bookkeeping to track if we are or are not in rasterizing mode + with the mixed-mode backends is relatively complicated and is now + handled in the matplotlib.artist.allow_rasterization decorator. + + This helper defines the absolute minimum methods and attributes on a + shim class to be compatible with that decorator and then uses it to + rasterize the list of artists. + + This is maybe too-clever, but allows us to reuse the same code that is + used on normal artists to participate in the "are we rasterizing" + accounting. + + Please do not use this outside of the "rasterize below a given zorder" + functionality of Axes. + + Parameters + ---------- + figure : matplotlib.figure.Figure + The figure all of the artists belong to (not checked). We need this + because we can at the figure level suppress composition and insert each + rasterized artist as its own image. + + artists : List[matplotlib.artist.Artist] + The list of Artists to be rasterized. These are assumed to all + be in the same Figure. + + renderer : matplotlib.backendbases.RendererBase + The currently active renderer + + Returns + ------- + None + + """ + class _MinimalArtist: + def get_rasterized(self): + return True + + def get_agg_filter(self): + return None + + def __init__(self, figure, artists): + self.figure = figure + self.artists = artists + + def get_figure(self, root=False): + if root: + return self.figure.get_figure(root=True) + else: + return self.figure + + @martist.allow_rasterization + def draw(self, renderer): + for a in self.artists: + a.draw(renderer) + + return _MinimalArtist(figure, artists).draw(renderer) diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_base.pyi b/python_embeded/Lib/site-packages/matplotlib/axes/_base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..df82ad7ec4a5aa2459ccc81d46afceacfeb86951 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_base.pyi @@ -0,0 +1,459 @@ +import matplotlib.artist as martist + +import datetime +from collections.abc import Callable, Iterable, Iterator, Sequence +from matplotlib import cbook +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.axis import XAxis, YAxis, Tick +from matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent +from matplotlib.cbook import CallbackRegistry +from matplotlib.container import Container +from matplotlib.collections import Collection +from matplotlib.colorizer import ColorizingArtist +from matplotlib.legend import Legend +from matplotlib.lines import Line2D +from matplotlib.gridspec import SubplotSpec, GridSpec +from matplotlib.figure import Figure, SubFigure +from matplotlib.image import AxesImage +from matplotlib.patches import Patch +from matplotlib.scale import ScaleBase +from matplotlib.spines import Spines +from matplotlib.table import Table +from matplotlib.text import Text +from matplotlib.transforms import Transform, Bbox + +from cycler import Cycler + +import numpy as np +from numpy.typing import ArrayLike +from typing import Any, Literal, TypeVar, overload +from matplotlib.typing import ColorType + +_T = TypeVar("_T", bound=Artist) + +class _axis_method_wrapper: + attr_name: str + method_name: str + __doc__: str + def __init__( + self, attr_name: str, method_name: str, *, doc_sub: dict[str, str] | None = ... + ) -> None: ... + def __set_name__(self, owner: Any, name: str) -> None: ... + +class _AxesBase(martist.Artist): + name: str + patch: Patch + spines: Spines + fmt_xdata: Callable[[float], str] | None + fmt_ydata: Callable[[float], str] | None + xaxis: XAxis + yaxis: YAxis + bbox: Bbox + dataLim: Bbox + transAxes: Transform + transScale: Transform + transLimits: Transform + transData: Transform + ignore_existing_data_limits: bool + axison: bool + containers: list[Container] + callbacks: CallbackRegistry + child_axes: list[_AxesBase] + legend_: Legend | None + title: Text + _projection_init: Any + + def __init__( + self, + fig: Figure, + *args: tuple[float, float, float, float] | Bbox | int, + facecolor: ColorType | None = ..., + frameon: bool = ..., + sharex: _AxesBase | None = ..., + sharey: _AxesBase | None = ..., + label: Any = ..., + xscale: str | ScaleBase | None = ..., + yscale: str | ScaleBase | None = ..., + box_aspect: float | None = ..., + forward_navigation_events: bool | Literal["auto"] = ..., + **kwargs + ) -> None: ... + def get_subplotspec(self) -> SubplotSpec | None: ... + def set_subplotspec(self, subplotspec: SubplotSpec) -> None: ... + def get_gridspec(self) -> GridSpec | None: ... + def set_figure(self, fig: Figure | SubFigure) -> None: ... + @property + def viewLim(self) -> Bbox: ... + def get_xaxis_transform( + self, which: Literal["grid", "tick1", "tick2"] = ... + ) -> Transform: ... + def get_xaxis_text1_transform( + self, pad_points: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_xaxis_text2_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_transform( + self, which: Literal["grid", "tick1", "tick2"] = ... + ) -> Transform: ... + def get_yaxis_text1_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_text2_transform( + self, pad_points + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_position(self, original: bool = ...) -> Bbox: ... + def set_position( + self, + pos: Bbox | tuple[float, float, float, float], + which: Literal["both", "active", "original"] = ..., + ) -> None: ... + def reset_position(self) -> None: ... + def set_axes_locator( + self, locator: Callable[[_AxesBase, RendererBase], Bbox] + ) -> None: ... + def get_axes_locator(self) -> Callable[[_AxesBase, RendererBase], Bbox]: ... + def sharex(self, other: _AxesBase) -> None: ... + def sharey(self, other: _AxesBase) -> None: ... + def clear(self) -> None: ... + def cla(self) -> None: ... + + class ArtistList(Sequence[_T]): + def __init__( + self, + axes: _AxesBase, + prop_name: str, + valid_types: type | Iterable[type] | None = ..., + invalid_types: type | Iterable[type] | None = ..., + ) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + @overload + def __getitem__(self, key: int) -> _T: ... + @overload + def __getitem__(self, key: slice) -> list[_T]: ... + + @overload + def __add__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ... + @overload + def __add__(self, other: list[Any]) -> list[Any]: ... + @overload + def __add__(self, other: tuple[Any]) -> tuple[Any]: ... + + @overload + def __radd__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ... + @overload + def __radd__(self, other: list[Any]) -> list[Any]: ... + @overload + def __radd__(self, other: tuple[Any]) -> tuple[Any]: ... + + @property + def artists(self) -> _AxesBase.ArtistList[Artist]: ... + @property + def collections(self) -> _AxesBase.ArtistList[Collection]: ... + @property + def images(self) -> _AxesBase.ArtistList[AxesImage]: ... + @property + def lines(self) -> _AxesBase.ArtistList[Line2D]: ... + @property + def patches(self) -> _AxesBase.ArtistList[Patch]: ... + @property + def tables(self) -> _AxesBase.ArtistList[Table]: ... + @property + def texts(self) -> _AxesBase.ArtistList[Text]: ... + def get_facecolor(self) -> ColorType: ... + def set_facecolor(self, color: ColorType | None) -> None: ... + @overload + def set_prop_cycle(self, cycler: Cycler | None) -> None: ... + @overload + def set_prop_cycle(self, label: str, values: Iterable[Any]) -> None: ... + @overload + def set_prop_cycle(self, **kwargs: Iterable[Any]) -> None: ... + def get_aspect(self) -> float | Literal["auto"]: ... + def set_aspect( + self, + aspect: float | Literal["auto", "equal"], + adjustable: Literal["box", "datalim"] | None = ..., + anchor: str | tuple[float, float] | None = ..., + share: bool = ..., + ) -> None: ... + def get_adjustable(self) -> Literal["box", "datalim"]: ... + def set_adjustable( + self, adjustable: Literal["box", "datalim"], share: bool = ... + ) -> None: ... + def get_box_aspect(self) -> float | None: ... + def set_box_aspect(self, aspect: float | None = ...) -> None: ... + def get_anchor(self) -> str | tuple[float, float]: ... + def set_anchor( + self, anchor: str | tuple[float, float], share: bool = ... + ) -> None: ... + def get_data_ratio(self) -> float: ... + def apply_aspect(self, position: Bbox | None = ...) -> None: ... + @overload + def axis( + self, + arg: tuple[float, float, float, float] | bool | str | None = ..., + /, + *, + emit: bool = ... + ) -> tuple[float, float, float, float]: ... + @overload + def axis( + self, + *, + emit: bool = ..., + xmin: float | None = ..., + xmax: float | None = ..., + ymin: float | None = ..., + ymax: float | None = ... + ) -> tuple[float, float, float, float]: ... + def get_legend(self) -> Legend: ... + def get_images(self) -> list[AxesImage]: ... + def get_lines(self) -> list[Line2D]: ... + def get_xaxis(self) -> XAxis: ... + def get_yaxis(self) -> YAxis: ... + def has_data(self) -> bool: ... + def add_artist(self, a: Artist) -> Artist: ... + def add_child_axes(self, ax: _AxesBase) -> _AxesBase: ... + def add_collection( + self, collection: Collection, autolim: bool = ... + ) -> Collection: ... + def add_image(self, image: AxesImage) -> AxesImage: ... + def add_line(self, line: Line2D) -> Line2D: ... + def add_patch(self, p: Patch) -> Patch: ... + def add_table(self, tab: Table) -> Table: ... + def add_container(self, container: Container) -> Container: ... + def relim(self, visible_only: bool = ...) -> None: ... + def update_datalim( + self, xys: ArrayLike, updatex: bool = ..., updatey: bool = ... + ) -> None: ... + def in_axes(self, mouseevent: MouseEvent) -> bool: ... + def get_autoscale_on(self) -> bool: ... + def set_autoscale_on(self, b: bool) -> None: ... + @property + def use_sticky_edges(self) -> bool: ... + @use_sticky_edges.setter + def use_sticky_edges(self, b: bool) -> None: ... + def get_xmargin(self) -> float: ... + def get_ymargin(self) -> float: ... + def set_xmargin(self, m: float) -> None: ... + def set_ymargin(self, m: float) -> None: ... + + # Probably could be made better with overloads + def margins( + self, + *margins: float, + x: float | None = ..., + y: float | None = ..., + tight: bool | None = ... + ) -> tuple[float, float] | None: ... + def set_rasterization_zorder(self, z: float | None) -> None: ... + def get_rasterization_zorder(self) -> float | None: ... + def autoscale( + self, + enable: bool = ..., + axis: Literal["both", "x", "y"] = ..., + tight: bool | None = ..., + ) -> None: ... + def autoscale_view( + self, tight: bool | None = ..., scalex: bool = ..., scaley: bool = ... + ) -> None: ... + def draw_artist(self, a: Artist) -> None: ... + def redraw_in_frame(self) -> None: ... + def get_frame_on(self) -> bool: ... + def set_frame_on(self, b: bool) -> None: ... + def get_axisbelow(self) -> bool | Literal["line"]: ... + def set_axisbelow(self, b: bool | Literal["line"]) -> None: ... + def grid( + self, + visible: bool | None = ..., + which: Literal["major", "minor", "both"] = ..., + axis: Literal["both", "x", "y"] = ..., + **kwargs + ) -> None: ... + def ticklabel_format( + self, + *, + axis: Literal["both", "x", "y"] = ..., + style: Literal["", "sci", "scientific", "plain"] | None = ..., + scilimits: tuple[int, int] | None = ..., + useOffset: bool | float | None = ..., + useLocale: bool | None = ..., + useMathText: bool | None = ... + ) -> None: ... + def locator_params( + self, axis: Literal["both", "x", "y"] = ..., tight: bool | None = ..., **kwargs + ) -> None: ... + def tick_params(self, axis: Literal["both", "x", "y"] = ..., **kwargs) -> None: ... + def set_axis_off(self) -> None: ... + def set_axis_on(self) -> None: ... + def get_xlabel(self) -> str: ... + def set_xlabel( + self, + xlabel: str, + fontdict: dict[str, Any] | None = ..., + labelpad: float | None = ..., + *, + loc: Literal["left", "center", "right"] | None = ..., + **kwargs + ) -> Text: ... + def invert_xaxis(self) -> None: ... + def get_xbound(self) -> tuple[float, float]: ... + def set_xbound( + self, lower: float | None = ..., upper: float | None = ... + ) -> None: ... + def get_xlim(self) -> tuple[float, float]: ... + def set_xlim( + self, + left: float | tuple[float, float] | None = ..., + right: float | None = ..., + *, + emit: bool = ..., + auto: bool | None = ..., + xmin: float | None = ..., + xmax: float | None = ... + ) -> tuple[float, float]: ... + def get_ylabel(self) -> str: ... + def set_ylabel( + self, + ylabel: str, + fontdict: dict[str, Any] | None = ..., + labelpad: float | None = ..., + *, + loc: Literal["bottom", "center", "top"] | None = ..., + **kwargs + ) -> Text: ... + def invert_yaxis(self) -> None: ... + def get_ybound(self) -> tuple[float, float]: ... + def set_ybound( + self, lower: float | None = ..., upper: float | None = ... + ) -> None: ... + def get_ylim(self) -> tuple[float, float]: ... + def set_ylim( + self, + bottom: float | tuple[float, float] | None = ..., + top: float | None = ..., + *, + emit: bool = ..., + auto: bool | None = ..., + ymin: float | None = ..., + ymax: float | None = ... + ) -> tuple[float, float]: ... + def format_xdata(self, x: float) -> str: ... + def format_ydata(self, y: float) -> str: ... + def format_coord(self, x: float, y: float) -> str: ... + def minorticks_on(self) -> None: ... + def minorticks_off(self) -> None: ... + def can_zoom(self) -> bool: ... + def can_pan(self) -> bool: ... + def get_navigate(self) -> bool: ... + def set_navigate(self, b: bool) -> None: ... + def get_forward_navigation_events(self) -> bool | Literal["auto"]: ... + def set_forward_navigation_events(self, forward: bool | Literal["auto"]) -> None: ... + def get_navigate_mode(self) -> Literal["PAN", "ZOOM"] | None: ... + def set_navigate_mode(self, b: Literal["PAN", "ZOOM"] | None) -> None: ... + def start_pan(self, x: float, y: float, button: MouseButton) -> None: ... + def end_pan(self) -> None: ... + def drag_pan( + self, button: MouseButton, key: str | None, x: float, y: float + ) -> None: ... + def get_children(self) -> list[Artist]: ... + def contains_point(self, point: tuple[int, int]) -> bool: ... + def get_default_bbox_extra_artists(self) -> list[Artist]: ... + def get_tightbbox( + self, + renderer: RendererBase | None = ..., + *, + call_axes_locator: bool = ..., + bbox_extra_artists: Sequence[Artist] | None = ..., + for_layout_only: bool = ... + ) -> Bbox | None: ... + def twinx(self) -> Axes: ... + def twiny(self) -> Axes: ... + def get_shared_x_axes(self) -> cbook.GrouperView: ... + def get_shared_y_axes(self) -> cbook.GrouperView: ... + def label_outer(self, remove_inner_ticks: bool = ...) -> None: ... + + # The methods underneath this line are added via the `_axis_method_wrapper` class + # Initially they are set to an object, but that object uses `__set_name__` to override + # itself with a method modified from the Axis methods for the x or y Axis. + # As such, they are typed according to the resultant method rather than as that object. + + def get_xgridlines(self) -> list[Line2D]: ... + def get_xticklines(self, minor: bool = ...) -> list[Line2D]: ... + def get_ygridlines(self) -> list[Line2D]: ... + def get_yticklines(self, minor: bool = ...) -> list[Line2D]: ... + def _sci(self, im: ColorizingArtist) -> None: ... + def get_autoscalex_on(self) -> bool: ... + def get_autoscaley_on(self) -> bool: ... + def set_autoscalex_on(self, b: bool) -> None: ... + def set_autoscaley_on(self, b: bool) -> None: ... + def xaxis_inverted(self) -> bool: ... + def get_xscale(self) -> str: ... + def set_xscale(self, value: str | ScaleBase, **kwargs) -> None: ... + def get_xticks(self, *, minor: bool = ...) -> np.ndarray: ... + def set_xticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def get_xmajorticklabels(self) -> list[Text]: ... + def get_xminorticklabels(self) -> list[Text]: ... + def get_xticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def set_xticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def yaxis_inverted(self) -> bool: ... + def get_yscale(self) -> str: ... + def set_yscale(self, value: str | ScaleBase, **kwargs) -> None: ... + def get_yticks(self, *, minor: bool = ...) -> np.ndarray: ... + def set_yticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def get_ymajorticklabels(self) -> list[Text]: ... + def get_yminorticklabels(self) -> list[Text]: ... + def get_yticklabels( + self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ... + ) -> list[Text]: ... + def set_yticklabels( + self, + labels: Iterable[str | Text], + *, + minor: bool = ..., + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> list[Text]: ... + def xaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... + def yaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.py b/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..15a1970fa4a6e7762da98b58c6c5317e0ede7ec1 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.py @@ -0,0 +1,322 @@ +import numbers + +import numpy as np + +from matplotlib import _api, _docstring, transforms +import matplotlib.ticker as mticker +from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator +from matplotlib.axis import Axis +from matplotlib.transforms import Transform + + +class SecondaryAxis(_AxesBase): + """ + General class to hold a Secondary_X/Yaxis. + """ + + def __init__(self, parent, orientation, location, functions, transform=None, + **kwargs): + """ + See `.secondary_xaxis` and `.secondary_yaxis` for the doc string. + While there is no need for this to be private, it should really be + called by those higher level functions. + """ + _api.check_in_list(["x", "y"], orientation=orientation) + self._functions = functions + self._parent = parent + self._orientation = orientation + self._ticks_set = False + + fig = self._parent.get_figure(root=False) + if self._orientation == 'x': + super().__init__(fig, [0, 1., 1, 0.0001], **kwargs) + self._axis = self.xaxis + self._locstrings = ['top', 'bottom'] + self._otherstrings = ['left', 'right'] + else: # 'y' + super().__init__(fig, [0, 1., 0.0001, 1], **kwargs) + self._axis = self.yaxis + self._locstrings = ['right', 'left'] + self._otherstrings = ['top', 'bottom'] + self._parentscale = None + # this gets positioned w/o constrained_layout so exclude: + + self.set_location(location, transform) + self.set_functions(functions) + + # styling: + otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis + otheraxis.set_major_locator(mticker.NullLocator()) + otheraxis.set_ticks_position('none') + + self.spines[self._otherstrings].set_visible(False) + self.spines[self._locstrings].set_visible(True) + + if self._pos < 0.5: + # flip the location strings... + self._locstrings = self._locstrings[::-1] + self.set_alignment(self._locstrings[0]) + + def set_alignment(self, align): + """ + Set if axes spine and labels are drawn at top or bottom (or left/right) + of the Axes. + + Parameters + ---------- + align : {'top', 'bottom', 'left', 'right'} + Either 'top' or 'bottom' for orientation='x' or + 'left' or 'right' for orientation='y' axis. + """ + _api.check_in_list(self._locstrings, align=align) + if align == self._locstrings[1]: # Need to change the orientation. + self._locstrings = self._locstrings[::-1] + self.spines[self._locstrings[0]].set_visible(True) + self.spines[self._locstrings[1]].set_visible(False) + self._axis.set_ticks_position(align) + self._axis.set_label_position(align) + + def set_location(self, location, transform=None): + """ + Set the vertical or horizontal location of the axes in + parent-normalized coordinates. + + Parameters + ---------- + location : {'top', 'bottom', 'left', 'right'} or float + The position to put the secondary axis. Strings can be 'top' or + 'bottom' for orientation='x' and 'right' or 'left' for + orientation='y'. A float indicates the relative position on the + parent Axes to put the new Axes, 0.0 being the bottom (or left) + and 1.0 being the top (or right). + + transform : `.Transform`, optional + Transform for the location to use. Defaults to + the parent's ``transAxes``, so locations are normally relative to + the parent axes. + + .. versionadded:: 3.9 + """ + + _api.check_isinstance((transforms.Transform, None), transform=transform) + + # This puts the rectangle into figure-relative coordinates. + if isinstance(location, str): + _api.check_in_list(self._locstrings, location=location) + self._pos = 1. if location in ('top', 'right') else 0. + elif isinstance(location, numbers.Real): + self._pos = location + else: + raise ValueError( + f"location must be {self._locstrings[0]!r}, " + f"{self._locstrings[1]!r}, or a float, not {location!r}") + + self._loc = location + + if self._orientation == 'x': + # An x-secondary axes is like an inset axes from x = 0 to x = 1 and + # from y = pos to y = pos + eps, in the parent's transAxes coords. + bounds = [0, self._pos, 1., 1e-10] + + # If a transformation is provided, use its y component rather than + # the parent's transAxes. This can be used to place axes in the data + # coords, for instance. + if transform is not None: + transform = transforms.blended_transform_factory( + self._parent.transAxes, transform) + else: # 'y' + bounds = [self._pos, 0, 1e-10, 1] + if transform is not None: + transform = transforms.blended_transform_factory( + transform, self._parent.transAxes) # Use provided x axis + + # If no transform is provided, use the parent's transAxes + if transform is None: + transform = self._parent.transAxes + + # this locator lets the axes move in the parent axes coordinates. + # so it never needs to know where the parent is explicitly in + # figure coordinates. + # it gets called in ax.apply_aspect() (of all places) + self.set_axes_locator(_TransformedBoundsLocator(bounds, transform)) + + def apply_aspect(self, position=None): + # docstring inherited. + self._set_lims() + super().apply_aspect(position) + + @_docstring.copy(Axis.set_ticks) + def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): + ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs) + self.stale = True + self._ticks_set = True + return ret + + def set_functions(self, functions): + """ + Set how the secondary axis converts limits from the parent Axes. + + Parameters + ---------- + functions : 2-tuple of func, or `Transform` with an inverse. + Transform between the parent axis values and the secondary axis + values. + + If supplied as a 2-tuple of functions, the first function is + the forward transform function and the second is the inverse + transform. + + If a transform is supplied, then the transform must have an + inverse. + """ + + if (isinstance(functions, tuple) and len(functions) == 2 and + callable(functions[0]) and callable(functions[1])): + # make an arbitrary convert from a two-tuple of functions + # forward and inverse. + self._functions = functions + elif isinstance(functions, Transform): + self._functions = ( + functions.transform, + lambda x: functions.inverted().transform(x) + ) + elif functions is None: + self._functions = (lambda x: x, lambda x: x) + else: + raise ValueError('functions argument of secondary Axes ' + 'must be a two-tuple of callable functions ' + 'with the first function being the transform ' + 'and the second being the inverse') + self._set_scale() + + def draw(self, renderer): + """ + Draw the secondary Axes. + + Consults the parent Axes for its limits and converts them + using the converter specified by + `~.axes._secondary_axes.set_functions` (or *functions* + parameter when Axes initialized.) + """ + self._set_lims() + # this sets the scale in case the parent has set its scale. + self._set_scale() + super().draw(renderer) + + def _set_scale(self): + """ + Check if parent has set its scale + """ + + if self._orientation == 'x': + pscale = self._parent.xaxis.get_scale() + set_scale = self.set_xscale + else: # 'y' + pscale = self._parent.yaxis.get_scale() + set_scale = self.set_yscale + if pscale == self._parentscale: + return + + if self._ticks_set: + ticks = self._axis.get_ticklocs() + + # need to invert the roles here for the ticks to line up. + set_scale('functionlog' if pscale == 'log' else 'function', + functions=self._functions[::-1]) + + # OK, set_scale sets the locators, but if we've called + # axsecond.set_ticks, we want to keep those. + if self._ticks_set: + self._axis.set_major_locator(mticker.FixedLocator(ticks)) + + # If the parent scale doesn't change, we can skip this next time. + self._parentscale = pscale + + def _set_lims(self): + """ + Set the limits based on parent limits and the convert method + between the parent and this secondary Axes. + """ + if self._orientation == 'x': + lims = self._parent.get_xlim() + set_lim = self.set_xlim + else: # 'y' + lims = self._parent.get_ylim() + set_lim = self.set_ylim + order = lims[0] < lims[1] + lims = self._functions[0](np.array(lims)) + neworder = lims[0] < lims[1] + if neworder != order: + # Flip because the transform will take care of the flipping. + lims = lims[::-1] + set_lim(lims) + + def set_aspect(self, *args, **kwargs): + """ + Secondary Axes cannot set the aspect ratio, so calling this just + sets a warning. + """ + _api.warn_external("Secondary Axes can't set the aspect ratio") + + def set_color(self, color): + """ + Change the color of the secondary Axes and all decorators. + + Parameters + ---------- + color : :mpltype:`color` + """ + axis = self._axis_map[self._orientation] + axis.set_tick_params(colors=color) + for spine in self.spines.values(): + if spine.axis is axis: + spine.set_color(color) + axis.label.set_color(color) + + +_secax_docstring = ''' +Warnings +-------- +This method is experimental as of 3.1, and the API may change. + +Parameters +---------- +location : {'top', 'bottom', 'left', 'right'} or float + The position to put the secondary axis. Strings can be 'top' or + 'bottom' for orientation='x' and 'right' or 'left' for + orientation='y'. A float indicates the relative position on the + parent Axes to put the new Axes, 0.0 being the bottom (or left) + and 1.0 being the top (or right). + +functions : 2-tuple of func, or Transform with an inverse + + If a 2-tuple of functions, the user specifies the transform + function and its inverse. i.e. + ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an + reciprocal transform with a factor of 2. Both functions must accept + numpy arrays as input. + + The user can also directly supply a subclass of + `.transforms.Transform` so long as it has an inverse. + + See :doc:`/gallery/subplots_axes_and_figures/secondary_axis` + for examples of making these conversions. + +transform : `.Transform`, optional + If specified, *location* will be + placed relative to this transform (in the direction of the axis) + rather than the parent's axis. i.e. a secondary x-axis will + use the provided y transform and the x transform of the parent. + + .. versionadded:: 3.9 + +Returns +------- +ax : axes._secondary_axes.SecondaryAxis + +Other Parameters +---------------- +**kwargs : `~matplotlib.axes.Axes` properties. + Other miscellaneous Axes parameters. +''' +_docstring.interpd.register(_secax_docstring=_secax_docstring) diff --git a/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.pyi b/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..afb429f740c4aa58a42b64f9209e1e0bd9ee57f7 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/axes/_secondary_axes.pyi @@ -0,0 +1,45 @@ +from matplotlib.axes._base import _AxesBase +from matplotlib.axis import Tick + +from matplotlib.transforms import Transform + +from collections.abc import Callable, Iterable +from typing import Literal +from numpy.typing import ArrayLike +from matplotlib.typing import ColorType + +class SecondaryAxis(_AxesBase): + def __init__( + self, + parent: _AxesBase, + orientation: Literal["x", "y"], + location: Literal["top", "bottom", "right", "left"] | float, + functions: tuple[ + Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike] + ] + | Transform, + transform: Transform | None = ..., + **kwargs + ) -> None: ... + def set_alignment( + self, align: Literal["top", "bottom", "right", "left"] + ) -> None: ... + def set_location( + self, + location: Literal["top", "bottom", "right", "left"] | float, + transform: Transform | None = ... + ) -> None: ... + def set_ticks( + self, + ticks: ArrayLike, + labels: Iterable[str] | None = ..., + *, + minor: bool = ..., + **kwargs + ) -> list[Tick]: ... + def set_functions( + self, + functions: tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] | Transform, + ) -> None: ... + def set_aspect(self, *args, **kwargs) -> None: ... + def set_color(self, color: ColorType) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/__init__.py b/python_embeded/Lib/site-packages/matplotlib/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0f682d5d4b4772426ea2ff0e62251ce947a827 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/__init__.py @@ -0,0 +1,5 @@ +from .registry import BackendFilter, backend_registry # noqa: F401 + +# NOTE: plt.switch_backend() (called at import time) will add a "backend" +# attribute here for backcompat. +_QT_FORCE_QT5_BINDING = False diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_backend_agg.pyi b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_agg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_backend_gtk.py b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_gtk.py new file mode 100644 index 0000000000000000000000000000000000000000..ac443730e28a89ffb8c31d9163e343835aa6d9fe --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_gtk.py @@ -0,0 +1,331 @@ +""" +Common code for GTK3 and GTK4 backends. +""" + +import logging +import sys + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + TimerBase) +from matplotlib.backend_tools import Cursors + +import gi +# The GTK3/GTK4 backends will have already called `gi.require_version` to set +# the desired GTK. +from gi.repository import Gdk, Gio, GLib, Gtk + + +try: + gi.require_foreign("cairo") +except ImportError as e: + raise ImportError("Gtk-based backends require cairo") from e + +_log = logging.getLogger(__name__) +_application = None # Placeholder + + +def _shutdown_application(app): + # The application might prematurely shut down if Ctrl-C'd out of IPython, + # so close all windows. + for win in app.get_windows(): + win.close() + # The PyGObject wrapper incorrectly thinks that None is not allowed, or we + # would call this: + # Gio.Application.set_default(None) + # Instead, we set this property and ignore default applications with it: + app._created_by_matplotlib = True + global _application + _application = None + + +def _create_application(): + global _application + + if _application is None: + app = Gio.Application.get_default() + if app is None or getattr(app, '_created_by_matplotlib', False): + # display_is_valid returns False only if on Linux and neither X11 + # nor Wayland display can be opened. + if not mpl._c_internal_utils.display_is_valid(): + raise RuntimeError('Invalid DISPLAY variable') + _application = Gtk.Application.new('org.matplotlib.Matplotlib3', + Gio.ApplicationFlags.NON_UNIQUE) + # The activate signal must be connected, but we don't care for + # handling it, since we don't do any remote processing. + _application.connect('activate', lambda *args, **kwargs: None) + _application.connect('shutdown', _shutdown_application) + _application.register() + cbook._setup_new_guiapp() + else: + _application = app + + return _application + + +def mpl_to_gtk_cursor_name(mpl_cursor): + return _api.check_getitem({ + Cursors.MOVE: "move", + Cursors.HAND: "pointer", + Cursors.POINTER: "default", + Cursors.SELECT_REGION: "crosshair", + Cursors.WAIT: "wait", + Cursors.RESIZE_HORIZONTAL: "ew-resize", + Cursors.RESIZE_VERTICAL: "ns-resize", + }, cursor=mpl_cursor) + + +class TimerGTK(TimerBase): + """Subclass of `.TimerBase` using GTK timer events.""" + + def __init__(self, *args, **kwargs): + self._timer = None + super().__init__(*args, **kwargs) + + def _timer_start(self): + # Need to stop it, otherwise we potentially leak a timer id that will + # never be stopped. + self._timer_stop() + self._timer = GLib.timeout_add(self._interval, self._on_timer) + + def _timer_stop(self): + if self._timer is not None: + GLib.source_remove(self._timer) + self._timer = None + + def _timer_set_interval(self): + # Only stop and restart it if the timer has already been started. + if self._timer is not None: + self._timer_stop() + self._timer_start() + + def _on_timer(self): + super()._on_timer() + + # Gtk timeout_add() requires that the callback returns True if it + # is to be called again. + if self.callbacks and not self._single: + return True + else: + self._timer = None + return False + + +class _FigureCanvasGTK(FigureCanvasBase): + _timer_cls = TimerGTK + + +class _FigureManagerGTK(FigureManagerBase): + """ + Attributes + ---------- + canvas : `FigureCanvas` + The FigureCanvas instance + num : int or str + The Figure number + toolbar : Gtk.Toolbar or Gtk.Box + The toolbar + vbox : Gtk.VBox + The Gtk.VBox containing the canvas and toolbar + window : Gtk.Window + The Gtk.Window + """ + + def __init__(self, canvas, num): + self._gtk_ver = gtk_ver = Gtk.get_major_version() + + app = _create_application() + self.window = Gtk.Window() + app.add_window(self.window) + super().__init__(canvas, num) + + if gtk_ver == 3: + icon_ext = "png" if sys.platform == "win32" else "svg" + self.window.set_icon_from_file( + str(cbook._get_data_path(f"images/matplotlib.{icon_ext}"))) + + self.vbox = Gtk.Box() + self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL) + + if gtk_ver == 3: + self.window.add(self.vbox) + self.vbox.show() + self.canvas.show() + self.vbox.pack_start(self.canvas, True, True, 0) + elif gtk_ver == 4: + self.window.set_child(self.vbox) + self.vbox.prepend(self.canvas) + + # calculate size for window + w, h = self.canvas.get_width_height() + + if self.toolbar is not None: + if gtk_ver == 3: + self.toolbar.show() + self.vbox.pack_end(self.toolbar, False, False, 0) + elif gtk_ver == 4: + sw = Gtk.ScrolledWindow(vscrollbar_policy=Gtk.PolicyType.NEVER) + sw.set_child(self.toolbar) + self.vbox.append(sw) + min_size, nat_size = self.toolbar.get_preferred_size() + h += nat_size.height + + self.window.set_default_size(w, h) + + self._destroying = False + self.window.connect("destroy", lambda *args: Gcf.destroy(self)) + self.window.connect({3: "delete_event", 4: "close-request"}[gtk_ver], + lambda *args: Gcf.destroy(self)) + if mpl.is_interactive(): + self.window.show() + self.canvas.draw_idle() + + self.canvas.grab_focus() + + def destroy(self, *args): + if self._destroying: + # Otherwise, this can be called twice when the user presses 'q', + # which calls Gcf.destroy(self), then this destroy(), then triggers + # Gcf.destroy(self) once again via + # `connect("destroy", lambda *args: Gcf.destroy(self))`. + return + self._destroying = True + self.window.destroy() + self.canvas.destroy() + + @classmethod + def start_main_loop(cls): + global _application + if _application is None: + return + + try: + _application.run() # Quits when all added windows close. + except KeyboardInterrupt: + # Ensure all windows can process their close event from + # _shutdown_application. + context = GLib.MainContext.default() + while context.pending(): + context.iteration(True) + raise + finally: + # Running after quit is undefined, so create a new one next time. + _application = None + + def show(self): + # show the figure window + self.window.show() + self.canvas.draw() + if mpl.rcParams["figure.raise_window"]: + meth_name = {3: "get_window", 4: "get_surface"}[self._gtk_ver] + if getattr(self.window, meth_name)(): + self.window.present() + else: + # If this is called by a callback early during init, + # self.window (a GtkWindow) may not have an associated + # low-level GdkWindow (on GTK3) or GdkSurface (on GTK4) yet, + # and present() would crash. + _api.warn_external("Cannot raise window yet to be setup") + + def full_screen_toggle(self): + is_fullscreen = { + 3: lambda w: (w.get_window().get_state() + & Gdk.WindowState.FULLSCREEN), + 4: lambda w: w.is_fullscreen(), + }[self._gtk_ver] + if is_fullscreen(self.window): + self.window.unfullscreen() + else: + self.window.fullscreen() + + def get_window_title(self): + return self.window.get_title() + + def set_window_title(self, title): + self.window.set_title(title) + + def resize(self, width, height): + width = int(width / self.canvas.device_pixel_ratio) + height = int(height / self.canvas.device_pixel_ratio) + if self.toolbar: + min_size, nat_size = self.toolbar.get_preferred_size() + height += nat_size.height + canvas_size = self.canvas.get_allocation() + if self._gtk_ver >= 4 or canvas_size.width == canvas_size.height == 1: + # A canvas size of (1, 1) cannot exist in most cases, because + # window decorations would prevent such a small window. This call + # must be before the window has been mapped and widgets have been + # sized, so just change the window's starting size. + self.window.set_default_size(width, height) + else: + self.window.resize(width, height) + + +class _NavigationToolbar2GTK(NavigationToolbar2): + # Must be implemented in GTK3/GTK4 backends: + # * __init__ + # * save_figure + + def set_message(self, s): + escaped = GLib.markup_escape_text(s) + self.message.set_markup(f'{escaped}') + + def draw_rubberband(self, event, x0, y0, x1, y1): + height = self.canvas.figure.bbox.height + y1 = height - y1 + y0 = height - y0 + rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] + self.canvas._draw_rubberband(rect) + + def remove_rubberband(self): + self.canvas._draw_rubberband(None) + + def _update_buttons_checked(self): + for name, active in [("Pan", "PAN"), ("Zoom", "ZOOM")]: + button = self._gtk_ids.get(name) + if button: + with button.handler_block(button._signal_handler): + button.set_active(self.mode.name == active) + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if 'Back' in self._gtk_ids: + self._gtk_ids['Back'].set_sensitive(can_backward) + if 'Forward' in self._gtk_ids: + self._gtk_ids['Forward'].set_sensitive(can_forward) + + +class RubberbandGTK(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + _NavigationToolbar2GTK.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + _NavigationToolbar2GTK.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +class ConfigureSubplotsGTK(backend_tools.ConfigureSubplotsBase): + def trigger(self, *args): + _NavigationToolbar2GTK.configure_subplots(self, None) + + +class _BackendGTK(_Backend): + backend_version = "{}.{}.{}".format( + Gtk.get_major_version(), + Gtk.get_minor_version(), + Gtk.get_micro_version(), + ) + mainloop = _FigureManagerGTK.start_main_loop diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_backend_pdf_ps.py b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_pdf_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a878d54156f7fb54ad31c1c109f7a5be23e0ee --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_pdf_ps.py @@ -0,0 +1,189 @@ +""" +Common functionality between the PDF and PS backends. +""" + +from io import BytesIO +import functools +import logging + +from fontTools import subset + +import matplotlib as mpl +from .. import font_manager, ft2font +from .._afm import AFM +from ..backend_bases import RendererBase + + +@functools.lru_cache(50) +def _cached_get_afm_from_fname(fname): + with open(fname, "rb") as fh: + return AFM(fh) + + +def get_glyphs_subset(fontfile, characters): + """ + Subset a TTF font + + Reads the named fontfile and restricts the font to the characters. + + Parameters + ---------- + fontfile : str + Path to the font file + characters : str + Continuous set of characters to include in subset + + Returns + ------- + fontTools.ttLib.ttFont.TTFont + An open font object representing the subset, which needs to + be closed by the caller. + """ + + options = subset.Options(glyph_names=True, recommended_glyphs=True) + + # Prevent subsetting extra tables. + options.drop_tables += [ + 'FFTM', # FontForge Timestamp. + 'PfEd', # FontForge personal table. + 'BDF', # X11 BDF header. + 'meta', # Metadata stores design/supported languages (meaningless for subsets). + 'MERG', # Merge Table. + 'TSIV', # Microsoft Visual TrueType extension. + 'Zapf', # Information about the individual glyphs in the font. + 'bdat', # The bitmap data table. + 'bloc', # The bitmap location table. + 'cidg', # CID to Glyph ID table (Apple Advanced Typography). + 'fdsc', # The font descriptors table. + 'feat', # Feature name table (Apple Advanced Typography). + 'fmtx', # The Font Metrics Table. + 'fond', # Data-fork font information (Apple Advanced Typography). + 'just', # The justification table (Apple Advanced Typography). + 'kerx', # An extended kerning table (Apple Advanced Typography). + 'ltag', # Language Tag. + 'morx', # Extended Glyph Metamorphosis Table. + 'trak', # Tracking table. + 'xref', # The cross-reference table (some Apple font tooling information). + ] + # if fontfile is a ttc, specify font number + if fontfile.endswith(".ttc"): + options.font_number = 0 + + font = subset.load_font(fontfile, options) + subsetter = subset.Subsetter(options=options) + subsetter.populate(text=characters) + subsetter.subset(font) + return font + + +def font_as_file(font): + """ + Convert a TTFont object into a file-like object. + + Parameters + ---------- + font : fontTools.ttLib.ttFont.TTFont + A font object + + Returns + ------- + BytesIO + A file object with the font saved into it + """ + fh = BytesIO() + font.save(fh, reorderTables=False) + return fh + + +class CharacterTracker: + """ + Helper for font subsetting by the pdf and ps backends. + + Maintains a mapping of font paths to the set of character codepoints that + are being used from that font. + """ + + def __init__(self): + self.used = {} + + def track(self, font, s): + """Record that string *s* is being typeset using font *font*.""" + char_to_font = font._get_fontmap(s) + for _c, _f in char_to_font.items(): + self.used.setdefault(_f.fname, set()).add(ord(_c)) + + def track_glyph(self, font, glyph): + """Record that codepoint *glyph* is being typeset using font *font*.""" + self.used.setdefault(font.fname, set()).add(glyph) + + +class RendererPDFPSBase(RendererBase): + # The following attributes must be defined by the subclasses: + # - _afm_font_dir + # - _use_afm_rc_name + + def __init__(self, width, height): + super().__init__() + self.width = width + self.height = height + + def flipy(self): + # docstring inherited + return False # y increases from bottom to top. + + def option_scale_image(self): + # docstring inherited + return True # PDF and PS support arbitrary image scaling. + + def option_image_nocomposite(self): + # docstring inherited + # Decide whether to composite image based on rcParam value. + return not mpl.rcParams["image.composite_image"] + + def get_canvas_width_height(self): + # docstring inherited + return self.width * 72.0, self.height * 72.0 + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + if ismath == "TeX": + return super().get_text_width_height_descent(s, prop, ismath) + elif ismath: + parse = self._text2path.mathtext_parser.parse(s, 72, prop) + return parse.width, parse.height, parse.depth + elif mpl.rcParams[self._use_afm_rc_name]: + font = self._get_font_afm(prop) + l, b, w, h, d = font.get_str_bbox_and_descent(s) + scale = prop.get_size_in_points() / 1000 + w *= scale + h *= scale + d *= scale + return w, h, d + else: + font = self._get_font_ttf(prop) + font.set_text(s, 0.0, flags=ft2font.LoadFlags.NO_HINTING) + w, h = font.get_width_height() + d = font.get_descent() + scale = 1 / 64 + w *= scale + h *= scale + d *= scale + return w, h, d + + def _get_font_afm(self, prop): + fname = font_manager.findfont( + prop, fontext="afm", directory=self._afm_font_dir) + return _cached_get_afm_from_fname(fname) + + def _get_font_ttf(self, prop): + fnames = font_manager.fontManager._find_fonts_by_props(prop) + try: + font = font_manager.get_font(fnames) + font.clear() + font.set_size(prop.get_size_in_points(), 72) + return font + except RuntimeError: + logging.getLogger(__name__).warning( + "The PostScript/PDF backend does not currently " + "support the selected font (%s).", fnames) + raise diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_backend_tk.py b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_tk.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbff1379ffae2adb946a2987d92966b034e01f1 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/_backend_tk.py @@ -0,0 +1,1077 @@ +import uuid +import weakref +from contextlib import contextmanager +import logging +import math +import os.path +import pathlib +import sys +import tkinter as tk +import tkinter.filedialog +import tkinter.font +import tkinter.messagebox +from tkinter.simpledialog import SimpleDialog + +import numpy as np +from PIL import Image, ImageTk + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook, _c_internal_utils +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + TimerBase, ToolContainerBase, cursors, _Mode, MouseButton, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent) +from matplotlib._pylab_helpers import Gcf +from . import _tkagg +from ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET + + +_log = logging.getLogger(__name__) +cursord = { + cursors.MOVE: "fleur", + cursors.HAND: "hand2", + cursors.POINTER: "arrow", + cursors.SELECT_REGION: "crosshair", + cursors.WAIT: "watch", + cursors.RESIZE_HORIZONTAL: "sb_h_double_arrow", + cursors.RESIZE_VERTICAL: "sb_v_double_arrow", +} + + +@contextmanager +def _restore_foreground_window_at_end(): + foreground = _c_internal_utils.Win32_GetForegroundWindow() + try: + yield + finally: + if foreground and mpl.rcParams['tk.window_focus']: + _c_internal_utils.Win32_SetForegroundWindow(foreground) + + +_blit_args = {} +# Initialize to a non-empty string that is not a Tcl command +_blit_tcl_name = "mpl_blit_" + uuid.uuid4().hex + + +def _blit(argsid): + """ + Thin wrapper to blit called via tkapp.call. + + *argsid* is a unique string identifier to fetch the correct arguments from + the ``_blit_args`` dict, since arguments cannot be passed directly. + """ + photoimage, data, offsets, bbox, comp_rule = _blit_args.pop(argsid) + if not photoimage.tk.call("info", "commands", photoimage): + return + _tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets, + bbox) + + +def blit(photoimage, aggimage, offsets, bbox=None): + """ + Blit *aggimage* to *photoimage*. + + *offsets* is a tuple describing how to fill the ``offset`` field of the + ``Tk_PhotoImageBlock`` struct: it should be (0, 1, 2, 3) for RGBA8888 data, + (2, 1, 0, 3) for little-endian ARBG32 (i.e. GBRA8888) data and (1, 2, 3, 0) + for big-endian ARGB32 (i.e. ARGB8888) data. + + If *bbox* is passed, it defines the region that gets blitted. That region + will be composed with the previous data according to the alpha channel. + Blitting will be clipped to pixels inside the canvas, including silently + doing nothing if the *bbox* region is entirely outside the canvas. + + Tcl events must be dispatched to trigger a blit from a non-Tcl thread. + """ + data = np.asarray(aggimage) + height, width = data.shape[:2] + if bbox is not None: + (x1, y1), (x2, y2) = bbox.__array__() + x1 = max(math.floor(x1), 0) + x2 = min(math.ceil(x2), width) + y1 = max(math.floor(y1), 0) + y2 = min(math.ceil(y2), height) + if (x1 > x2) or (y1 > y2): + return + bboxptr = (x1, x2, y1, y2) + comp_rule = TK_PHOTO_COMPOSITE_OVERLAY + else: + bboxptr = (0, width, 0, height) + comp_rule = TK_PHOTO_COMPOSITE_SET + + # NOTE: _tkagg.blit is thread unsafe and will crash the process if called + # from a thread (GH#13293). Instead of blanking and blitting here, + # use tkapp.call to post a cross-thread event if this function is called + # from a non-Tcl thread. + + # tkapp.call coerces all arguments to strings, so to avoid string parsing + # within _blit, pack up the arguments into a global data structure. + args = photoimage, data, offsets, bboxptr, comp_rule + # Need a unique key to avoid thread races. + # Again, make the key a string to avoid string parsing in _blit. + argsid = str(id(args)) + _blit_args[argsid] = args + + try: + photoimage.tk.call(_blit_tcl_name, argsid) + except tk.TclError as e: + if "invalid command name" not in str(e): + raise + photoimage.tk.createcommand(_blit_tcl_name, _blit) + photoimage.tk.call(_blit_tcl_name, argsid) + + +class TimerTk(TimerBase): + """Subclass of `backend_bases.TimerBase` using Tk timer events.""" + + def __init__(self, parent, *args, **kwargs): + self._timer = None + super().__init__(*args, **kwargs) + self.parent = parent + + def _timer_start(self): + self._timer_stop() + self._timer = self.parent.after(self._interval, self._on_timer) + + def _timer_stop(self): + if self._timer is not None: + self.parent.after_cancel(self._timer) + self._timer = None + + def _on_timer(self): + super()._on_timer() + # Tk after() is only a single shot, so we need to add code here to + # reset the timer if we're not operating in single shot mode. However, + # if _timer is None, this means that _timer_stop has been called; so + # don't recreate the timer in that case. + if not self._single and self._timer: + if self._interval > 0: + self._timer = self.parent.after(self._interval, self._on_timer) + else: + # Edge case: Tcl after 0 *prepends* events to the queue + # so a 0 interval does not allow any other events to run. + # This incantation is cancellable and runs as fast as possible + # while also allowing events and drawing every frame. GH#18236 + self._timer = self.parent.after_idle( + lambda: self.parent.after(self._interval, self._on_timer) + ) + else: + self._timer = None + + +class FigureCanvasTk(FigureCanvasBase): + required_interactive_framework = "tk" + manager_class = _api.classproperty(lambda cls: FigureManagerTk) + + def __init__(self, figure=None, master=None): + super().__init__(figure) + self._idle_draw_id = None + self._event_loop_id = None + w, h = self.get_width_height(physical=True) + self._tkcanvas = tk.Canvas( + master=master, background="white", + width=w, height=h, borderwidth=0, highlightthickness=0) + self._tkphoto = tk.PhotoImage( + master=self._tkcanvas, width=w, height=h) + self._tkcanvas_image_region = self._tkcanvas.create_image( + w//2, h//2, image=self._tkphoto) + self._tkcanvas.bind("", self.resize) + self._tkcanvas.bind("", self._update_device_pixel_ratio) + self._tkcanvas.bind("", self.key_press) + self._tkcanvas.bind("", self.motion_notify_event) + self._tkcanvas.bind("", self.enter_notify_event) + self._tkcanvas.bind("", self.leave_notify_event) + self._tkcanvas.bind("", self.key_release) + for name in ["", "", ""]: + self._tkcanvas.bind(name, self.button_press_event) + for name in [ + "", "", ""]: + self._tkcanvas.bind(name, self.button_dblclick_event) + for name in [ + "", "", ""]: + self._tkcanvas.bind(name, self.button_release_event) + + # Mouse wheel on Linux generates button 4/5 events + for name in "", "": + self._tkcanvas.bind(name, self.scroll_event) + # Mouse wheel for windows goes to the window with the focus. + # Since the canvas won't usually have the focus, bind the + # event to the window containing the canvas instead. + # See https://wiki.tcl-lang.org/3893 (mousewheel) for details + root = self._tkcanvas.winfo_toplevel() + + # Prevent long-lived references via tkinter callback structure GH-24820 + weakself = weakref.ref(self) + weakroot = weakref.ref(root) + + def scroll_event_windows(event): + self = weakself() + if self is None: + root = weakroot() + if root is not None: + root.unbind("", scroll_event_windows_id) + return + return self.scroll_event_windows(event) + scroll_event_windows_id = root.bind("", scroll_event_windows, "+") + + # Can't get destroy events by binding to _tkcanvas. Therefore, bind + # to the window and filter. + def filter_destroy(event): + self = weakself() + if self is None: + root = weakroot() + if root is not None: + root.unbind("", filter_destroy_id) + return + if event.widget is self._tkcanvas: + CloseEvent("close_event", self)._process() + filter_destroy_id = root.bind("", filter_destroy, "+") + + self._tkcanvas.focus_set() + + self._rubberband_rect_black = None + self._rubberband_rect_white = None + + def _update_device_pixel_ratio(self, event=None): + ratio = None + if sys.platform == 'win32': + # Tk gives scaling with respect to 72 DPI, but Windows screens are + # scaled vs 96 dpi, and pixel ratio settings are given in whole + # percentages, so round to 2 digits. + ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2) + elif sys.platform == "linux": + ratio = self._tkcanvas.winfo_fpixels('1i') / 96 + if ratio is not None and self._set_device_pixel_ratio(ratio): + # The easiest way to resize the canvas is to resize the canvas + # widget itself, since we implement all the logic for resizing the + # canvas backing store on that event. + w, h = self.get_width_height(physical=True) + self._tkcanvas.configure(width=w, height=h) + + def resize(self, event): + width, height = event.width, event.height + + # compute desired figure size in inches + dpival = self.figure.dpi + winch = width / dpival + hinch = height / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + + self._tkcanvas.delete(self._tkcanvas_image_region) + self._tkphoto.configure(width=int(width), height=int(height)) + self._tkcanvas_image_region = self._tkcanvas.create_image( + int(width / 2), int(height / 2), image=self._tkphoto) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + def draw_idle(self): + # docstring inherited + if self._idle_draw_id: + return + + def idle_draw(*args): + try: + self.draw() + finally: + self._idle_draw_id = None + + self._idle_draw_id = self._tkcanvas.after_idle(idle_draw) + + def get_tk_widget(self): + """ + Return the Tk widget used to implement FigureCanvasTkAgg. + + Although the initial implementation uses a Tk canvas, this routine + is intended to hide that fact. + """ + return self._tkcanvas + + def _event_mpl_coords(self, event): + # calling canvasx/canvasy allows taking scrollbars into account (i.e. + # the top of the widget may have been scrolled out of view). + return (self._tkcanvas.canvasx(event.x), + # flipy so y=0 is bottom of canvas + self.figure.bbox.height - self._tkcanvas.canvasy(event.y)) + + def motion_notify_event(self, event): + MouseEvent("motion_notify_event", self, + *self._event_mpl_coords(event), + buttons=self._mpl_buttons(event), + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def enter_notify_event(self, event): + LocationEvent("figure_enter_event", self, + *self._event_mpl_coords(event), + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def leave_notify_event(self, event): + LocationEvent("figure_leave_event", self, + *self._event_mpl_coords(event), + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def button_press_event(self, event, dblclick=False): + # set focus to the canvas so that it can receive keyboard events + self._tkcanvas.focus_set() + + num = getattr(event, 'num', None) + if sys.platform == 'darwin': # 2 and 3 are reversed. + num = {2: 3, 3: 2}.get(num, num) + MouseEvent("button_press_event", self, + *self._event_mpl_coords(event), num, dblclick=dblclick, + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def button_dblclick_event(self, event): + self.button_press_event(event, dblclick=True) + + def button_release_event(self, event): + num = getattr(event, 'num', None) + if sys.platform == 'darwin': # 2 and 3 are reversed. + num = {2: 3, 3: 2}.get(num, num) + MouseEvent("button_release_event", self, + *self._event_mpl_coords(event), num, + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def scroll_event(self, event): + num = getattr(event, 'num', None) + step = 1 if num == 4 else -1 if num == 5 else 0 + MouseEvent("scroll_event", self, + *self._event_mpl_coords(event), step=step, + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def scroll_event_windows(self, event): + """MouseWheel event processor""" + # need to find the window that contains the mouse + w = event.widget.winfo_containing(event.x_root, event.y_root) + if w != self._tkcanvas: + return + x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx()) + y = (self.figure.bbox.height + - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty())) + step = event.delta / 120 + MouseEvent("scroll_event", self, + x, y, step=step, modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + @staticmethod + def _mpl_buttons(event): # See _mpl_modifiers. + # NOTE: This fails to report multiclicks on macOS; only one button is + # reported (multiclicks work correctly on Linux & Windows). + modifiers = [ + # macOS appears to swap right and middle (look for "Swap buttons + # 2/3" in tk/macosx/tkMacOSXMouseEvent.c). + (MouseButton.LEFT, 1 << 8), + (MouseButton.RIGHT, 1 << 9), + (MouseButton.MIDDLE, 1 << 10), + (MouseButton.BACK, 1 << 11), + (MouseButton.FORWARD, 1 << 12), + ] if sys.platform == "darwin" else [ + (MouseButton.LEFT, 1 << 8), + (MouseButton.MIDDLE, 1 << 9), + (MouseButton.RIGHT, 1 << 10), + (MouseButton.BACK, 1 << 11), + (MouseButton.FORWARD, 1 << 12), + ] + # State *before* press/release. + return [name for name, mask in modifiers if event.state & mask] + + @staticmethod + def _mpl_modifiers(event, *, exclude=None): + # Add modifier keys to the key string. Bit values are inferred from + # the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... = + # Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5) + # In general, the modifier key is excluded from the modifier flag, + # however this is not the case on "darwin", so double check that + # we aren't adding repeat modifier flags to a modifier key. + modifiers = [ + ("ctrl", 1 << 2, "control"), + ("alt", 1 << 17, "alt"), + ("shift", 1 << 0, "shift"), + ] if sys.platform == "win32" else [ + ("ctrl", 1 << 2, "control"), + ("alt", 1 << 4, "alt"), + ("shift", 1 << 0, "shift"), + ("cmd", 1 << 3, "cmd"), + ] if sys.platform == "darwin" else [ + ("ctrl", 1 << 2, "control"), + ("alt", 1 << 3, "alt"), + ("shift", 1 << 0, "shift"), + ("super", 1 << 6, "super"), + ] + return [name for name, mask, key in modifiers + if event.state & mask and exclude != key] + + def _get_key(self, event): + unikey = event.char + key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym) + if key is not None: + mods = self._mpl_modifiers(event, exclude=key) + # shift is not added to the keys as this is already accounted for. + if "shift" in mods and unikey: + mods.remove("shift") + return "+".join([*mods, key]) + + def key_press(self, event): + KeyEvent("key_press_event", self, + self._get_key(event), *self._event_mpl_coords(event), + guiEvent=event)._process() + + def key_release(self, event): + KeyEvent("key_release_event", self, + self._get_key(event), *self._event_mpl_coords(event), + guiEvent=event)._process() + + def new_timer(self, *args, **kwargs): + # docstring inherited + return TimerTk(self._tkcanvas, *args, **kwargs) + + def flush_events(self): + # docstring inherited + self._tkcanvas.update() + + def start_event_loop(self, timeout=0): + # docstring inherited + if timeout > 0: + milliseconds = int(1000 * timeout) + if milliseconds > 0: + self._event_loop_id = self._tkcanvas.after( + milliseconds, self.stop_event_loop) + else: + self._event_loop_id = self._tkcanvas.after_idle( + self.stop_event_loop) + self._tkcanvas.mainloop() + + def stop_event_loop(self): + # docstring inherited + if self._event_loop_id: + self._tkcanvas.after_cancel(self._event_loop_id) + self._event_loop_id = None + self._tkcanvas.quit() + + def set_cursor(self, cursor): + try: + self._tkcanvas.configure(cursor=cursord[cursor]) + except tkinter.TclError: + pass + + +class FigureManagerTk(FigureManagerBase): + """ + Attributes + ---------- + canvas : `FigureCanvas` + The FigureCanvas instance + num : int or str + The Figure number + toolbar : tk.Toolbar + The tk.Toolbar + window : tk.Window + The tk.Window + """ + + _owns_mainloop = False + + def __init__(self, canvas, num, window): + self.window = window + super().__init__(canvas, num) + self.window.withdraw() + # packing toolbar first, because if space is getting low, last packed + # widget is getting shrunk first (-> the canvas) + self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) + + # If the window has per-monitor DPI awareness, then setup a Tk variable + # to store the DPI, which will be updated by the C code, and the trace + # will handle it on the Python side. + window_frame = int(window.wm_frame(), 16) + self._window_dpi = tk.IntVar(master=window, value=96, + name=f'window_dpi{window_frame}') + self._window_dpi_cbname = '' + if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()): + self._window_dpi_cbname = self._window_dpi.trace_add( + 'write', self._update_window_dpi) + + self._shown = False + + @classmethod + def create_with_canvas(cls, canvas_class, figure, num): + # docstring inherited + with _restore_foreground_window_at_end(): + if cbook._get_running_interactive_framework() is None: + cbook._setup_new_guiapp() + _c_internal_utils.Win32_SetProcessDpiAwareness_max() + window = tk.Tk(className="matplotlib") + window.withdraw() + + # Put a Matplotlib icon on the window rather than the default tk + # icon. See https://www.tcl.tk/man/tcl/TkCmd/wm.html#M50 + # + # `ImageTk` can be replaced with `tk` whenever the minimum + # supported Tk version is increased to 8.6, as Tk 8.6+ natively + # supports PNG images. + icon_fname = str(cbook._get_data_path( + 'images/matplotlib.png')) + icon_img = ImageTk.PhotoImage(file=icon_fname, master=window) + + icon_fname_large = str(cbook._get_data_path( + 'images/matplotlib_large.png')) + icon_img_large = ImageTk.PhotoImage( + file=icon_fname_large, master=window) + + window.iconphoto(False, icon_img_large, icon_img) + + canvas = canvas_class(figure, master=window) + manager = cls(canvas, num, window) + if mpl.is_interactive(): + manager.show() + canvas.draw_idle() + return manager + + @classmethod + def start_main_loop(cls): + managers = Gcf.get_all_fig_managers() + if managers: + first_manager = managers[0] + manager_class = type(first_manager) + if manager_class._owns_mainloop: + return + manager_class._owns_mainloop = True + try: + first_manager.window.mainloop() + finally: + manager_class._owns_mainloop = False + + def _update_window_dpi(self, *args): + newdpi = self._window_dpi.get() + self.window.call('tk', 'scaling', newdpi / 72) + if self.toolbar and hasattr(self.toolbar, '_rescale'): + self.toolbar._rescale() + self.canvas._update_device_pixel_ratio() + + def resize(self, width, height): + max_size = 1_400_000 # the measured max on xorg 1.20.8 was 1_409_023 + + if (width > max_size or height > max_size) and sys.platform == 'linux': + raise ValueError( + 'You have requested to resize the ' + f'Tk window to ({width}, {height}), one of which ' + f'is bigger than {max_size}. At larger sizes xorg will ' + 'either exit with an error on newer versions (~1.20) or ' + 'cause corruption on older version (~1.19). We ' + 'do not expect a window over a million pixel wide or tall ' + 'to be intended behavior.') + self.canvas._tkcanvas.configure(width=width, height=height) + + def show(self): + with _restore_foreground_window_at_end(): + if not self._shown: + def destroy(*args): + Gcf.destroy(self) + self.window.protocol("WM_DELETE_WINDOW", destroy) + self.window.deiconify() + self.canvas._tkcanvas.focus_set() + else: + self.canvas.draw_idle() + if mpl.rcParams['figure.raise_window']: + self.canvas.manager.window.attributes('-topmost', 1) + self.canvas.manager.window.attributes('-topmost', 0) + self._shown = True + + def destroy(self, *args): + if self.canvas._idle_draw_id: + self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id) + if self.canvas._event_loop_id: + self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id) + if self._window_dpi_cbname: + self._window_dpi.trace_remove('write', self._window_dpi_cbname) + + # NOTE: events need to be flushed before issuing destroy (GH #9956), + # however, self.window.update() can break user code. An async callback + # is the safest way to achieve a complete draining of the event queue, + # but it leaks if no tk event loop is running. Therefore we explicitly + # check for an event loop and choose our best guess. + def delayed_destroy(): + self.window.destroy() + + if self._owns_mainloop and not Gcf.get_num_fig_managers(): + self.window.quit() + + if cbook._get_running_interactive_framework() == "tk": + # "after idle after 0" avoids Tcl error/race (GH #19940) + self.window.after_idle(self.window.after, 0, delayed_destroy) + else: + self.window.update() + delayed_destroy() + + def get_window_title(self): + return self.window.wm_title() + + def set_window_title(self, title): + self.window.wm_title(title) + + def full_screen_toggle(self): + is_fullscreen = bool(self.window.attributes('-fullscreen')) + self.window.attributes('-fullscreen', not is_fullscreen) + + +class NavigationToolbar2Tk(NavigationToolbar2, tk.Frame): + def __init__(self, canvas, window=None, *, pack_toolbar=True): + """ + Parameters + ---------- + canvas : `FigureCanvas` + The figure canvas on which to operate. + window : tk.Window + The tk.Window which owns this toolbar. + pack_toolbar : bool, default: True + If True, add the toolbar to the parent's pack manager's packing + list during initialization with ``side="bottom"`` and ``fill="x"``. + If you want to use the toolbar with a different layout manager, use + ``pack_toolbar=False``. + """ + + if window is None: + window = canvas.get_tk_widget().master + tk.Frame.__init__(self, master=window, borderwidth=2, + width=int(canvas.figure.bbox.width), height=50) + + self._buttons = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + # Add a spacer; return value is unused. + self._Spacer() + else: + self._buttons[text] = button = self._Button( + text, + str(cbook._get_data_path(f"images/{image_file}.png")), + toggle=callback in ["zoom", "pan"], + command=getattr(self, callback), + ) + if tooltip_text is not None: + add_tooltip(button, tooltip_text) + + self._label_font = tkinter.font.Font(root=window, size=10) + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = tk.Label(master=self, font=self._label_font, + text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.pack(side=tk.RIGHT) + + self.message = tk.StringVar(master=self) + self._message_label = tk.Label(master=self, font=self._label_font, + textvariable=self.message, + justify=tk.RIGHT) + self._message_label.pack(side=tk.RIGHT) + + NavigationToolbar2.__init__(self, canvas) + if pack_toolbar: + self.pack(side=tk.BOTTOM, fill=tk.X) + + def _rescale(self): + """ + Scale all children of the toolbar to current DPI setting. + + Before this is called, the Tk scaling setting will have been updated to + match the new DPI. Tk widgets do not update for changes to scaling, but + all measurements made after the change will match the new scaling. Thus + this function re-applies all the same sizes in points, which Tk will + scale correctly to pixels. + """ + for widget in self.winfo_children(): + if isinstance(widget, (tk.Button, tk.Checkbutton)): + if hasattr(widget, '_image_file'): + # Explicit class because ToolbarTk calls _rescale. + NavigationToolbar2Tk._set_image_for_button(self, widget) + else: + # Text-only button is handled by the font setting instead. + pass + elif isinstance(widget, tk.Frame): + widget.configure(height='18p') + widget.pack_configure(padx='3p') + elif isinstance(widget, tk.Label): + pass # Text is handled by the font setting instead. + else: + _log.warning('Unknown child class %s', widget.winfo_class) + self._label_font.configure(size=10) + + def _update_buttons_checked(self): + # sync button checkstates to match active mode + for text, mode in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]: + if text in self._buttons: + if self.mode == mode: + self._buttons[text].select() # NOT .invoke() + else: + self._buttons[text].deselect() + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def set_message(self, s): + self.message.set(s) + + def draw_rubberband(self, event, x0, y0, x1, y1): + # Block copied from remove_rubberband for backend_tools convenience. + if self.canvas._rubberband_rect_white: + self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white) + if self.canvas._rubberband_rect_black: + self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black) + height = self.canvas.figure.bbox.height + y0 = height - y0 + y1 = height - y1 + self.canvas._rubberband_rect_black = ( + self.canvas._tkcanvas.create_rectangle( + x0, y0, x1, y1)) + self.canvas._rubberband_rect_white = ( + self.canvas._tkcanvas.create_rectangle( + x0, y0, x1, y1, outline='white', dash=(3, 3))) + + def remove_rubberband(self): + if self.canvas._rubberband_rect_white: + self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white) + self.canvas._rubberband_rect_white = None + if self.canvas._rubberband_rect_black: + self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black) + self.canvas._rubberband_rect_black = None + + def _set_image_for_button(self, button): + """ + Set the image for a button based on its pixel size. + + The pixel size is determined by the DPI scaling of the window. + """ + if button._image_file is None: + return + + # Allow _image_file to be relative to Matplotlib's "images" data + # directory. + path_regular = cbook._get_data_path('images', button._image_file) + path_large = path_regular.with_name( + path_regular.name.replace('.png', '_large.png')) + size = button.winfo_pixels('18p') + + # Nested functions because ToolbarTk calls _Button. + def _get_color(color_name): + # `winfo_rgb` returns an (r, g, b) tuple in the range 0-65535 + return button.winfo_rgb(button.cget(color_name)) + + def _is_dark(color): + if isinstance(color, str): + color = _get_color(color) + return max(color) < 65535 / 2 + + def _recolor_icon(image, color): + image_data = np.asarray(image).copy() + black_mask = (image_data[..., :3] == 0).all(axis=-1) + image_data[black_mask, :3] = color + return Image.fromarray(image_data, mode="RGBA") + + # Use the high-resolution (48x48 px) icon if it exists and is needed + with Image.open(path_large if (size > 24 and path_large.exists()) + else path_regular) as im: + # assure a RGBA image as foreground color is RGB + im = im.convert("RGBA") + image = ImageTk.PhotoImage(im.resize((size, size)), master=self) + button._ntimage = image + + # create a version of the icon with the button's text color + foreground = (255 / 65535) * np.array( + button.winfo_rgb(button.cget("foreground"))) + im_alt = _recolor_icon(im, foreground) + image_alt = ImageTk.PhotoImage( + im_alt.resize((size, size)), master=self) + button._ntimage_alt = image_alt + + if _is_dark("background"): + # For Checkbuttons, we need to set `image` and `selectimage` at + # the same time. Otherwise, when updating the `image` option + # (such as when changing DPI), if the old `selectimage` has + # just been overwritten, Tk will throw an error. + image_kwargs = {"image": image_alt} + else: + image_kwargs = {"image": image} + # Checkbuttons may switch the background to `selectcolor` in the + # checked state, so check separately which image it needs to use in + # that state to still ensure enough contrast with the background. + if ( + isinstance(button, tk.Checkbutton) + and button.cget("selectcolor") != "" + ): + if self._windowingsystem != "x11": + selectcolor = "selectcolor" + else: + # On X11, selectcolor isn't used directly for indicator-less + # buttons. See `::tk::CheckEnter` in the Tk button.tcl source + # code for details. + r1, g1, b1 = _get_color("selectcolor") + r2, g2, b2 = _get_color("activebackground") + selectcolor = ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2) + if _is_dark(selectcolor): + image_kwargs["selectimage"] = image_alt + else: + image_kwargs["selectimage"] = image + + button.configure(**image_kwargs, height='18p', width='18p') + + def _Button(self, text, image_file, toggle, command): + if not toggle: + b = tk.Button( + master=self, text=text, command=command, + relief="flat", overrelief="groove", borderwidth=1, + ) + else: + # There is a bug in tkinter included in some python 3.6 versions + # that without this variable, produces a "visual" toggling of + # other near checkbuttons + # https://bugs.python.org/issue29402 + # https://bugs.python.org/issue25684 + var = tk.IntVar(master=self) + b = tk.Checkbutton( + master=self, text=text, command=command, indicatoron=False, + variable=var, offrelief="flat", overrelief="groove", + borderwidth=1 + ) + b.var = var + b._image_file = image_file + if image_file is not None: + # Explicit class because ToolbarTk calls _Button. + NavigationToolbar2Tk._set_image_for_button(self, b) + else: + b.configure(font=self._label_font) + b.pack(side=tk.LEFT) + return b + + def _Spacer(self): + # Buttons are also 18pt high. + s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray') + s.pack(side=tk.LEFT, padx='3p') + return s + + def save_figure(self, *args): + filetypes = self.canvas.get_supported_filetypes_grouped() + tk_filetypes = [ + (name, " ".join(f"*.{ext}" for ext in exts)) + for name, exts in sorted(filetypes.items()) + ] + + default_extension = self.canvas.get_default_filetype() + default_filetype = self.canvas.get_supported_filetypes()[default_extension] + filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype) + + # adding a default extension seems to break the + # asksaveasfilename dialog when you choose various save types + # from the dropdown. Passing in the empty string seems to + # work - JDH! + # defaultextension = self.canvas.get_default_filetype() + defaultextension = '' + initialdir = os.path.expanduser(mpl.rcParams['savefig.directory']) + # get_default_filename() contains the default extension. On some platforms, + # choosing a different extension from the dropdown does not overwrite it, + # so we need to remove it to make the dropdown functional. + initialfile = pathlib.Path(self.canvas.get_default_filename()).stem + fname = tkinter.filedialog.asksaveasfilename( + master=self.canvas.get_tk_widget().master, + title='Save the figure', + filetypes=tk_filetypes, + defaultextension=defaultextension, + initialdir=initialdir, + initialfile=initialfile, + typevariable=filetype_variable + ) + + if fname in ["", ()]: + return None + # Save dir for next time, unless empty str (i.e., use cwd). + if initialdir != "": + mpl.rcParams['savefig.directory'] = ( + os.path.dirname(str(fname))) + + # If the filename contains an extension, let savefig() infer the file + # format from that. If it does not, use the selected dropdown option. + if pathlib.Path(fname).suffix[1:] != "": + extension = None + else: + extension = filetypes[filetype_variable.get()][0] + + try: + self.canvas.figure.savefig(fname, format=extension) + return fname + except Exception as e: + tkinter.messagebox.showerror("Error saving file", str(e)) + + def set_history_buttons(self): + state_map = {True: tk.NORMAL, False: tk.DISABLED} + can_back = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if "Back" in self._buttons: + self._buttons['Back']['state'] = state_map[can_back] + if "Forward" in self._buttons: + self._buttons['Forward']['state'] = state_map[can_forward] + + +def add_tooltip(widget, text): + tipwindow = None + + def showtip(event): + """Display text in tooltip window.""" + nonlocal tipwindow + if tipwindow or not text: + return + x, y, _, _ = widget.bbox("insert") + x = x + widget.winfo_rootx() + widget.winfo_width() + y = y + widget.winfo_rooty() + tipwindow = tk.Toplevel(widget) + tipwindow.overrideredirect(1) + tipwindow.geometry(f"+{x}+{y}") + try: # For Mac OS + tipwindow.tk.call("::tk::unsupported::MacWindowStyle", + "style", tipwindow._w, + "help", "noActivates") + except tk.TclError: + pass + label = tk.Label(tipwindow, text=text, justify=tk.LEFT, + relief=tk.SOLID, borderwidth=1) + label.pack(ipadx=1) + + def hidetip(event): + nonlocal tipwindow + if tipwindow: + tipwindow.destroy() + tipwindow = None + + widget.bind("", showtip) + widget.bind("", hidetip) + + +@backend_tools._register_tool_class(FigureCanvasTk) +class RubberbandTk(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + NavigationToolbar2Tk.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + NavigationToolbar2Tk.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +class ToolbarTk(ToolContainerBase, tk.Frame): + def __init__(self, toolmanager, window=None): + ToolContainerBase.__init__(self, toolmanager) + if window is None: + window = self.toolmanager.canvas.get_tk_widget().master + xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx + height, width = 50, xmax - xmin + tk.Frame.__init__(self, master=window, + width=int(width), height=int(height), + borderwidth=2) + self._label_font = tkinter.font.Font(size=10) + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = tk.Label(master=self, font=self._label_font, + text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.pack(side=tk.RIGHT) + self._message = tk.StringVar(master=self) + self._message_label = tk.Label(master=self, font=self._label_font, + textvariable=self._message) + self._message_label.pack(side=tk.RIGHT) + self._toolitems = {} + self.pack(side=tk.TOP, fill=tk.X) + self._groups = {} + + def _rescale(self): + return NavigationToolbar2Tk._rescale(self) + + def add_toolitem( + self, name, group, position, image_file, description, toggle): + frame = self._get_groupframe(group) + buttons = frame.pack_slaves() + if position >= len(buttons) or position < 0: + before = None + else: + before = buttons[position] + button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle, + lambda: self._button_click(name)) + button.pack_configure(before=before) + if description is not None: + add_tooltip(button, description) + self._toolitems.setdefault(name, []) + self._toolitems[name].append(button) + + def _get_groupframe(self, group): + if group not in self._groups: + if self._groups: + self._add_separator() + frame = tk.Frame(master=self, borderwidth=0) + frame.pack(side=tk.LEFT, fill=tk.Y) + frame._label_font = self._label_font + self._groups[group] = frame + return self._groups[group] + + def _add_separator(self): + return NavigationToolbar2Tk._Spacer(self) + + def _button_click(self, name): + self.trigger_tool(name) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for toolitem in self._toolitems[name]: + if toggled: + toolitem.select() + else: + toolitem.deselect() + + def remove_toolitem(self, name): + for toolitem in self._toolitems.pop(name, []): + toolitem.pack_forget() + + def set_message(self, s): + self._message.set(s) + + +@backend_tools._register_tool_class(FigureCanvasTk) +class SaveFigureTk(backend_tools.SaveFigureBase): + def trigger(self, *args): + NavigationToolbar2Tk.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasTk) +class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase): + def trigger(self, *args): + NavigationToolbar2Tk.configure_subplots(self) + + +@backend_tools._register_tool_class(FigureCanvasTk) +class HelpTk(backend_tools.ToolHelpBase): + def trigger(self, *args): + dialog = SimpleDialog( + self.figure.canvas._tkcanvas, self._get_help_text(), ["OK"]) + dialog.done = lambda num: dialog.frame.master.withdraw() + + +Toolbar = ToolbarTk +FigureManagerTk._toolbar2_class = NavigationToolbar2Tk +FigureManagerTk._toolmanager_toolbar_class = ToolbarTk + + +@_Backend.export +class _BackendTk(_Backend): + backend_version = tk.TkVersion + FigureCanvas = FigureCanvasTk + FigureManager = FigureManagerTk + mainloop = FigureManagerTk.start_main_loop diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_macosx.pyi b/python_embeded/Lib/site-packages/matplotlib/backends/_macosx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/_tkagg.pyi b/python_embeded/Lib/site-packages/matplotlib/backends/_tkagg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5c3f1112ec7c594b0377a2a89e738770e0737400 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/_tkagg.pyi @@ -0,0 +1,15 @@ +import numpy as np +from numpy.typing import NDArray + +TK_PHOTO_COMPOSITE_OVERLAY: int +TK_PHOTO_COMPOSITE_SET: int + +def blit( + interp: int, + photo_name: str, + data: NDArray[np.uint8], + comp_rule: int, + offset: tuple[int, int, int, int], + bbox: tuple[int, int, int, int], +) -> None: ... +def enable_dpi_awareness(frame_handle: int, interp: int) -> bool | None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_agg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_agg.py new file mode 100644 index 0000000000000000000000000000000000000000..c3742736926771328d526e1550a0e9ffefb9183d --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_agg.py @@ -0,0 +1,528 @@ +""" +An `Anti-Grain Geometry`_ (AGG) backend. + +Features that are implemented: + +* capstyles and join styles +* dashes +* linewidth +* lines, rectangles, ellipses +* clipping to a rectangle +* output to RGBA and Pillow-supported image formats +* alpha blending +* DPI scaling properly - everything scales properly (dashes, linewidths, etc) +* draw polygon +* freetype2 w/ ft2font + +Still TODO: + +* integrate screen dpi w/ ppi and text + +.. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com +""" + +from contextlib import nullcontext +from math import radians, cos, sin + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) +from matplotlib.font_manager import fontManager as _fontManager, get_font +from matplotlib.ft2font import LoadFlags +from matplotlib.mathtext import MathTextParser +from matplotlib.path import Path +from matplotlib.transforms import Bbox, BboxBase +from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg + + +def get_hinting_flag(): + mapping = { + 'default': LoadFlags.DEFAULT, + 'no_autohint': LoadFlags.NO_AUTOHINT, + 'force_autohint': LoadFlags.FORCE_AUTOHINT, + 'no_hinting': LoadFlags.NO_HINTING, + True: LoadFlags.FORCE_AUTOHINT, + False: LoadFlags.NO_HINTING, + 'either': LoadFlags.DEFAULT, + 'native': LoadFlags.NO_AUTOHINT, + 'auto': LoadFlags.FORCE_AUTOHINT, + 'none': LoadFlags.NO_HINTING, + } + return mapping[mpl.rcParams['text.hinting']] + + +class RendererAgg(RendererBase): + """ + The renderer handles all the drawing primitives using a graphics + context instance that controls the colors/styles + """ + + def __init__(self, width, height, dpi): + super().__init__() + + self.dpi = dpi + self.width = width + self.height = height + self._renderer = _RendererAgg(int(width), int(height), dpi) + self._filter_renderers = [] + + self._update_methods() + self.mathtext_parser = MathTextParser('agg') + + self.bbox = Bbox.from_bounds(0, 0, self.width, self.height) + + def __getstate__(self): + # We only want to preserve the init keywords of the Renderer. + # Anything else can be re-created. + return {'width': self.width, 'height': self.height, 'dpi': self.dpi} + + def __setstate__(self, state): + self.__init__(state['width'], state['height'], state['dpi']) + + def _update_methods(self): + self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles + self.draw_image = self._renderer.draw_image + self.draw_markers = self._renderer.draw_markers + self.draw_path_collection = self._renderer.draw_path_collection + self.draw_quad_mesh = self._renderer.draw_quad_mesh + self.copy_from_bbox = self._renderer.copy_from_bbox + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing + npts = path.vertices.shape[0] + + if (npts > nmax > 100 and path.should_simplify and + rgbFace is None and gc.get_hatch() is None): + nch = np.ceil(npts / nmax) + chsize = int(np.ceil(npts / nch)) + i0 = np.arange(0, npts, chsize) + i1 = np.zeros_like(i0) + i1[:-1] = i0[1:] - 1 + i1[-1] = npts + for ii0, ii1 in zip(i0, i1): + v = path.vertices[ii0:ii1, :] + c = path.codes + if c is not None: + c = c[ii0:ii1] + c[0] = Path.MOVETO # move to end of last chunk + p = Path(v, c) + p.simplify_threshold = path.simplify_threshold + try: + self._renderer.draw_path(gc, p, transform, rgbFace) + except OverflowError: + msg = ( + "Exceeded cell block limit in Agg.\n\n" + "Please reduce the value of " + f"rcParams['agg.path.chunksize'] (currently {nmax}) " + "or increase the path simplification threshold" + "(rcParams['path.simplify_threshold'] = " + f"{mpl.rcParams['path.simplify_threshold']:.2f} by " + "default and path.simplify_threshold = " + f"{path.simplify_threshold:.2f} on the input)." + ) + raise OverflowError(msg) from None + else: + try: + self._renderer.draw_path(gc, path, transform, rgbFace) + except OverflowError: + cant_chunk = '' + if rgbFace is not None: + cant_chunk += "- cannot split filled path\n" + if gc.get_hatch() is not None: + cant_chunk += "- cannot split hatched path\n" + if not path.should_simplify: + cant_chunk += "- path.should_simplify is False\n" + if len(cant_chunk): + msg = ( + "Exceeded cell block limit in Agg, however for the " + "following reasons:\n\n" + f"{cant_chunk}\n" + "we cannot automatically split up this path to draw." + "\n\nPlease manually simplify your path." + ) + + else: + inc_threshold = ( + "or increase the path simplification threshold" + "(rcParams['path.simplify_threshold'] = " + f"{mpl.rcParams['path.simplify_threshold']} " + "by default and path.simplify_threshold " + f"= {path.simplify_threshold} " + "on the input)." + ) + if nmax > 100: + msg = ( + "Exceeded cell block limit in Agg. Please reduce " + "the value of rcParams['agg.path.chunksize'] " + f"(currently {nmax}) {inc_threshold}" + ) + else: + msg = ( + "Exceeded cell block limit in Agg. Please set " + "the value of rcParams['agg.path.chunksize'], " + f"(currently {nmax}) to be greater than 100 " + + inc_threshold + ) + + raise OverflowError(msg) from None + + def draw_mathtext(self, gc, x, y, s, prop, angle): + """Draw mathtext using :mod:`matplotlib.mathtext`.""" + ox, oy, width, height, descent, font_image = \ + self.mathtext_parser.parse(s, self.dpi, prop, + antialiased=gc.get_antialiased()) + + xd = descent * sin(radians(angle)) + yd = descent * cos(radians(angle)) + x = round(x + ox + xd) + y = round(y - oy + yd) + self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + if ismath: + return self.draw_mathtext(gc, x, y, s, prop, angle) + font = self._prepare_font(prop) + # We pass '0' for angle here, since it will be rotated (in raster + # space) in the following call to draw_text_image). + font.set_text(s, 0, flags=get_hinting_flag()) + font.draw_glyphs_to_bitmap( + antialiased=gc.get_antialiased()) + d = font.get_descent() / 64.0 + # The descent needs to be adjusted for the angle. + xo, yo = font.get_bitmap_offset() + xo /= 64.0 + yo /= 64.0 + xd = d * sin(radians(angle)) + yd = d * cos(radians(angle)) + x = round(x + xo + xd) + y = round(y + yo + yd) + self._renderer.draw_text_image(font, x, y + 1, angle, gc) + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + + _api.check_in_list(["TeX", True, False], ismath=ismath) + if ismath == "TeX": + return super().get_text_width_height_descent(s, prop, ismath) + + if ismath: + ox, oy, width, height, descent, font_image = \ + self.mathtext_parser.parse(s, self.dpi, prop) + return width, height, descent + + font = self._prepare_font(prop) + font.set_text(s, 0.0, flags=get_hinting_flag()) + w, h = font.get_width_height() # width and height of unrotated string + d = font.get_descent() + w /= 64.0 # convert from subpixels + h /= 64.0 + d /= 64.0 + return w, h, d + + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + # todo, handle props, angle, origins + size = prop.get_size_in_points() + + texmanager = self.get_texmanager() + + Z = texmanager.get_grey(s, size, self.dpi) + Z = np.array(Z * 255.0, np.uint8) + + w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX") + xd = d * sin(radians(angle)) + yd = d * cos(radians(angle)) + x = round(x + xd) + y = round(y + yd) + self._renderer.draw_text_image(Z, x, y, angle, gc) + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def _prepare_font(self, font_prop): + """ + Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size. + """ + font = get_font(_fontManager._find_fonts_by_props(font_prop)) + font.clear() + size = font_prop.get_size_in_points() + font.set_size(size, self.dpi) + return font + + def points_to_pixels(self, points): + # docstring inherited + return points * self.dpi / 72 + + def buffer_rgba(self): + return memoryview(self._renderer) + + def tostring_argb(self): + return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes() + + def clear(self): + self._renderer.clear() + + def option_image_nocomposite(self): + # docstring inherited + + # It is generally faster to composite each image directly to + # the Figure, and there's no file size benefit to compositing + # with the Agg backend + return True + + def option_scale_image(self): + # docstring inherited + return False + + def restore_region(self, region, bbox=None, xy=None): + """ + Restore the saved region. If bbox (instance of BboxBase, or + its extents) is given, only the region specified by the bbox + will be restored. *xy* (a pair of floats) optionally + specifies the new position (the LLC of the original region, + not the LLC of the bbox) where the region will be restored. + + >>> region = renderer.copy_from_bbox() + >>> x1, y1, x2, y2 = region.get_extents() + >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), + ... xy=(x1-dx, y1)) + + """ + if bbox is not None or xy is not None: + if bbox is None: + x1, y1, x2, y2 = region.get_extents() + elif isinstance(bbox, BboxBase): + x1, y1, x2, y2 = bbox.extents + else: + x1, y1, x2, y2 = bbox + + if xy is None: + ox, oy = x1, y1 + else: + ox, oy = xy + + # The incoming data is float, but the _renderer type-checking wants + # to see integers. + self._renderer.restore_region(region, int(x1), int(y1), + int(x2), int(y2), int(ox), int(oy)) + + else: + self._renderer.restore_region(region) + + def start_filter(self): + """ + Start filtering. It simply creates a new canvas (the old one is saved). + """ + self._filter_renderers.append(self._renderer) + self._renderer = _RendererAgg(int(self.width), int(self.height), + self.dpi) + self._update_methods() + + def stop_filter(self, post_processing): + """ + Save the current canvas as an image and apply post processing. + + The *post_processing* function:: + + def post_processing(image, dpi): + # ny, nx, depth = image.shape + # image (numpy array) has RGBA channels and has a depth of 4. + ... + # create a new_image (numpy array of 4 channels, size can be + # different). The resulting image may have offsets from + # lower-left corner of the original image + return new_image, offset_x, offset_y + + The saved renderer is restored and the returned image from + post_processing is plotted (using draw_image) on it. + """ + orig_img = np.asarray(self.buffer_rgba()) + slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3]) + cropped_img = orig_img[slice_y, slice_x] + + self._renderer = self._filter_renderers.pop() + self._update_methods() + + if cropped_img.size: + img, ox, oy = post_processing(cropped_img / 255, self.dpi) + gc = self.new_gc() + if img.dtype.kind == 'f': + img = np.asarray(img * 255., np.uint8) + self._renderer.draw_image( + gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy, + img[::-1]) + + +class FigureCanvasAgg(FigureCanvasBase): + # docstring inherited + + _lastKey = None # Overwritten per-instance on the first draw. + + def copy_from_bbox(self, bbox): + renderer = self.get_renderer() + return renderer.copy_from_bbox(bbox) + + def restore_region(self, region, bbox=None, xy=None): + renderer = self.get_renderer() + return renderer.restore_region(region, bbox, xy) + + def draw(self): + # docstring inherited + self.renderer = self.get_renderer() + self.renderer.clear() + # Acquire a lock on the shared font cache. + with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar + else nullcontext()): + self.figure.draw(self.renderer) + # A GUI class may be need to update a window using this draw, so + # don't forget to call the superclass. + super().draw() + + def get_renderer(self): + w, h = self.figure.bbox.size + key = w, h, self.figure.dpi + reuse_renderer = (self._lastKey == key) + if not reuse_renderer: + self.renderer = RendererAgg(w, h, self.figure.dpi) + self._lastKey = key + return self.renderer + + def tostring_argb(self): + """ + Get the image as ARGB `bytes`. + + `draw` must be called at least once before this function will work and + to update the renderer for any subsequent changes to the Figure. + """ + return self.renderer.tostring_argb() + + def buffer_rgba(self): + """ + Get the image as a `memoryview` to the renderer's buffer. + + `draw` must be called at least once before this function will work and + to update the renderer for any subsequent changes to the Figure. + """ + return self.renderer.buffer_rgba() + + def print_raw(self, filename_or_obj, *, metadata=None): + if metadata is not None: + raise ValueError("metadata not supported for raw/rgba") + FigureCanvasAgg.draw(self) + renderer = self.get_renderer() + with cbook.open_file_cm(filename_or_obj, "wb") as fh: + fh.write(renderer.buffer_rgba()) + + print_rgba = print_raw + + def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None): + """ + Draw the canvas, then save it using `.image.imsave` (to which + *pil_kwargs* and *metadata* are forwarded). + """ + FigureCanvasAgg.draw(self) + mpl.image.imsave( + filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper", + dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs) + + def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None): + """ + Write the figure to a PNG file. + + Parameters + ---------- + filename_or_obj : str or path-like or file-like + The file to write to. + + metadata : dict, optional + Metadata in the PNG file as key-value pairs of bytes or latin-1 + encodable strings. + According to the PNG specification, keys must be shorter than 79 + chars. + + The `PNG specification`_ defines some common keywords that may be + used as appropriate: + + - Title: Short (one line) title or caption for image. + - Author: Name of image's creator. + - Description: Description of image (possibly long). + - Copyright: Copyright notice. + - Creation Time: Time of original image creation + (usually RFC 1123 format). + - Software: Software used to create the image. + - Disclaimer: Legal disclaimer. + - Warning: Warning of nature of content. + - Source: Device used to create the image. + - Comment: Miscellaneous comment; + conversion from other image format. + + Other keywords may be invented for other purposes. + + If 'Software' is not given, an autogenerated value for Matplotlib + will be used. This can be removed by setting it to *None*. + + For more details see the `PNG specification`_. + + .. _PNG specification: \ + https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords + + pil_kwargs : dict, optional + Keyword arguments passed to `PIL.Image.Image.save`. + + If the 'pnginfo' key is present, it completely overrides + *metadata*, including the default 'Software' key. + """ + self._print_pil(filename_or_obj, "png", pil_kwargs, metadata) + + def print_to_buffer(self): + FigureCanvasAgg.draw(self) + renderer = self.get_renderer() + return (bytes(renderer.buffer_rgba()), + (int(renderer.width), int(renderer.height))) + + # Note that these methods should typically be called via savefig() and + # print_figure(), and the latter ensures that `self.figure.dpi` already + # matches the dpi kwarg (if any). + + def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None): + # savefig() has already applied savefig.facecolor; we now set it to + # white to make imsave() blend semi-transparent figures against an + # assumed white background. + with mpl.rc_context({"savefig.facecolor": "white"}): + self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata) + + print_jpeg = print_jpg + + def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None): + self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata) + + print_tiff = print_tif + + def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None): + self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata) + + print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map( + """ + Write the figure to a {} file. + + Parameters + ---------- + filename_or_obj : str or path-like or file-like + The file to write to. + pil_kwargs : dict, optional + Additional keyword arguments that are passed to + `PIL.Image.Image.save` when saving the figure. + """.format, ["JPEG", "TIFF", "WebP"]) + + +@_Backend.export +class _BackendAgg(_Backend): + backend_version = 'v2.2' + FigureCanvas = FigureCanvasAgg + FigureManager = FigureManagerBase diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_cairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..7409cd35b394344314ec14de768f77b80e512e8c --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_cairo.py @@ -0,0 +1,529 @@ +""" +A Cairo backend for Matplotlib +============================== +:Author: Steve Chaplin and others + +This backend depends on cairocffi or pycairo. +""" + +import functools +import gzip +import math + +import numpy as np + +try: + import cairo + if cairo.version_info < (1, 14, 0): # Introduced set_device_scale. + raise ImportError(f"Cairo backend requires cairo>=1.14.0, " + f"but only {cairo.version_info} is available") +except ImportError: + try: + import cairocffi as cairo + except ImportError as err: + raise ImportError( + "cairo backend requires that pycairo>=1.14.0 or cairocffi " + "is installed") from err + +from .. import _api, cbook, font_manager +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, + RendererBase) +from matplotlib.font_manager import ttfFontProperty +from matplotlib.path import Path +from matplotlib.transforms import Affine2D + + +def _set_rgba(ctx, color, alpha, forced_alpha): + if len(color) == 3 or forced_alpha: + ctx.set_source_rgba(*color[:3], alpha) + else: + ctx.set_source_rgba(*color) + + +def _append_path(ctx, path, transform, clip=None): + for points, code in path.iter_segments( + transform, remove_nans=True, clip=clip): + if code == Path.MOVETO: + ctx.move_to(*points) + elif code == Path.CLOSEPOLY: + ctx.close_path() + elif code == Path.LINETO: + ctx.line_to(*points) + elif code == Path.CURVE3: + cur = np.asarray(ctx.get_current_point()) + a = points[:2] + b = points[-2:] + ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b) + elif code == Path.CURVE4: + ctx.curve_to(*points) + + +def _cairo_font_args_from_font_prop(prop): + """ + Convert a `.FontProperties` or a `.FontEntry` to arguments that can be + passed to `.Context.select_font_face`. + """ + def attr(field): + try: + return getattr(prop, f"get_{field}")() + except AttributeError: + return getattr(prop, field) + + name = attr("name") + slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}") + weight = attr("weight") + weight = (cairo.FONT_WEIGHT_NORMAL + if font_manager.weight_dict.get(weight, weight) < 550 + else cairo.FONT_WEIGHT_BOLD) + return name, slant, weight + + +class RendererCairo(RendererBase): + def __init__(self, dpi): + self.dpi = dpi + self.gc = GraphicsContextCairo(renderer=self) + self.width = None + self.height = None + self.text_ctx = cairo.Context( + cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) + super().__init__() + + def set_context(self, ctx): + surface = ctx.get_target() + if hasattr(surface, "get_width") and hasattr(surface, "get_height"): + size = surface.get_width(), surface.get_height() + elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface. + ext = surface.get_extents() + size = ext.width, ext.height + else: # vector surfaces. + ctx.save() + ctx.reset_clip() + rect, *rest = ctx.copy_clip_rectangle_list() + if rest: + raise TypeError("Cannot infer surface size") + _, _, *size = rect + ctx.restore() + self.gc.ctx = ctx + self.width, self.height = size + + @staticmethod + def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides): + if fill_c is not None: + ctx.save() + _set_rgba(ctx, fill_c, alpha, alpha_overrides) + ctx.fill_preserve() + ctx.restore() + ctx.stroke() + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + ctx = gc.ctx + # Clip the path to the actual rendering extents if it isn't filled. + clip = (ctx.clip_extents() + if rgbFace is None and gc.get_hatch() is None + else None) + transform = (transform + + Affine2D().scale(1, -1).translate(0, self.height)) + ctx.new_path() + _append_path(ctx, path, transform, clip) + if rgbFace is not None: + ctx.save() + _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + ctx.fill_preserve() + ctx.restore() + hatch_path = gc.get_hatch_path() + if hatch_path: + dpi = int(self.dpi) + hatch_surface = ctx.get_target().create_similar( + cairo.Content.COLOR_ALPHA, dpi, dpi) + hatch_ctx = cairo.Context(hatch_surface) + _append_path(hatch_ctx, hatch_path, + Affine2D().scale(dpi, -dpi).translate(0, dpi), + None) + hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth())) + hatch_ctx.set_source_rgba(*gc.get_hatch_color()) + hatch_ctx.fill_preserve() + hatch_ctx.stroke() + hatch_pattern = cairo.SurfacePattern(hatch_surface) + hatch_pattern.set_extend(cairo.Extend.REPEAT) + ctx.save() + ctx.set_source(hatch_pattern) + ctx.fill_preserve() + ctx.restore() + ctx.stroke() + + def draw_markers(self, gc, marker_path, marker_trans, path, transform, + rgbFace=None): + # docstring inherited + + ctx = gc.ctx + ctx.new_path() + # Create the path for the marker; it needs to be flipped here already! + _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1)) + marker_path = ctx.copy_path_flat() + + # Figure out whether the path has a fill + x1, y1, x2, y2 = ctx.fill_extents() + if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0: + filled = False + # No fill, just unset this (so we don't try to fill it later on) + rgbFace = None + else: + filled = True + + transform = (transform + + Affine2D().scale(1, -1).translate(0, self.height)) + + ctx.new_path() + for i, (vertices, codes) in enumerate( + path.iter_segments(transform, simplify=False)): + if len(vertices): + x, y = vertices[-2:] + ctx.save() + + # Translate and apply path + ctx.translate(x, y) + ctx.append_path(marker_path) + + ctx.restore() + + # Slower code path if there is a fill; we need to draw + # the fill and stroke for each marker at the same time. + # Also flush out the drawing every once in a while to + # prevent the paths from getting way too long. + if filled or i % 1000 == 0: + self._fill_and_stroke( + ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + + # Fast path, if there is no fill, draw everything in one step + if not filled: + self._fill_and_stroke( + ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) + + def draw_image(self, gc, x, y, im): + im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1]) + surface = cairo.ImageSurface.create_for_data( + im.ravel().data, cairo.FORMAT_ARGB32, + im.shape[1], im.shape[0], im.shape[1] * 4) + ctx = gc.ctx + y = self.height - y - im.shape[0] + + ctx.save() + ctx.set_source_surface(surface, float(x), float(y)) + ctx.paint() + ctx.restore() + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + # Note: (x, y) are device/display coords, not user-coords, unlike other + # draw_* methods + if ismath: + self._draw_mathtext(gc, x, y, s, prop, angle) + + else: + ctx = gc.ctx + ctx.new_path() + ctx.move_to(x, y) + + ctx.save() + ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) + ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) + opts = cairo.FontOptions() + opts.set_antialias(gc.get_antialiased()) + ctx.set_font_options(opts) + if angle: + ctx.rotate(np.deg2rad(-angle)) + ctx.show_text(s) + ctx.restore() + + def _draw_mathtext(self, gc, x, y, s, prop, angle): + ctx = gc.ctx + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, self.dpi, prop) + + ctx.save() + ctx.translate(x, y) + if angle: + ctx.rotate(np.deg2rad(-angle)) + + for font, fontsize, idx, ox, oy in glyphs: + ctx.new_path() + ctx.move_to(ox, -oy) + ctx.select_font_face( + *_cairo_font_args_from_font_prop(ttfFontProperty(font))) + ctx.set_font_size(self.points_to_pixels(fontsize)) + ctx.show_text(chr(idx)) + + for ox, oy, w, h in rects: + ctx.new_path() + ctx.rectangle(ox, -oy, w, -h) + ctx.set_source_rgb(0, 0, 0) + ctx.fill_preserve() + + ctx.restore() + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + + if ismath == 'TeX': + return super().get_text_width_height_descent(s, prop, ismath) + + if ismath: + width, height, descent, *_ = \ + self._text2path.mathtext_parser.parse(s, self.dpi, prop) + return width, height, descent + + ctx = self.text_ctx + # problem - scale remembers last setting and font can become + # enormous causing program to crash + # save/restore prevents the problem + ctx.save() + ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) + ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) + + y_bearing, w, h = ctx.text_extents(s)[1:4] + ctx.restore() + + return w, h, h + y_bearing + + def new_gc(self): + # docstring inherited + self.gc.ctx.save() + # FIXME: The following doesn't properly implement a stack-like behavior + # and relies instead on the (non-guaranteed) fact that artists never + # rely on nesting gc states, so directly resetting the attributes (IOW + # a single-level stack) is enough. + self.gc._alpha = 1 + self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA + self.gc._hatch = None + return self.gc + + def points_to_pixels(self, points): + # docstring inherited + return points / 72 * self.dpi + + +class GraphicsContextCairo(GraphicsContextBase): + _joind = { + 'bevel': cairo.LINE_JOIN_BEVEL, + 'miter': cairo.LINE_JOIN_MITER, + 'round': cairo.LINE_JOIN_ROUND, + } + + _capd = { + 'butt': cairo.LINE_CAP_BUTT, + 'projecting': cairo.LINE_CAP_SQUARE, + 'round': cairo.LINE_CAP_ROUND, + } + + def __init__(self, renderer): + super().__init__() + self.renderer = renderer + + def restore(self): + self.ctx.restore() + + def set_alpha(self, alpha): + super().set_alpha(alpha) + _set_rgba( + self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha()) + + def set_antialiased(self, b): + self.ctx.set_antialias( + cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE) + + def get_antialiased(self): + return self.ctx.get_antialias() + + def set_capstyle(self, cs): + self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs)) + self._capstyle = cs + + def set_clip_rectangle(self, rectangle): + if not rectangle: + return + x, y, w, h = np.round(rectangle.bounds) + ctx = self.ctx + ctx.new_path() + ctx.rectangle(x, self.renderer.height - h - y, w, h) + ctx.clip() + + def set_clip_path(self, path): + if not path: + return + tpath, affine = path.get_transformed_path_and_affine() + ctx = self.ctx + ctx.new_path() + affine = (affine + + Affine2D().scale(1, -1).translate(0, self.renderer.height)) + _append_path(ctx, tpath, affine) + ctx.clip() + + def set_dashes(self, offset, dashes): + self._dashes = offset, dashes + if dashes is None: + self.ctx.set_dash([], 0) # switch dashes off + else: + self.ctx.set_dash( + list(self.renderer.points_to_pixels(np.asarray(dashes))), + offset) + + def set_foreground(self, fg, isRGBA=None): + super().set_foreground(fg, isRGBA) + if len(self._rgb) == 3: + self.ctx.set_source_rgb(*self._rgb) + else: + self.ctx.set_source_rgba(*self._rgb) + + def get_rgb(self): + return self.ctx.get_source().get_rgba()[:3] + + def set_joinstyle(self, js): + self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js)) + self._joinstyle = js + + def set_linewidth(self, w): + self._linewidth = float(w) + self.ctx.set_line_width(self.renderer.points_to_pixels(w)) + + +class _CairoRegion: + def __init__(self, slices, data): + self._slices = slices + self._data = data + + +class FigureCanvasCairo(FigureCanvasBase): + @property + def _renderer(self): + # In theory, _renderer should be set in __init__, but GUI canvas + # subclasses (FigureCanvasFooCairo) don't always interact well with + # multiple inheritance (FigureCanvasFoo inits but doesn't super-init + # FigureCanvasCairo), so initialize it in the getter instead. + if not hasattr(self, "_cached_renderer"): + self._cached_renderer = RendererCairo(self.figure.dpi) + return self._cached_renderer + + def get_renderer(self): + return self._renderer + + def copy_from_bbox(self, bbox): + surface = self._renderer.gc.ctx.get_target() + if not isinstance(surface, cairo.ImageSurface): + raise RuntimeError( + "copy_from_bbox only works when rendering to an ImageSurface") + sw = surface.get_width() + sh = surface.get_height() + x0 = math.ceil(bbox.x0) + x1 = math.floor(bbox.x1) + y0 = math.ceil(sh - bbox.y1) + y1 = math.floor(sh - bbox.y0) + if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1 + and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1): + raise ValueError("Invalid bbox") + sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0)) + data = (np.frombuffer(surface.get_data(), np.uint32) + .reshape((sh, sw))[sls].copy()) + return _CairoRegion(sls, data) + + def restore_region(self, region): + surface = self._renderer.gc.ctx.get_target() + if not isinstance(surface, cairo.ImageSurface): + raise RuntimeError( + "restore_region only works when rendering to an ImageSurface") + surface.flush() + sw = surface.get_width() + sh = surface.get_height() + sly, slx = region._slices + (np.frombuffer(surface.get_data(), np.uint32) + .reshape((sh, sw))[sly, slx]) = region._data + surface.mark_dirty_rectangle( + slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start) + + def print_png(self, fobj): + self._get_printed_image_surface().write_to_png(fobj) + + def print_rgba(self, fobj): + width, height = self.get_width_height() + buf = self._get_printed_image_surface().get_data() + fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888( + np.asarray(buf).reshape((width, height, 4)))) + + print_raw = print_rgba + + def _get_printed_image_surface(self): + self._renderer.dpi = self.figure.dpi + width, height = self.get_width_height() + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) + self._renderer.set_context(cairo.Context(surface)) + self.figure.draw(self._renderer) + return surface + + def _save(self, fmt, fobj, *, orientation='portrait'): + # save PDF/PS/SVG + + dpi = 72 + self.figure.dpi = dpi + w_in, h_in = self.figure.get_size_inches() + width_in_points, height_in_points = w_in * dpi, h_in * dpi + + if orientation == 'landscape': + width_in_points, height_in_points = ( + height_in_points, width_in_points) + + if fmt == 'ps': + if not hasattr(cairo, 'PSSurface'): + raise RuntimeError('cairo has not been compiled with PS ' + 'support enabled') + surface = cairo.PSSurface(fobj, width_in_points, height_in_points) + elif fmt == 'pdf': + if not hasattr(cairo, 'PDFSurface'): + raise RuntimeError('cairo has not been compiled with PDF ' + 'support enabled') + surface = cairo.PDFSurface(fobj, width_in_points, height_in_points) + elif fmt in ('svg', 'svgz'): + if not hasattr(cairo, 'SVGSurface'): + raise RuntimeError('cairo has not been compiled with SVG ' + 'support enabled') + if fmt == 'svgz': + if isinstance(fobj, str): + fobj = gzip.GzipFile(fobj, 'wb') + else: + fobj = gzip.GzipFile(None, 'wb', fileobj=fobj) + surface = cairo.SVGSurface(fobj, width_in_points, height_in_points) + else: + raise ValueError(f"Unknown format: {fmt!r}") + + self._renderer.dpi = self.figure.dpi + self._renderer.set_context(cairo.Context(surface)) + ctx = self._renderer.gc.ctx + + if orientation == 'landscape': + ctx.rotate(np.pi / 2) + ctx.translate(0, -height_in_points) + # Perhaps add an '%%Orientation: Landscape' comment? + + self.figure.draw(self._renderer) + + ctx.show_page() + surface.finish() + if fmt == 'svgz': + fobj.close() + + print_pdf = functools.partialmethod(_save, "pdf") + print_ps = functools.partialmethod(_save, "ps") + print_svg = functools.partialmethod(_save, "svg") + print_svgz = functools.partialmethod(_save, "svgz") + + +@_Backend.export +class _BackendCairo(_Backend): + backend_version = cairo.version + FigureCanvas = FigureCanvasCairo + FigureManager = FigureManagerBase diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3.py new file mode 100644 index 0000000000000000000000000000000000000000..888f5a770f5d196d36a5a2446ef78a670aa230db --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3.py @@ -0,0 +1,596 @@ +import functools +import logging +import os +from pathlib import Path + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib.backend_bases import ( + ToolContainerBase, MouseButton, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent) + +try: + import gi +except ImportError as err: + raise ImportError("The GTK3 backends require PyGObject") from err + +try: + # :raises ValueError: If module/version is already loaded, already + # required, or unavailable. + gi.require_version("Gtk", "3.0") +except ValueError as e: + # in this case we want to re-raise as ImportError so the + # auto-backend selection logic correctly skips. + raise ImportError(e) from e + +from gi.repository import Gio, GLib, GObject, Gtk, Gdk +from . import _backend_gtk +from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611 + _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, + TimerGTK as TimerGTK3, +) + + +_log = logging.getLogger(__name__) + + +@functools.cache +def _mpl_to_gtk_cursor(mpl_cursor): + return Gdk.Cursor.new_from_name( + Gdk.Display.get_default(), + _backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor)) + + +class FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea): + required_interactive_framework = "gtk3" + manager_class = _api.classproperty(lambda cls: FigureManagerGTK3) + # Setting this as a static constant prevents + # this resulting expression from leaking + event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK + | Gdk.EventMask.BUTTON_RELEASE_MASK + | Gdk.EventMask.EXPOSURE_MASK + | Gdk.EventMask.KEY_PRESS_MASK + | Gdk.EventMask.KEY_RELEASE_MASK + | Gdk.EventMask.ENTER_NOTIFY_MASK + | Gdk.EventMask.LEAVE_NOTIFY_MASK + | Gdk.EventMask.POINTER_MOTION_MASK + | Gdk.EventMask.SCROLL_MASK) + + def __init__(self, figure=None): + super().__init__(figure=figure) + + self._idle_draw_id = 0 + self._rubberband_rect = None + + self.connect('scroll_event', self.scroll_event) + self.connect('button_press_event', self.button_press_event) + self.connect('button_release_event', self.button_release_event) + self.connect('configure_event', self.configure_event) + self.connect('screen-changed', self._update_device_pixel_ratio) + self.connect('notify::scale-factor', self._update_device_pixel_ratio) + self.connect('draw', self.on_draw_event) + self.connect('draw', self._post_draw) + self.connect('key_press_event', self.key_press_event) + self.connect('key_release_event', self.key_release_event) + self.connect('motion_notify_event', self.motion_notify_event) + self.connect('enter_notify_event', self.enter_notify_event) + self.connect('leave_notify_event', self.leave_notify_event) + self.connect('size_allocate', self.size_allocate) + + self.set_events(self.__class__.event_mask) + + self.set_can_focus(True) + + css = Gtk.CssProvider() + css.load_from_data(b".matplotlib-canvas { background-color: white; }") + style_ctx = self.get_style_context() + style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) + style_ctx.add_class("matplotlib-canvas") + + def destroy(self): + CloseEvent("close_event", self)._process() + + def set_cursor(self, cursor): + # docstring inherited + window = self.get_property("window") + if window is not None: + window.set_cursor(_mpl_to_gtk_cursor(cursor)) + context = GLib.MainContext.default() + context.iteration(True) + + def _mpl_coords(self, event=None): + """ + Convert the position of a GTK event, or of the current cursor position + if *event* is None, to Matplotlib coordinates. + + GTK use logical pixels, but the figure is scaled to physical pixels for + rendering. Transform to physical pixels so that all of the down-stream + transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if event is None: + window = self.get_window() + t, x, y, state = window.get_device_position( + window.get_display().get_device_manager().get_client_pointer()) + else: + x, y = event.x, event.y + x = x * self.device_pixel_ratio + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height - y * self.device_pixel_ratio + return x, y + + def scroll_event(self, widget, event): + step = 1 if event.direction == Gdk.ScrollDirection.UP else -1 + MouseEvent("scroll_event", self, + *self._mpl_coords(event), step=step, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def button_press_event(self, widget, event): + MouseEvent("button_press_event", self, + *self._mpl_coords(event), event.button, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def button_release_event(self, widget, event): + MouseEvent("button_release_event", self, + *self._mpl_coords(event), event.button, + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def key_press_event(self, widget, event): + KeyEvent("key_press_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + return True # stop event propagation + + def key_release_event(self, widget, event): + KeyEvent("key_release_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + return True # stop event propagation + + def motion_notify_event(self, widget, event): + MouseEvent("motion_notify_event", self, *self._mpl_coords(event), + buttons=self._mpl_buttons(event.state), + modifiers=self._mpl_modifiers(event.state), + guiEvent=event)._process() + return False # finish event propagation? + + def enter_notify_event(self, widget, event): + gtk_mods = Gdk.Keymap.get_for_display( + self.get_display()).get_modifier_state() + LocationEvent("figure_enter_event", self, *self._mpl_coords(event), + modifiers=self._mpl_modifiers(gtk_mods), + guiEvent=event)._process() + + def leave_notify_event(self, widget, event): + gtk_mods = Gdk.Keymap.get_for_display( + self.get_display()).get_modifier_state() + LocationEvent("figure_leave_event", self, *self._mpl_coords(event), + modifiers=self._mpl_modifiers(gtk_mods), + guiEvent=event)._process() + + def size_allocate(self, widget, allocation): + dpival = self.figure.dpi + winch = allocation.width * self.device_pixel_ratio / dpival + hinch = allocation.height * self.device_pixel_ratio / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + @staticmethod + def _mpl_buttons(event_state): + modifiers = [ + (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK), + (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK), + (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK), + (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK), + (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK), + ] + # State *before* press/release. + return [name for name, mask in modifiers if event_state & mask] + + @staticmethod + def _mpl_modifiers(event_state, *, exclude=None): + modifiers = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"), + ("alt", Gdk.ModifierType.MOD1_MASK, "alt"), + ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"), + ("super", Gdk.ModifierType.MOD4_MASK, "super"), + ] + return [name for name, mask, key in modifiers + if exclude != key and event_state & mask] + + def _get_key(self, event): + unikey = chr(Gdk.keyval_to_unicode(event.keyval)) + key = cbook._unikey_or_keysym_to_mplkey( + unikey, Gdk.keyval_name(event.keyval)) + mods = self._mpl_modifiers(event.state, exclude=key) + if "shift" in mods and unikey.isprintable(): + mods.remove("shift") + return "+".join([*mods, key]) + + def _update_device_pixel_ratio(self, *args, **kwargs): + # We need to be careful in cases with mixed resolution displays if + # device_pixel_ratio changes. + if self._set_device_pixel_ratio(self.get_scale_factor()): + # The easiest way to resize the canvas is to emit a resize event + # since we implement all the logic for resizing the canvas for that + # event. + self.queue_resize() + self.queue_draw() + + def configure_event(self, widget, event): + if widget.get_property("window") is None: + return + w = event.width * self.device_pixel_ratio + h = event.height * self.device_pixel_ratio + if w < 3 or h < 3: + return # empty fig + # resize the figure (in inches) + dpi = self.figure.dpi + self.figure.set_size_inches(w / dpi, h / dpi, forward=False) + return False # finish event propagation? + + def _draw_rubberband(self, rect): + self._rubberband_rect = rect + # TODO: Only update the rubberband area. + self.queue_draw() + + def _post_draw(self, widget, ctx): + if self._rubberband_rect is None: + return + + x0, y0, w, h = (dim / self.device_pixel_ratio + for dim in self._rubberband_rect) + x1 = x0 + w + y1 = y0 + h + + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + ctx.move_to(x0, y0) + ctx.line_to(x0, y1) + ctx.move_to(x0, y0) + ctx.line_to(x1, y0) + ctx.move_to(x0, y1) + ctx.line_to(x1, y1) + ctx.move_to(x1, y0) + ctx.line_to(x1, y1) + + ctx.set_antialias(1) + ctx.set_line_width(1) + ctx.set_dash((3, 3), 0) + ctx.set_source_rgb(0, 0, 0) + ctx.stroke_preserve() + + ctx.set_dash((3, 3), 3) + ctx.set_source_rgb(1, 1, 1) + ctx.stroke() + + def on_draw_event(self, widget, ctx): + # to be overwritten by GTK3Agg or GTK3Cairo + pass + + def draw(self): + # docstring inherited + if self.is_drawable(): + self.queue_draw() + + def draw_idle(self): + # docstring inherited + if self._idle_draw_id != 0: + return + def idle_draw(*args): + try: + self.draw() + finally: + self._idle_draw_id = 0 + return False + self._idle_draw_id = GLib.idle_add(idle_draw) + + def flush_events(self): + # docstring inherited + context = GLib.MainContext.default() + while context.pending(): + context.iteration(True) + + +class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar): + def __init__(self, canvas): + GObject.GObject.__init__(self) + + self.set_style(Gtk.ToolbarStyle.ICONS) + + self._gtk_ids = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.insert(Gtk.SeparatorToolItem(), -1) + continue + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string( + str(cbook._get_data_path('images', + f'{image_file}-symbolic.svg'))), + Gtk.IconSize.LARGE_TOOLBAR) + self._gtk_ids[text] = button = ( + Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else + Gtk.ToolButton()) + button.set_label(text) + button.set_icon_widget(image) + # Save the handler id, so that we can block it as needed. + button._signal_handler = button.connect( + 'clicked', getattr(self, callback)) + button.set_tooltip_text(tooltip_text) + self.insert(button, -1) + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + toolitem = Gtk.ToolItem() + self.insert(toolitem, -1) + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + toolitem.set_expand(True) # Push real message to the right. + toolitem.add(label) + + toolitem = Gtk.ToolItem() + self.insert(toolitem, -1) + self.message = Gtk.Label() + self.message.set_justify(Gtk.Justification.RIGHT) + toolitem.add(self.message) + + self.show_all() + + _NavigationToolbar2GTK.__init__(self, canvas) + + def save_figure(self, *args): + dialog = Gtk.FileChooserDialog( + title="Save the figure", + transient_for=self.canvas.get_toplevel(), + action=Gtk.FileChooserAction.SAVE, + buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK), + ) + for name, fmts \ + in self.canvas.get_supported_filetypes_grouped().items(): + ff = Gtk.FileFilter() + ff.set_name(name) + for fmt in fmts: + ff.add_pattern(f'*.{fmt}') + dialog.add_filter(ff) + if self.canvas.get_default_filetype() in fmts: + dialog.set_filter(ff) + + @functools.partial(dialog.connect, "notify::filter") + def on_notify_filter(*args): + name = dialog.get_filter().get_name() + fmt = self.canvas.get_supported_filetypes_grouped()[name][0] + dialog.set_current_name( + str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}'))) + + dialog.set_current_folder(mpl.rcParams["savefig.directory"]) + dialog.set_current_name(self.canvas.get_default_filename()) + dialog.set_do_overwrite_confirmation(True) + + response = dialog.run() + fname = dialog.get_filename() + ff = dialog.get_filter() # Doesn't autoadjust to filename :/ + fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0] + dialog.destroy() + if response != Gtk.ResponseType.OK: + return None + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams['savefig.directory']: + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) + try: + self.canvas.figure.savefig(fname, format=fmt) + return fname + except Exception as e: + dialog = Gtk.MessageDialog( + transient_for=self.canvas.get_toplevel(), text=str(e), + message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK) + dialog.run() + dialog.destroy() + + +class ToolbarGTK3(ToolContainerBase, Gtk.Box): + _icon_extension = '-symbolic.svg' + + def __init__(self, toolmanager): + ToolContainerBase.__init__(self, toolmanager) + Gtk.Box.__init__(self) + self.set_property('orientation', Gtk.Orientation.HORIZONTAL) + self._message = Gtk.Label() + self._message.set_justify(Gtk.Justification.RIGHT) + self.pack_end(self._message, False, False, 0) + self.show_all() + self._groups = {} + self._toolitems = {} + + def add_toolitem(self, name, group, position, image_file, description, + toggle): + if toggle: + button = Gtk.ToggleToolButton() + else: + button = Gtk.ToolButton() + button.set_label(name) + + if image_file is not None: + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string(image_file), + Gtk.IconSize.LARGE_TOOLBAR) + button.set_icon_widget(image) + + if position is None: + position = -1 + + self._add_button(button, group, position) + signal = button.connect('clicked', self._call_tool, name) + button.set_tooltip_text(description) + button.show_all() + self._toolitems.setdefault(name, []) + self._toolitems[name].append((button, signal)) + + def _add_button(self, button, group, position): + if group not in self._groups: + if self._groups: + self._add_separator() + toolbar = Gtk.Toolbar() + toolbar.set_style(Gtk.ToolbarStyle.ICONS) + self.pack_start(toolbar, False, False, 0) + toolbar.show_all() + self._groups[group] = toolbar + self._groups[group].insert(button, position) + + def _call_tool(self, btn, name): + self.trigger_tool(name) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for toolitem, signal in self._toolitems[name]: + toolitem.handler_block(signal) + toolitem.set_active(toggled) + toolitem.handler_unblock(signal) + + def remove_toolitem(self, name): + for toolitem, _signal in self._toolitems.pop(name, []): + for group in self._groups: + if toolitem in self._groups[group]: + self._groups[group].remove(toolitem) + + def _add_separator(self): + sep = Gtk.Separator() + sep.set_property("orientation", Gtk.Orientation.VERTICAL) + self.pack_start(sep, False, True, 0) + sep.show_all() + + def set_message(self, s): + self._message.set_label(s) + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class SaveFigureGTK3(backend_tools.SaveFigureBase): + def trigger(self, *args, **kwargs): + NavigationToolbar2GTK3.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class HelpGTK3(backend_tools.ToolHelpBase): + def _normalize_shortcut(self, key): + """ + Convert Matplotlib key presses to GTK+ accelerator identifiers. + + Related to `FigureCanvasGTK3._get_key`. + """ + special = { + 'backspace': 'BackSpace', + 'pagedown': 'Page_Down', + 'pageup': 'Page_Up', + 'scroll_lock': 'Scroll_Lock', + } + + parts = key.split('+') + mods = ['<' + mod + '>' for mod in parts[:-1]] + key = parts[-1] + + if key in special: + key = special[key] + elif len(key) > 1: + key = key.capitalize() + elif key.isupper(): + mods += [''] + + return ''.join(mods) + key + + def _is_valid_shortcut(self, key): + """ + Check for a valid shortcut to be displayed. + + - GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`). + - The shortcut window only shows keyboard shortcuts, not mouse buttons. + """ + return 'cmd+' not in key and not key.startswith('MouseButton.') + + def _show_shortcuts_window(self): + section = Gtk.ShortcutsSection() + + for name, tool in sorted(self.toolmanager.tools.items()): + if not tool.description: + continue + + # Putting everything in a separate group allows GTK to + # automatically split them into separate columns/pages, which is + # useful because we have lots of shortcuts, some with many keys + # that are very wide. + group = Gtk.ShortcutsGroup() + section.add(group) + # A hack to remove the title since we have no group naming. + group.forall(lambda widget, data: widget.set_visible(False), None) + + shortcut = Gtk.ShortcutsShortcut( + accelerator=' '.join( + self._normalize_shortcut(key) + for key in self.toolmanager.get_tool_keymap(name) + if self._is_valid_shortcut(key)), + title=tool.name, + subtitle=tool.description) + group.add(shortcut) + + window = Gtk.ShortcutsWindow( + title='Help', + modal=True, + transient_for=self._figure.canvas.get_toplevel()) + section.show() # Must be done explicitly before add! + window.add(section) + + window.show_all() + + def _show_shortcuts_dialog(self): + dialog = Gtk.MessageDialog( + self._figure.canvas.get_toplevel(), + 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(), + title="Help") + dialog.run() + dialog.destroy() + + def trigger(self, *args): + if Gtk.check_version(3, 20, 0) is None: + self._show_shortcuts_window() + else: + self._show_shortcuts_dialog() + + +@backend_tools._register_tool_class(FigureCanvasGTK3) +class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) + window = self.canvas.get_window() + x, y, width, height = window.get_geometry() + pb = Gdk.pixbuf_get_from_window(window, x, y, width, height) + clipboard.set_image(pb) + + +Toolbar = ToolbarGTK3 +backend_tools._register_tool_class( + FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK) +backend_tools._register_tool_class( + FigureCanvasGTK3, _backend_gtk.RubberbandGTK) + + +class FigureManagerGTK3(_FigureManagerGTK): + _toolbar2_class = NavigationToolbar2GTK3 + _toolmanager_toolbar_class = ToolbarGTK3 + + +@_BackendGTK.export +class _BackendGTK3(_BackendGTK): + FigureCanvas = FigureCanvasGTK3 + FigureManager = FigureManagerGTK3 diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3agg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3agg.py new file mode 100644 index 0000000000000000000000000000000000000000..bb469b85783dc10c11395fa2761a1d1625f3d885 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3agg.py @@ -0,0 +1,74 @@ +import numpy as np + +from .. import cbook, transforms +from . import backend_agg, backend_gtk3 +from .backend_gtk3 import GLib, Gtk, _BackendGTK3 + +import cairo # Presence of cairo is already checked by _backend_gtk. + + +class FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg, + backend_gtk3.FigureCanvasGTK3): + def __init__(self, figure): + super().__init__(figure=figure) + self._bbox_queue = [] + + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + scale = self.device_pixel_ratio + allocation = self.get_allocation() + w = allocation.width * scale + h = allocation.height * scale + + if not len(self._bbox_queue): + Gtk.render_background( + self.get_style_context(), ctx, + allocation.x, allocation.y, + allocation.width, allocation.height) + bbox_queue = [transforms.Bbox([[0, 0], [w, h]])] + else: + bbox_queue = self._bbox_queue + + for bbox in bbox_queue: + x = int(bbox.x0) + y = h - int(bbox.y1) + width = int(bbox.x1) - int(bbox.x0) + height = int(bbox.y1) - int(bbox.y0) + + buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32( + np.asarray(self.copy_from_bbox(bbox))) + image = cairo.ImageSurface.create_for_data( + buf.ravel().data, cairo.FORMAT_ARGB32, width, height) + image.set_device_scale(scale, scale) + ctx.set_source_surface(image, x / scale, y / scale) + ctx.paint() + + if len(self._bbox_queue): + self._bbox_queue = [] + + return False + + def blit(self, bbox=None): + # If bbox is None, blit the entire canvas to gtk. Otherwise + # blit only the area defined by the bbox. + if bbox is None: + bbox = self.figure.bbox + + scale = self.device_pixel_ratio + allocation = self.get_allocation() + x = int(bbox.x0 / scale) + y = allocation.height - int(bbox.y1 / scale) + width = (int(bbox.x1) - int(bbox.x0)) // scale + height = (int(bbox.y1) - int(bbox.y0)) // scale + + self._bbox_queue.append(bbox) + self.queue_draw_area(x, y, width, height) + + +@_BackendGTK3.export +class _BackendGTK3Agg(_BackendGTK3): + FigureCanvas = FigureCanvasGTK3Agg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3cairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..371b8dc1b31fb96dd823eeed65592d1692d5b8f2 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk3cairo.py @@ -0,0 +1,35 @@ +from contextlib import nullcontext + +from .backend_cairo import FigureCanvasCairo +from .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3 + + +class FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3): + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar + else nullcontext()): + allocation = self.get_allocation() + # Render the background before scaling, as the allocated size here is in + # logical pixels. + Gtk.render_background( + self.get_style_context(), ctx, + 0, 0, allocation.width, allocation.height) + scale = self.device_pixel_ratio + # Scale physical drawing to logical size. + ctx.scale(1 / scale, 1 / scale) + self._renderer.set_context(ctx) + # Set renderer to physical size so it renders in full resolution. + self._renderer.width = allocation.width * scale + self._renderer.height = allocation.height * scale + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + + +@_BackendGTK3.export +class _BackendGTK3Cairo(_BackendGTK3): + FigureCanvas = FigureCanvasGTK3Cairo diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4.py new file mode 100644 index 0000000000000000000000000000000000000000..620c9e5b94b664a54ae5e36e78f7398c4a19017c --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4.py @@ -0,0 +1,627 @@ +import functools +import io +import os + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib.backend_bases import ( + ToolContainerBase, MouseButton, + KeyEvent, LocationEvent, MouseEvent, ResizeEvent, CloseEvent) + +try: + import gi +except ImportError as err: + raise ImportError("The GTK4 backends require PyGObject") from err + +try: + # :raises ValueError: If module/version is already loaded, already + # required, or unavailable. + gi.require_version("Gtk", "4.0") +except ValueError as e: + # in this case we want to re-raise as ImportError so the + # auto-backend selection logic correctly skips. + raise ImportError(e) from e + +from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf +from . import _backend_gtk +from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611 + _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, + TimerGTK as TimerGTK4, +) + +_GOBJECT_GE_3_47 = gi.version_info >= (3, 47, 0) + + +class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea): + required_interactive_framework = "gtk4" + supports_blit = False + manager_class = _api.classproperty(lambda cls: FigureManagerGTK4) + + def __init__(self, figure=None): + super().__init__(figure=figure) + + self.set_hexpand(True) + self.set_vexpand(True) + + self._idle_draw_id = 0 + self._rubberband_rect = None + + self.set_draw_func(self._draw_func) + self.connect('resize', self.resize_event) + self.connect('notify::scale-factor', self._update_device_pixel_ratio) + + click = Gtk.GestureClick() + click.set_button(0) # All buttons. + click.connect('pressed', self.button_press_event) + click.connect('released', self.button_release_event) + self.add_controller(click) + + key = Gtk.EventControllerKey() + key.connect('key-pressed', self.key_press_event) + key.connect('key-released', self.key_release_event) + self.add_controller(key) + + motion = Gtk.EventControllerMotion() + motion.connect('motion', self.motion_notify_event) + motion.connect('enter', self.enter_notify_event) + motion.connect('leave', self.leave_notify_event) + self.add_controller(motion) + + scroll = Gtk.EventControllerScroll.new( + Gtk.EventControllerScrollFlags.VERTICAL) + scroll.connect('scroll', self.scroll_event) + self.add_controller(scroll) + + self.set_focusable(True) + + css = Gtk.CssProvider() + style = '.matplotlib-canvas { background-color: white; }' + if Gtk.check_version(4, 9, 3) is None: + css.load_from_data(style, -1) + else: + css.load_from_data(style.encode('utf-8')) + style_ctx = self.get_style_context() + style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) + style_ctx.add_class("matplotlib-canvas") + + def destroy(self): + CloseEvent("close_event", self)._process() + + def set_cursor(self, cursor): + # docstring inherited + self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor)) + + def _mpl_coords(self, xy=None): + """ + Convert the *xy* position of a GTK event, or of the current cursor + position if *xy* is None, to Matplotlib coordinates. + + GTK use logical pixels, but the figure is scaled to physical pixels for + rendering. Transform to physical pixels so that all of the down-stream + transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if xy is None: + surface = self.get_native().get_surface() + is_over, x, y, mask = surface.get_device_position( + self.get_display().get_default_seat().get_pointer()) + else: + x, y = xy + x = x * self.device_pixel_ratio + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height - y * self.device_pixel_ratio + return x, y + + def scroll_event(self, controller, dx, dy): + MouseEvent( + "scroll_event", self, *self._mpl_coords(), step=dy, + modifiers=self._mpl_modifiers(controller), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + return True + + def button_press_event(self, controller, n_press, x, y): + MouseEvent( + "button_press_event", self, *self._mpl_coords((x, y)), + controller.get_current_button(), + modifiers=self._mpl_modifiers(controller), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + self.grab_focus() + + def button_release_event(self, controller, n_press, x, y): + MouseEvent( + "button_release_event", self, *self._mpl_coords((x, y)), + controller.get_current_button(), + modifiers=self._mpl_modifiers(controller), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + + def key_press_event(self, controller, keyval, keycode, state): + KeyEvent( + "key_press_event", self, self._get_key(keyval, keycode, state), + *self._mpl_coords(), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + return True + + def key_release_event(self, controller, keyval, keycode, state): + KeyEvent( + "key_release_event", self, self._get_key(keyval, keycode, state), + *self._mpl_coords(), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + return True + + def motion_notify_event(self, controller, x, y): + MouseEvent( + "motion_notify_event", self, *self._mpl_coords((x, y)), + buttons=self._mpl_buttons(controller), + modifiers=self._mpl_modifiers(controller), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + + def enter_notify_event(self, controller, x, y): + LocationEvent( + "figure_enter_event", self, *self._mpl_coords((x, y)), + modifiers=self._mpl_modifiers(), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + + def leave_notify_event(self, controller): + LocationEvent( + "figure_leave_event", self, *self._mpl_coords(), + modifiers=self._mpl_modifiers(), + guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None, + )._process() + + def resize_event(self, area, width, height): + self._update_device_pixel_ratio() + dpi = self.figure.dpi + winch = width * self.device_pixel_ratio / dpi + hinch = height * self.device_pixel_ratio / dpi + self.figure.set_size_inches(winch, hinch, forward=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + def _mpl_buttons(self, controller): + # NOTE: This spews "Broken accounting of active state" warnings on + # right click on macOS. + surface = self.get_native().get_surface() + is_over, x, y, event_state = surface.get_device_position( + self.get_display().get_default_seat().get_pointer()) + # NOTE: alternatively we could use + # event_state = controller.get_current_event_state() + # but for button_press/button_release this would report the state + # *prior* to the event rather than after it; the above reports the + # state *after* it. + mod_table = [ + (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK), + (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK), + (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK), + (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK), + (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK), + ] + return {name for name, mask in mod_table if event_state & mask} + + def _mpl_modifiers(self, controller=None): + if controller is None: + surface = self.get_native().get_surface() + is_over, x, y, event_state = surface.get_device_position( + self.get_display().get_default_seat().get_pointer()) + else: + event_state = controller.get_current_event_state() + mod_table = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK), + ("alt", Gdk.ModifierType.ALT_MASK), + ("shift", Gdk.ModifierType.SHIFT_MASK), + ("super", Gdk.ModifierType.SUPER_MASK), + ] + return [name for name, mask in mod_table if event_state & mask] + + def _get_key(self, keyval, keycode, state): + unikey = chr(Gdk.keyval_to_unicode(keyval)) + key = cbook._unikey_or_keysym_to_mplkey( + unikey, + Gdk.keyval_name(keyval)) + modifiers = [ + ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"), + ("alt", Gdk.ModifierType.ALT_MASK, "alt"), + ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"), + ("super", Gdk.ModifierType.SUPER_MASK, "super"), + ] + mods = [ + mod for mod, mask, mod_key in modifiers + if (mod_key != key and state & mask + and not (mod == "shift" and unikey.isprintable()))] + return "+".join([*mods, key]) + + def _update_device_pixel_ratio(self, *args, **kwargs): + # We need to be careful in cases with mixed resolution displays if + # device_pixel_ratio changes. + if self._set_device_pixel_ratio(self.get_scale_factor()): + self.draw() + + def _draw_rubberband(self, rect): + self._rubberband_rect = rect + # TODO: Only update the rubberband area. + self.queue_draw() + + def _draw_func(self, drawing_area, ctx, width, height): + self.on_draw_event(self, ctx) + self._post_draw(self, ctx) + + def _post_draw(self, widget, ctx): + if self._rubberband_rect is None: + return + + lw = 1 + dash = 3 + x0, y0, w, h = (dim / self.device_pixel_ratio + for dim in self._rubberband_rect) + x1 = x0 + w + y1 = y0 + h + + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + ctx.move_to(x0, y0) + ctx.line_to(x0, y1) + ctx.move_to(x0, y0) + ctx.line_to(x1, y0) + ctx.move_to(x0, y1) + ctx.line_to(x1, y1) + ctx.move_to(x1, y0) + ctx.line_to(x1, y1) + + ctx.set_antialias(1) + ctx.set_line_width(lw) + ctx.set_dash((dash, dash), 0) + ctx.set_source_rgb(0, 0, 0) + ctx.stroke_preserve() + + ctx.set_dash((dash, dash), dash) + ctx.set_source_rgb(1, 1, 1) + ctx.stroke() + + def on_draw_event(self, widget, ctx): + # to be overwritten by GTK4Agg or GTK4Cairo + pass + + def draw(self): + # docstring inherited + if self.is_drawable(): + self.queue_draw() + + def draw_idle(self): + # docstring inherited + if self._idle_draw_id != 0: + return + def idle_draw(*args): + try: + self.draw() + finally: + self._idle_draw_id = 0 + return False + self._idle_draw_id = GLib.idle_add(idle_draw) + + def flush_events(self): + # docstring inherited + context = GLib.MainContext.default() + while context.pending(): + context.iteration(True) + + +class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box): + def __init__(self, canvas): + Gtk.Box.__init__(self) + + self.add_css_class('toolbar') + + self._gtk_ids = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.append(Gtk.Separator()) + continue + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string( + str(cbook._get_data_path('images', + f'{image_file}-symbolic.svg')))) + self._gtk_ids[text] = button = ( + Gtk.ToggleButton() if callback in ['zoom', 'pan'] else + Gtk.Button()) + button.set_child(image) + button.add_css_class('flat') + button.add_css_class('image-button') + # Save the handler id, so that we can block it as needed. + button._signal_handler = button.connect( + 'clicked', getattr(self, callback)) + button.set_tooltip_text(tooltip_text) + self.append(button) + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.set_hexpand(True) # Push real message to the right. + self.append(label) + + self.message = Gtk.Label() + self.message.set_justify(Gtk.Justification.RIGHT) + self.append(self.message) + + _NavigationToolbar2GTK.__init__(self, canvas) + + def save_figure(self, *args): + dialog = Gtk.FileChooserNative( + title='Save the figure', + transient_for=self.canvas.get_root(), + action=Gtk.FileChooserAction.SAVE, + modal=True) + self._save_dialog = dialog # Must keep a reference. + + ff = Gtk.FileFilter() + ff.set_name('All files') + ff.add_pattern('*') + dialog.add_filter(ff) + dialog.set_filter(ff) + + formats = [] + default_format = None + for i, (name, fmts) in enumerate( + self.canvas.get_supported_filetypes_grouped().items()): + ff = Gtk.FileFilter() + ff.set_name(name) + for fmt in fmts: + ff.add_pattern(f'*.{fmt}') + dialog.add_filter(ff) + formats.append(name) + if self.canvas.get_default_filetype() in fmts: + default_format = i + # Setting the choice doesn't always work, so make sure the default + # format is first. + formats = [formats[default_format], *formats[:default_format], + *formats[default_format+1:]] + dialog.add_choice('format', 'File format', formats, formats) + dialog.set_choice('format', formats[0]) + + dialog.set_current_folder(Gio.File.new_for_path( + os.path.expanduser(mpl.rcParams['savefig.directory']))) + dialog.set_current_name(self.canvas.get_default_filename()) + + @functools.partial(dialog.connect, 'response') + def on_response(dialog, response): + file = dialog.get_file() + fmt = dialog.get_choice('format') + fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0] + dialog.destroy() + self._save_dialog = None + if response != Gtk.ResponseType.ACCEPT: + return + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams['savefig.directory']: + parent = file.get_parent() + mpl.rcParams['savefig.directory'] = parent.get_path() + try: + self.canvas.figure.savefig(file.get_path(), format=fmt) + except Exception as e: + msg = Gtk.MessageDialog( + transient_for=self.canvas.get_root(), + message_type=Gtk.MessageType.ERROR, + buttons=Gtk.ButtonsType.OK, modal=True, + text=str(e)) + msg.show() + + dialog.show() + return self.UNKNOWN_SAVED_STATUS + + +class ToolbarGTK4(ToolContainerBase, Gtk.Box): + _icon_extension = '-symbolic.svg' + + def __init__(self, toolmanager): + ToolContainerBase.__init__(self, toolmanager) + Gtk.Box.__init__(self) + self.set_property('orientation', Gtk.Orientation.HORIZONTAL) + + # Tool items are created later, but must appear before the message. + self._tool_box = Gtk.Box() + self.append(self._tool_box) + self._groups = {} + self._toolitems = {} + + # This filler item ensures the toolbar is always at least two text + # lines high. Otherwise the canvas gets redrawn as the mouse hovers + # over images because those use two-line messages which resize the + # toolbar. + label = Gtk.Label() + label.set_markup( + '\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}') + label.set_hexpand(True) # Push real message to the right. + self.append(label) + + self._message = Gtk.Label() + self._message.set_justify(Gtk.Justification.RIGHT) + self.append(self._message) + + def add_toolitem(self, name, group, position, image_file, description, + toggle): + if toggle: + button = Gtk.ToggleButton() + else: + button = Gtk.Button() + button.set_label(name) + button.add_css_class('flat') + + if image_file is not None: + image = Gtk.Image.new_from_gicon( + Gio.Icon.new_for_string(image_file)) + button.set_child(image) + button.add_css_class('image-button') + + if position is None: + position = -1 + + self._add_button(button, group, position) + signal = button.connect('clicked', self._call_tool, name) + button.set_tooltip_text(description) + self._toolitems.setdefault(name, []) + self._toolitems[name].append((button, signal)) + + def _find_child_at_position(self, group, position): + children = [None] + child = self._groups[group].get_first_child() + while child is not None: + children.append(child) + child = child.get_next_sibling() + return children[position] + + def _add_button(self, button, group, position): + if group not in self._groups: + if self._groups: + self._add_separator() + group_box = Gtk.Box() + self._tool_box.append(group_box) + self._groups[group] = group_box + self._groups[group].insert_child_after( + button, self._find_child_at_position(group, position)) + + def _call_tool(self, btn, name): + self.trigger_tool(name) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for toolitem, signal in self._toolitems[name]: + toolitem.handler_block(signal) + toolitem.set_active(toggled) + toolitem.handler_unblock(signal) + + def remove_toolitem(self, name): + for toolitem, _signal in self._toolitems.pop(name, []): + for group in self._groups: + if toolitem in self._groups[group]: + self._groups[group].remove(toolitem) + + def _add_separator(self): + sep = Gtk.Separator() + sep.set_property("orientation", Gtk.Orientation.VERTICAL) + self._tool_box.append(sep) + + def set_message(self, s): + self._message.set_label(s) + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class SaveFigureGTK4(backend_tools.SaveFigureBase): + def trigger(self, *args, **kwargs): + NavigationToolbar2GTK4.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class HelpGTK4(backend_tools.ToolHelpBase): + def _normalize_shortcut(self, key): + """ + Convert Matplotlib key presses to GTK+ accelerator identifiers. + + Related to `FigureCanvasGTK4._get_key`. + """ + special = { + 'backspace': 'BackSpace', + 'pagedown': 'Page_Down', + 'pageup': 'Page_Up', + 'scroll_lock': 'Scroll_Lock', + } + + parts = key.split('+') + mods = ['<' + mod + '>' for mod in parts[:-1]] + key = parts[-1] + + if key in special: + key = special[key] + elif len(key) > 1: + key = key.capitalize() + elif key.isupper(): + mods += [''] + + return ''.join(mods) + key + + def _is_valid_shortcut(self, key): + """ + Check for a valid shortcut to be displayed. + + - GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`). + - The shortcut window only shows keyboard shortcuts, not mouse buttons. + """ + return 'cmd+' not in key and not key.startswith('MouseButton.') + + def trigger(self, *args): + section = Gtk.ShortcutsSection() + + for name, tool in sorted(self.toolmanager.tools.items()): + if not tool.description: + continue + + # Putting everything in a separate group allows GTK to + # automatically split them into separate columns/pages, which is + # useful because we have lots of shortcuts, some with many keys + # that are very wide. + group = Gtk.ShortcutsGroup() + section.append(group) + # A hack to remove the title since we have no group naming. + child = group.get_first_child() + while child is not None: + child.set_visible(False) + child = child.get_next_sibling() + + shortcut = Gtk.ShortcutsShortcut( + accelerator=' '.join( + self._normalize_shortcut(key) + for key in self.toolmanager.get_tool_keymap(name) + if self._is_valid_shortcut(key)), + title=tool.name, + subtitle=tool.description) + group.append(shortcut) + + window = Gtk.ShortcutsWindow( + title='Help', + modal=True, + transient_for=self._figure.canvas.get_root()) + window.set_child(section) + + window.show() + + +@backend_tools._register_tool_class(FigureCanvasGTK4) +class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + with io.BytesIO() as f: + self.canvas.print_rgba(f) + w, h = self.canvas.get_width_height() + pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(), + GdkPixbuf.Colorspace.RGB, True, + 8, w, h, w*4) + clipboard = self.canvas.get_clipboard() + clipboard.set(pb) + + +backend_tools._register_tool_class( + FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK) +backend_tools._register_tool_class( + FigureCanvasGTK4, _backend_gtk.RubberbandGTK) +Toolbar = ToolbarGTK4 + + +class FigureManagerGTK4(_FigureManagerGTK): + _toolbar2_class = NavigationToolbar2GTK4 + _toolmanager_toolbar_class = ToolbarGTK4 + + +@_BackendGTK.export +class _BackendGTK4(_BackendGTK): + FigureCanvas = FigureCanvasGTK4 + FigureManager = FigureManagerGTK4 diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4agg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4agg.py new file mode 100644 index 0000000000000000000000000000000000000000..0af07850a30aa1dac97fd24580e434e23b48bba5 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4agg.py @@ -0,0 +1,41 @@ +import numpy as np + +from .. import cbook +from . import backend_agg, backend_gtk4 +from .backend_gtk4 import GLib, Gtk, _BackendGTK4 + +import cairo # Presence of cairo is already checked by _backend_gtk. + + +class FigureCanvasGTK4Agg(backend_agg.FigureCanvasAgg, + backend_gtk4.FigureCanvasGTK4): + + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + scale = self.device_pixel_ratio + allocation = self.get_allocation() + + Gtk.render_background( + self.get_style_context(), ctx, + allocation.x, allocation.y, + allocation.width, allocation.height) + + buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32( + np.asarray(self.get_renderer().buffer_rgba())) + height, width, _ = buf.shape + image = cairo.ImageSurface.create_for_data( + buf.ravel().data, cairo.FORMAT_ARGB32, width, height) + image.set_device_scale(scale, scale) + ctx.set_source_surface(image, 0, 0) + ctx.paint() + + return False + + +@_BackendGTK4.export +class _BackendGTK4Agg(_BackendGTK4): + FigureCanvas = FigureCanvasGTK4Agg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4cairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..838ea03fcce6b4aec68de3baf876b876a1085803 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_gtk4cairo.py @@ -0,0 +1,32 @@ +from contextlib import nullcontext + +from .backend_cairo import FigureCanvasCairo +from .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4 + + +class FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4): + def _set_device_pixel_ratio(self, ratio): + # Cairo in GTK4 always uses logical pixels, so we don't need to do anything for + # changes to the device pixel ratio. + return False + + def on_draw_event(self, widget, ctx): + if self._idle_draw_id: + GLib.source_remove(self._idle_draw_id) + self._idle_draw_id = 0 + self.draw() + + with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar + else nullcontext()): + self._renderer.set_context(ctx) + allocation = self.get_allocation() + Gtk.render_background( + self.get_style_context(), ctx, + allocation.x, allocation.y, + allocation.width, allocation.height) + self.figure.draw(self._renderer) + + +@_BackendGTK4.export +class _BackendGTK4Cairo(_BackendGTK4): + FigureCanvas = FigureCanvasGTK4Cairo diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_macosx.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_macosx.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea437a90ca1af217820a0ae8f6571808f15b486 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_macosx.py @@ -0,0 +1,196 @@ +import os + +import matplotlib as mpl +from matplotlib import _api, cbook +from matplotlib._pylab_helpers import Gcf +from . import _macosx +from .backend_agg import FigureCanvasAgg +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + ResizeEvent, TimerBase, _allow_interrupt) + + +class TimerMac(_macosx.Timer, TimerBase): + """Subclass of `.TimerBase` using CFRunLoop timer events.""" + # completely implemented at the C-level (in _macosx.Timer) + + +def _allow_interrupt_macos(): + """A context manager that allows terminating a plot by sending a SIGINT.""" + return _allow_interrupt( + lambda rsock: _macosx.wake_on_fd_write(rsock.fileno()), _macosx.stop) + + +class FigureCanvasMac(FigureCanvasAgg, _macosx.FigureCanvas, FigureCanvasBase): + # docstring inherited + + # Ideally this class would be `class FCMacAgg(FCAgg, FCMac)` + # (FC=FigureCanvas) where FCMac would be an ObjC-implemented mac-specific + # class also inheriting from FCBase (this is the approach with other GUI + # toolkits). However, writing an extension type inheriting from a Python + # base class is slightly tricky (the extension type must be a heap type), + # and we can just as well lift the FCBase base up one level, keeping it *at + # the end* to have the right method resolution order. + + # Events such as button presses, mouse movements, and key presses are + # handled in C and events (MouseEvent, etc.) are triggered from there. + + required_interactive_framework = "macosx" + _timer_cls = TimerMac + manager_class = _api.classproperty(lambda cls: FigureManagerMac) + + def __init__(self, figure): + super().__init__(figure=figure) + self._draw_pending = False + self._is_drawing = False + # Keep track of the timers that are alive + self._timers = set() + + def draw(self): + """Render the figure and update the macosx canvas.""" + # The renderer draw is done here; delaying causes problems with code + # that uses the result of the draw() to update plot elements. + if self._is_drawing: + return + with cbook._setattr_cm(self, _is_drawing=True): + super().draw() + self.update() + + def draw_idle(self): + # docstring inherited + if not (getattr(self, '_draw_pending', False) or + getattr(self, '_is_drawing', False)): + self._draw_pending = True + # Add a singleshot timer to the eventloop that will call back + # into the Python method _draw_idle to take care of the draw + self._single_shot_timer(self._draw_idle) + + def _single_shot_timer(self, callback): + """Add a single shot timer with the given callback""" + def callback_func(callback, timer): + callback() + self._timers.remove(timer) + timer = self.new_timer(interval=0) + timer.single_shot = True + timer.add_callback(callback_func, callback, timer) + self._timers.add(timer) + timer.start() + + def _draw_idle(self): + """ + Draw method for singleshot timer + + This draw method can be added to a singleshot timer, which can + accumulate draws while the eventloop is spinning. This method will + then only draw the first time and short-circuit the others. + """ + with self._idle_draw_cntx(): + if not self._draw_pending: + # Short-circuit because our draw request has already been + # taken care of + return + self._draw_pending = False + self.draw() + + def blit(self, bbox=None): + # docstring inherited + super().blit(bbox) + self.update() + + def resize(self, width, height): + # Size from macOS is logical pixels, dpi is physical. + scale = self.figure.dpi / self.device_pixel_ratio + width /= scale + height /= scale + self.figure.set_size_inches(width, height, forward=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + def start_event_loop(self, timeout=0): + # docstring inherited + # Set up a SIGINT handler to allow terminating a plot via CTRL-C. + with _allow_interrupt_macos(): + self._start_event_loop(timeout=timeout) # Forward to ObjC implementation. + + +class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): + + def __init__(self, canvas): + data_path = cbook._get_data_path('images') + _, tooltips, image_names, _ = zip(*NavigationToolbar2.toolitems) + _macosx.NavigationToolbar2.__init__( + self, canvas, + tuple(str(data_path / image_name) + ".pdf" + for image_name in image_names if image_name is not None), + tuple(tooltip for tooltip in tooltips if tooltip is not None)) + NavigationToolbar2.__init__(self, canvas) + + def draw_rubberband(self, event, x0, y0, x1, y1): + self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1)) + + def remove_rubberband(self): + self.canvas.remove_rubberband() + + def save_figure(self, *args): + directory = os.path.expanduser(mpl.rcParams['savefig.directory']) + filename = _macosx.choose_save_file('Save the figure', + directory, + self.canvas.get_default_filename()) + if filename is None: # Cancel + return + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams['savefig.directory']: + mpl.rcParams['savefig.directory'] = os.path.dirname(filename) + self.canvas.figure.savefig(filename) + return filename + + +class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): + _toolbar2_class = NavigationToolbar2Mac + + def __init__(self, canvas, num): + self._shown = False + _macosx.FigureManager.__init__(self, canvas) + icon_path = str(cbook._get_data_path('images/matplotlib.pdf')) + _macosx.FigureManager.set_icon(icon_path) + FigureManagerBase.__init__(self, canvas, num) + self._set_window_mode(mpl.rcParams["macosx.window_mode"]) + if self.toolbar is not None: + self.toolbar.update() + if mpl.is_interactive(): + self.show() + self.canvas.draw_idle() + + def _close_button_pressed(self): + Gcf.destroy(self) + self.canvas.flush_events() + + def destroy(self): + # We need to clear any pending timers that never fired, otherwise + # we get a memory leak from the timer callbacks holding a reference + while self.canvas._timers: + timer = self.canvas._timers.pop() + timer.stop() + super().destroy() + + @classmethod + def start_main_loop(cls): + # Set up a SIGINT handler to allow terminating a plot via CTRL-C. + with _allow_interrupt_macos(): + _macosx.show() + + def show(self): + if self.canvas.figure.stale: + self.canvas.draw_idle() + if not self._shown: + self._show() + self._shown = True + if mpl.rcParams["figure.raise_window"]: + self._raise() + + +@_Backend.export +class _BackendMac(_Backend): + FigureCanvas = FigureCanvasMac + FigureManager = FigureManagerMac + mainloop = FigureManagerMac.start_main_loop diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_mixed.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_mixed.py new file mode 100644 index 0000000000000000000000000000000000000000..971d73cdb44882a70cf5d429cd2f02f445a62aeb --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_mixed.py @@ -0,0 +1,119 @@ +import numpy as np + +from matplotlib import cbook +from .backend_agg import RendererAgg +from matplotlib._tight_bbox import process_figure_for_rasterizing + + +class MixedModeRenderer: + """ + A helper class to implement a renderer that switches between + vector and raster drawing. An example may be a PDF writer, where + most things are drawn with PDF vector commands, but some very + complex objects, such as quad meshes, are rasterised and then + output as images. + """ + def __init__(self, figure, width, height, dpi, vector_renderer, + raster_renderer_class=None, + bbox_inches_restore=None): + """ + Parameters + ---------- + figure : `~matplotlib.figure.Figure` + The figure instance. + width : float + The width of the canvas in logical units + height : float + The height of the canvas in logical units + dpi : float + The dpi of the canvas + vector_renderer : `~matplotlib.backend_bases.RendererBase` + An instance of a subclass of + `~matplotlib.backend_bases.RendererBase` that will be used for the + vector drawing. + raster_renderer_class : `~matplotlib.backend_bases.RendererBase` + The renderer class to use for the raster drawing. If not provided, + this will use the Agg backend (which is currently the only viable + option anyway.) + + """ + if raster_renderer_class is None: + raster_renderer_class = RendererAgg + + self._raster_renderer_class = raster_renderer_class + self._width = width + self._height = height + self.dpi = dpi + + self._vector_renderer = vector_renderer + + self._raster_renderer = None + + # A reference to the figure is needed as we need to change + # the figure dpi before and after the rasterization. Although + # this looks ugly, I couldn't find a better solution. -JJL + self.figure = figure + self._figdpi = figure.dpi + + self._bbox_inches_restore = bbox_inches_restore + + self._renderer = vector_renderer + + def __getattr__(self, attr): + # Proxy everything that hasn't been overridden to the base + # renderer. Things that *are* overridden can call methods + # on self._renderer directly, but must not cache/store + # methods (because things like RendererAgg change their + # methods on the fly in order to optimise proxying down + # to the underlying C implementation). + return getattr(self._renderer, attr) + + def start_rasterizing(self): + """ + Enter "raster" mode. All subsequent drawing commands (until + `stop_rasterizing` is called) will be drawn with the raster backend. + """ + # change the dpi of the figure temporarily. + self.figure.dpi = self.dpi + if self._bbox_inches_restore: # when tight bbox is used + r = process_figure_for_rasterizing(self.figure, + self._bbox_inches_restore) + self._bbox_inches_restore = r + + self._raster_renderer = self._raster_renderer_class( + self._width*self.dpi, self._height*self.dpi, self.dpi) + self._renderer = self._raster_renderer + + def stop_rasterizing(self): + """ + Exit "raster" mode. All of the drawing that was done since + the last `start_rasterizing` call will be copied to the + vector backend by calling draw_image. + """ + + self._renderer = self._vector_renderer + + height = self._height * self.dpi + img = np.asarray(self._raster_renderer.buffer_rgba()) + slice_y, slice_x = cbook._get_nonzero_slices(img[..., 3]) + cropped_img = img[slice_y, slice_x] + if cropped_img.size: + gc = self._renderer.new_gc() + # TODO: If the mixedmode resolution differs from the figure's + # dpi, the image must be scaled (dpi->_figdpi). Not all + # backends support this. + self._renderer.draw_image( + gc, + slice_x.start * self._figdpi / self.dpi, + (height - slice_y.stop) * self._figdpi / self.dpi, + cropped_img[::-1]) + self._raster_renderer = None + + # restore the figure dpi. + self.figure.dpi = self._figdpi + + if self._bbox_inches_restore: # when tight bbox is used + r = process_figure_for_rasterizing(self.figure, + self._bbox_inches_restore, + self._figdpi) + self._bbox_inches_restore = r diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_nbagg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_nbagg.py new file mode 100644 index 0000000000000000000000000000000000000000..4d18e1e9fb88bd89cf5146d2c3f48bf3a54c9bca --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_nbagg.py @@ -0,0 +1,243 @@ +"""Interactive figures in the IPython notebook.""" +# Note: There is a notebook in +# lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify +# that changes made maintain expected behaviour. + +from base64 import b64encode +import io +import json +import pathlib +import uuid + +from ipykernel.comm import Comm +from IPython.display import display, Javascript, HTML + +from matplotlib import is_interactive +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2 +from .backend_webagg_core import ( + FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg) +from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611 + TimerTornado, TimerAsyncio) + + +def connection_info(): + """ + Return a string showing the figure and connection status for the backend. + + This is intended as a diagnostic tool, and not for general use. + """ + result = [ + '{fig} - {socket}'.format( + fig=(manager.canvas.figure.get_label() + or f"Figure {manager.num}"), + socket=manager.web_sockets) + for manager in Gcf.get_all_fig_managers() + ] + if not is_interactive(): + result.append(f'Figures pending show: {len(Gcf.figs)}') + return '\n'.join(result) + + +_FONT_AWESOME_CLASSES = { # font-awesome 4 names + 'home': 'fa fa-home', + 'back': 'fa fa-arrow-left', + 'forward': 'fa fa-arrow-right', + 'zoom_to_rect': 'fa fa-square-o', + 'move': 'fa fa-arrows', + 'download': 'fa fa-floppy-o', + None: None +} + + +class NavigationIPy(NavigationToolbar2WebAgg): + + # Use the standard toolbar items + download button + toolitems = [(text, tooltip_text, + _FONT_AWESOME_CLASSES[image_file], name_of_method) + for text, tooltip_text, image_file, name_of_method + in (NavigationToolbar2.toolitems + + (('Download', 'Download plot', 'download', 'download'),)) + if image_file in _FONT_AWESOME_CLASSES] + + +class FigureManagerNbAgg(FigureManagerWebAgg): + _toolbar2_class = ToolbarCls = NavigationIPy + + def __init__(self, canvas, num): + self._shown = False + super().__init__(canvas, num) + + @classmethod + def create_with_canvas(cls, canvas_class, figure, num): + canvas = canvas_class(figure) + manager = cls(canvas, num) + if is_interactive(): + manager.show() + canvas.draw_idle() + + def destroy(event): + canvas.mpl_disconnect(cid) + Gcf.destroy(manager) + + cid = canvas.mpl_connect('close_event', destroy) + return manager + + def display_js(self): + # XXX How to do this just once? It has to deal with multiple + # browser instances using the same kernel (require.js - but the + # file isn't static?). + display(Javascript(FigureManagerNbAgg.get_javascript())) + + def show(self): + if not self._shown: + self.display_js() + self._create_comm() + else: + self.canvas.draw_idle() + self._shown = True + # plt.figure adds an event which makes the figure in focus the active + # one. Disable this behaviour, as it results in figures being put as + # the active figure after they have been shown, even in non-interactive + # mode. + if hasattr(self, '_cidgcf'): + self.canvas.mpl_disconnect(self._cidgcf) + if not is_interactive(): + from matplotlib._pylab_helpers import Gcf + Gcf.figs.pop(self.num, None) + + def reshow(self): + """ + A special method to re-show the figure in the notebook. + + """ + self._shown = False + self.show() + + @property + def connected(self): + return bool(self.web_sockets) + + @classmethod + def get_javascript(cls, stream=None): + if stream is None: + output = io.StringIO() + else: + output = stream + super().get_javascript(stream=output) + output.write((pathlib.Path(__file__).parent + / "web_backend/js/nbagg_mpl.js") + .read_text(encoding="utf-8")) + if stream is None: + return output.getvalue() + + def _create_comm(self): + comm = CommSocket(self) + self.add_web_socket(comm) + return comm + + def destroy(self): + self._send_event('close') + # need to copy comms as callbacks will modify this list + for comm in list(self.web_sockets): + comm.on_close() + self.clearup_closed() + + def clearup_closed(self): + """Clear up any closed Comms.""" + self.web_sockets = {socket for socket in self.web_sockets + if socket.is_open()} + + if len(self.web_sockets) == 0: + CloseEvent("close_event", self.canvas)._process() + + def remove_comm(self, comm_id): + self.web_sockets = {socket for socket in self.web_sockets + if socket.comm.comm_id != comm_id} + + +class FigureCanvasNbAgg(FigureCanvasWebAggCore): + manager_class = FigureManagerNbAgg + + +class CommSocket: + """ + Manages the Comm connection between IPython and the browser (client). + + Comms are 2 way, with the CommSocket being able to publish a message + via the send_json method, and handle a message with on_message. On the + JS side figure.send_message and figure.ws.onmessage do the sending and + receiving respectively. + + """ + def __init__(self, manager): + self.supports_binary = None + self.manager = manager + self.uuid = str(uuid.uuid4()) + # Publish an output area with a unique ID. The javascript can then + # hook into this area. + display(HTML("
" % self.uuid)) + try: + self.comm = Comm('matplotlib', data={'id': self.uuid}) + except AttributeError as err: + raise RuntimeError('Unable to create an IPython notebook Comm ' + 'instance. Are you in the IPython ' + 'notebook?') from err + self.comm.on_msg(self.on_message) + + manager = self.manager + self._ext_close = False + + def _on_close(close_message): + self._ext_close = True + manager.remove_comm(close_message['content']['comm_id']) + manager.clearup_closed() + + self.comm.on_close(_on_close) + + def is_open(self): + return not (self._ext_close or self.comm._closed) + + def on_close(self): + # When the socket is closed, deregister the websocket with + # the FigureManager. + if self.is_open(): + try: + self.comm.close() + except KeyError: + # apparently already cleaned it up? + pass + + def send_json(self, content): + self.comm.send({'data': json.dumps(content)}) + + def send_binary(self, blob): + if self.supports_binary: + self.comm.send({'blob': 'image/png'}, buffers=[blob]) + else: + # The comm is ASCII, so we send the image in base64 encoded data + # URL form. + data = b64encode(blob).decode('ascii') + data_uri = f"data:image/png;base64,{data}" + self.comm.send({'data': data_uri}) + + def on_message(self, message): + # The 'supports_binary' message is relevant to the + # websocket itself. The other messages get passed along + # to matplotlib as-is. + + # Every message has a "type" and a "figure_id". + message = json.loads(message['content']['data']) + if message['type'] == 'closing': + self.on_close() + self.manager.clearup_closed() + elif message['type'] == 'supports_binary': + self.supports_binary = message['value'] + else: + self.manager.handle_json(message) + + +@_Backend.export +class _BackendNbAgg(_Backend): + FigureCanvas = FigureCanvasNbAgg + FigureManager = FigureManagerNbAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_pdf.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c5eb8819bef049516f6228530419faf9ff5b4f --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_pdf.py @@ -0,0 +1,2806 @@ +""" +A PDF Matplotlib backend. + +Author: Jouni K Seppänen and others. +""" + +import codecs +from datetime import timezone +from datetime import datetime +from enum import Enum +from functools import total_ordering +from io import BytesIO +import itertools +import logging +import math +import os +import string +import struct +import sys +import time +import types +import warnings +import zlib + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import _api, _text_helpers, _type1font, cbook, dviread +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, + RendererBase) +from matplotlib.backends.backend_mixed import MixedModeRenderer +from matplotlib.figure import Figure +from matplotlib.font_manager import get_font, fontManager as _fontManager +from matplotlib._afm import AFM +from matplotlib.ft2font import FT2Font, FaceFlags, Kerning, LoadFlags, StyleFlags +from matplotlib.transforms import Affine2D, BboxBase +from matplotlib.path import Path +from matplotlib.dates import UTC +from matplotlib import _path +from . import _backend_pdf_ps + +_log = logging.getLogger(__name__) + +# Overview +# +# The low-level knowledge about pdf syntax lies mainly in the pdfRepr +# function and the classes Reference, Name, Operator, and Stream. The +# PdfFile class knows about the overall structure of pdf documents. +# It provides a "write" method for writing arbitrary strings in the +# file, and an "output" method that passes objects through the pdfRepr +# function before writing them in the file. The output method is +# called by the RendererPdf class, which contains the various draw_foo +# methods. RendererPdf contains a GraphicsContextPdf instance, and +# each draw_foo calls self.check_gc before outputting commands. This +# method checks whether the pdf graphics state needs to be modified +# and outputs the necessary commands. GraphicsContextPdf represents +# the graphics state, and its "delta" method returns the commands that +# modify the state. + +# Add "pdf.use14corefonts: True" in your configuration file to use only +# the 14 PDF core fonts. These fonts do not need to be embedded; every +# PDF viewing application is required to have them. This results in very +# light PDF files you can use directly in LaTeX or ConTeXt documents +# generated with pdfTeX, without any conversion. + +# These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique, +# Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique, +# Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic, +# Times-BoldItalic, Symbol, ZapfDingbats. +# +# Some tricky points: +# +# 1. The clip path can only be widened by popping from the state +# stack. Thus the state must be pushed onto the stack before narrowing +# the clip path. This is taken care of by GraphicsContextPdf. +# +# 2. Sometimes it is necessary to refer to something (e.g., font, +# image, or extended graphics state, which contains the alpha value) +# in the page stream by a name that needs to be defined outside the +# stream. PdfFile provides the methods fontName, imageObject, and +# alphaState for this purpose. The implementations of these methods +# should perhaps be generalized. + +# TODOs: +# +# * encoding of fonts, including mathtext fonts and Unicode support +# * TTF support has lots of small TODOs, e.g., how do you know if a font +# is serif/sans-serif, or symbolic/non-symbolic? +# * draw_quad_mesh + + +def _fill(strings, linelen=75): + """ + Make one string from sequence of strings, with whitespace in between. + + The whitespace is chosen to form lines of at most *linelen* characters, + if possible. + """ + currpos = 0 + lasti = 0 + result = [] + for i, s in enumerate(strings): + length = len(s) + if currpos + length < linelen: + currpos += length + 1 + else: + result.append(b' '.join(strings[lasti:i])) + lasti = i + currpos = length + result.append(b' '.join(strings[lasti:])) + return b'\n'.join(result) + + +def _create_pdf_info_dict(backend, metadata): + """ + Create a PDF infoDict based on user-supplied metadata. + + A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though + the user metadata may override it. The date may be the current time, or a + time set by the ``SOURCE_DATE_EPOCH`` environment variable. + + Metadata is verified to have the correct keys and their expected types. Any + unknown keys/types will raise a warning. + + Parameters + ---------- + backend : str + The name of the backend to use in the Producer value. + + metadata : dict[str, Union[str, datetime, Name]] + A dictionary of metadata supplied by the user with information + following the PDF specification, also defined in + `~.backend_pdf.PdfPages` below. + + If any value is *None*, then the key will be removed. This can be used + to remove any pre-defined values. + + Returns + ------- + dict[str, Union[str, datetime, Name]] + A validated dictionary of metadata. + """ + + # get source date from SOURCE_DATE_EPOCH, if set + # See https://reproducible-builds.org/specs/source-date-epoch/ + source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") + if source_date_epoch: + source_date = datetime.fromtimestamp(int(source_date_epoch), timezone.utc) + source_date = source_date.replace(tzinfo=UTC) + else: + source_date = datetime.today() + + info = { + 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + 'Producer': f'Matplotlib {backend} backend v{mpl.__version__}', + 'CreationDate': source_date, + **metadata + } + info = {k: v for (k, v) in info.items() if v is not None} + + def is_string_like(x): + return isinstance(x, str) + is_string_like.text_for_warning = "an instance of str" + + def is_date(x): + return isinstance(x, datetime) + is_date.text_for_warning = "an instance of datetime.datetime" + + def check_trapped(x): + if isinstance(x, Name): + return x.name in (b'True', b'False', b'Unknown') + else: + return x in ('True', 'False', 'Unknown') + check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}' + + keywords = { + 'Title': is_string_like, + 'Author': is_string_like, + 'Subject': is_string_like, + 'Keywords': is_string_like, + 'Creator': is_string_like, + 'Producer': is_string_like, + 'CreationDate': is_date, + 'ModDate': is_date, + 'Trapped': check_trapped, + } + for k in info: + if k not in keywords: + _api.warn_external(f'Unknown infodict keyword: {k!r}. ' + f'Must be one of {set(keywords)!r}.') + elif not keywords[k](info[k]): + _api.warn_external(f'Bad value for infodict keyword {k}. ' + f'Got {info[k]!r} which is not ' + f'{keywords[k].text_for_warning}.') + if 'Trapped' in info: + info['Trapped'] = Name(info['Trapped']) + + return info + + +def _datetime_to_pdf(d): + """ + Convert a datetime to a PDF string representing it. + + Used for PDF and PGF. + """ + r = d.strftime('D:%Y%m%d%H%M%S') + z = d.utcoffset() + if z is not None: + z = z.seconds + else: + if time.daylight: + z = time.altzone + else: + z = time.timezone + if z == 0: + r += 'Z' + elif z < 0: + r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600) + else: + r += "-%02d'%02d'" % (z // 3600, z % 3600) + return r + + +def _calculate_quad_point_coordinates(x, y, width, height, angle=0): + """ + Calculate the coordinates of rectangle when rotated by angle around x, y + """ + + angle = math.radians(-angle) + sin_angle = math.sin(angle) + cos_angle = math.cos(angle) + a = x + height * sin_angle + b = y + height * cos_angle + c = x + width * cos_angle + height * sin_angle + d = y - width * sin_angle + height * cos_angle + e = x + width * cos_angle + f = y - width * sin_angle + return ((x, y), (e, f), (c, d), (a, b)) + + +def _get_coordinates_of_block(x, y, width, height, angle=0): + """ + Get the coordinates of rotated rectangle and rectangle that covers the + rotated rectangle. + """ + + vertices = _calculate_quad_point_coordinates(x, y, width, + height, angle) + + # Find min and max values for rectangle + # adjust so that QuadPoints is inside Rect + # PDF docs says that QuadPoints should be ignored if any point lies + # outside Rect, but for Acrobat it is enough that QuadPoints is on the + # border of Rect. + + pad = 0.00001 if angle % 90 else 0 + min_x = min(v[0] for v in vertices) - pad + min_y = min(v[1] for v in vertices) - pad + max_x = max(v[0] for v in vertices) + pad + max_y = max(v[1] for v in vertices) + pad + return (tuple(itertools.chain.from_iterable(vertices)), + (min_x, min_y, max_x, max_y)) + + +def _get_link_annotation(gc, x, y, width, height, angle=0): + """ + Create a link annotation object for embedding URLs. + """ + quadpoints, rect = _get_coordinates_of_block(x, y, width, height, angle) + link_annotation = { + 'Type': Name('Annot'), + 'Subtype': Name('Link'), + 'Rect': rect, + 'Border': [0, 0, 0], + 'A': { + 'S': Name('URI'), + 'URI': gc.get_url(), + }, + } + if angle % 90: + # Add QuadPoints + link_annotation['QuadPoints'] = quadpoints + return link_annotation + + +# PDF strings are supposed to be able to include any eight-bit data, except +# that unbalanced parens and backslashes must be escaped by a backslash. +# However, sf bug #2708559 shows that the carriage return character may get +# read as a newline; these characters correspond to \gamma and \Omega in TeX's +# math font encoding. Escaping them fixes the bug. +_str_escapes = str.maketrans({ + '\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'}) + + +def pdfRepr(obj): + """Map Python objects to PDF syntax.""" + + # Some objects defined later have their own pdfRepr method. + if hasattr(obj, 'pdfRepr'): + return obj.pdfRepr() + + # Floats. PDF does not have exponential notation (1.0e-10) so we + # need to use %f with some precision. Perhaps the precision + # should adapt to the magnitude of the number? + elif isinstance(obj, (float, np.floating)): + if not np.isfinite(obj): + raise ValueError("Can only output finite numbers in PDF") + r = b"%.10f" % obj + return r.rstrip(b'0').rstrip(b'.') + + # Booleans. Needs to be tested before integers since + # isinstance(True, int) is true. + elif isinstance(obj, bool): + return [b'false', b'true'][obj] + + # Integers are written as such. + elif isinstance(obj, (int, np.integer)): + return b"%d" % obj + + # Non-ASCII Unicode strings are encoded in UTF-16BE with byte-order mark. + elif isinstance(obj, str): + return pdfRepr(obj.encode('ascii') if obj.isascii() + else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE')) + + # Strings are written in parentheses, with backslashes and parens + # escaped. Actually balanced parens are allowed, but it is + # simpler to escape them all. TODO: cut long strings into lines; + # I believe there is some maximum line length in PDF. + # Despite the extra decode/encode, translate is faster than regex. + elif isinstance(obj, bytes): + return ( + b'(' + + obj.decode('latin-1').translate(_str_escapes).encode('latin-1') + + b')') + + # Dictionaries. The keys must be PDF names, so if we find strings + # there, we make Name objects from them. The values may be + # anything, so the caller must ensure that PDF names are + # represented as Name objects. + elif isinstance(obj, dict): + return _fill([ + b"<<", + *[Name(k).pdfRepr() + b" " + pdfRepr(v) for k, v in obj.items()], + b">>", + ]) + + # Lists. + elif isinstance(obj, (list, tuple)): + return _fill([b"[", *[pdfRepr(val) for val in obj], b"]"]) + + # The null keyword. + elif obj is None: + return b'null' + + # A date. + elif isinstance(obj, datetime): + return pdfRepr(_datetime_to_pdf(obj)) + + # A bounding box + elif isinstance(obj, BboxBase): + return _fill([pdfRepr(val) for val in obj.bounds]) + + else: + raise TypeError(f"Don't know a PDF representation for {type(obj)} " + "objects") + + +def _font_supports_glyph(fonttype, glyph): + """ + Returns True if the font is able to provide codepoint *glyph* in a PDF. + + For a Type 3 font, this method returns True only for single-byte + characters. For Type 42 fonts this method return True if the character is + from the Basic Multilingual Plane. + """ + if fonttype == 3: + return glyph <= 255 + if fonttype == 42: + return glyph <= 65535 + raise NotImplementedError() + + +class Reference: + """ + PDF reference object. + + Use PdfFile.reserveObject() to create References. + """ + + def __init__(self, id): + self.id = id + + def __repr__(self): + return "" % self.id + + def pdfRepr(self): + return b"%d 0 R" % self.id + + def write(self, contents, file): + write = file.write + write(b"%d 0 obj\n" % self.id) + write(pdfRepr(contents)) + write(b"\nendobj\n") + + +@total_ordering +class Name: + """PDF name object.""" + __slots__ = ('name',) + _hexify = {c: '#%02x' % c + for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}} + + def __init__(self, name): + if isinstance(name, Name): + self.name = name.name + else: + if isinstance(name, bytes): + name = name.decode('ascii') + self.name = name.translate(self._hexify).encode('ascii') + + def __repr__(self): + return "" % self.name + + def __str__(self): + return '/' + self.name.decode('ascii') + + def __eq__(self, other): + return isinstance(other, Name) and self.name == other.name + + def __lt__(self, other): + return isinstance(other, Name) and self.name < other.name + + def __hash__(self): + return hash(self.name) + + def pdfRepr(self): + return b'/' + self.name + + +class Verbatim: + """Store verbatim PDF command content for later inclusion in the stream.""" + def __init__(self, x): + self._x = x + + def pdfRepr(self): + return self._x + + +class Op(Enum): + """PDF operators (not an exhaustive list).""" + + close_fill_stroke = b'b' + fill_stroke = b'B' + fill = b'f' + closepath = b'h' + close_stroke = b's' + stroke = b'S' + endpath = b'n' + begin_text = b'BT' + end_text = b'ET' + curveto = b'c' + rectangle = b're' + lineto = b'l' + moveto = b'm' + concat_matrix = b'cm' + use_xobject = b'Do' + setgray_stroke = b'G' + setgray_nonstroke = b'g' + setrgb_stroke = b'RG' + setrgb_nonstroke = b'rg' + setcolorspace_stroke = b'CS' + setcolorspace_nonstroke = b'cs' + setcolor_stroke = b'SCN' + setcolor_nonstroke = b'scn' + setdash = b'd' + setlinejoin = b'j' + setlinecap = b'J' + setgstate = b'gs' + gsave = b'q' + grestore = b'Q' + textpos = b'Td' + selectfont = b'Tf' + textmatrix = b'Tm' + show = b'Tj' + showkern = b'TJ' + setlinewidth = b'w' + clip = b'W' + shading = b'sh' + + def pdfRepr(self): + return self.value + + @classmethod + def paint_path(cls, fill, stroke): + """ + Return the PDF operator to paint a path. + + Parameters + ---------- + fill : bool + Fill the path with the fill color. + stroke : bool + Stroke the outline of the path with the line color. + """ + if stroke: + if fill: + return cls.fill_stroke + else: + return cls.stroke + else: + if fill: + return cls.fill + else: + return cls.endpath + + +class Stream: + """ + PDF stream object. + + This has no pdfRepr method. Instead, call begin(), then output the + contents of the stream by calling write(), and finally call end(). + """ + __slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos') + + def __init__(self, id, len, file, extra=None, png=None): + """ + Parameters + ---------- + id : int + Object id of the stream. + len : Reference or None + An unused Reference object for the length of the stream; + None means to use a memory buffer so the length can be inlined. + file : PdfFile + The underlying object to write the stream to. + extra : dict from Name to anything, or None + Extra key-value pairs to include in the stream header. + png : dict or None + If the data is already png encoded, the decode parameters. + """ + self.id = id # object id + self.len = len # id of length object + self.pdfFile = file + self.file = file.fh # file to which the stream is written + self.compressobj = None # compression object + if extra is None: + self.extra = dict() + else: + self.extra = extra.copy() + if png is not None: + self.extra.update({'Filter': Name('FlateDecode'), + 'DecodeParms': png}) + + self.pdfFile.recordXref(self.id) + if mpl.rcParams['pdf.compression'] and not png: + self.compressobj = zlib.compressobj( + mpl.rcParams['pdf.compression']) + if self.len is None: + self.file = BytesIO() + else: + self._writeHeader() + self.pos = self.file.tell() + + def _writeHeader(self): + write = self.file.write + write(b"%d 0 obj\n" % self.id) + dict = self.extra + dict['Length'] = self.len + if mpl.rcParams['pdf.compression']: + dict['Filter'] = Name('FlateDecode') + + write(pdfRepr(dict)) + write(b"\nstream\n") + + def end(self): + """Finalize stream.""" + + self._flush() + if self.len is None: + contents = self.file.getvalue() + self.len = len(contents) + self.file = self.pdfFile.fh + self._writeHeader() + self.file.write(contents) + self.file.write(b"\nendstream\nendobj\n") + else: + length = self.file.tell() - self.pos + self.file.write(b"\nendstream\nendobj\n") + self.pdfFile.writeObject(self.len, length) + + def write(self, data): + """Write some data on the stream.""" + + if self.compressobj is None: + self.file.write(data) + else: + compressed = self.compressobj.compress(data) + self.file.write(compressed) + + def _flush(self): + """Flush the compression object.""" + + if self.compressobj is not None: + compressed = self.compressobj.flush() + self.file.write(compressed) + self.compressobj = None + + +def _get_pdf_charprocs(font_path, glyph_ids): + font = get_font(font_path, hinting_factor=1) + conv = 1000 / font.units_per_EM # Conversion to PS units (1/1000's). + procs = {} + for glyph_id in glyph_ids: + g = font.load_glyph(glyph_id, LoadFlags.NO_SCALE) + # NOTE: We should be using round(), but instead use + # "(x+.5).astype(int)" to keep backcompat with the old ttconv code + # (this is different for negative x's). + d1 = (np.array([g.horiAdvance, 0, *g.bbox]) * conv + .5).astype(int) + v, c = font.get_path() + v = (v * 64).astype(int) # Back to TrueType's internal units (1/64's). + # Backcompat with old ttconv code: control points between two quads are + # omitted if they are exactly at the midpoint between the control of + # the quad before and the quad after, but ttconv used to interpolate + # *after* conversion to PS units, causing floating point errors. Here + # we reproduce ttconv's logic, detecting these "implicit" points and + # re-interpolating them. Note that occasionally (e.g. with DejaVu Sans + # glyph "0") a point detected as "implicit" is actually explicit, and + # will thus be shifted by 1. + quads, = np.nonzero(c == 3) + quads_on = quads[1::2] + quads_mid_on = np.array( + sorted({*quads_on} & {*(quads - 1)} & {*(quads + 1)}), int) + implicit = quads_mid_on[ + (v[quads_mid_on] # As above, use astype(int), not // division + == ((v[quads_mid_on - 1] + v[quads_mid_on + 1]) / 2).astype(int)) + .all(axis=1)] + if (font.postscript_name, glyph_id) in [ + ("DejaVuSerif-Italic", 77), # j + ("DejaVuSerif-Italic", 135), # \AA + ]: + v[:, 0] -= 1 # Hard-coded backcompat (FreeType shifts glyph by 1). + v = (v * conv + .5).astype(int) # As above re: truncation vs rounding. + v[implicit] = (( # Fix implicit points; again, truncate. + (v[implicit - 1] + v[implicit + 1]) / 2).astype(int)) + procs[font.get_glyph_name(glyph_id)] = ( + " ".join(map(str, d1)).encode("ascii") + b" d1\n" + + _path.convert_to_string( + Path(v, c), None, None, False, None, -1, + # no code for quad Beziers triggers auto-conversion to cubics. + [b"m", b"l", b"", b"c", b"h"], True) + + b"f") + return procs + + +class PdfFile: + """PDF file object.""" + + def __init__(self, filename, metadata=None): + """ + Parameters + ---------- + filename : str or path-like or file-like + Output target; if a string, a file will be opened for writing. + + metadata : dict from strings to strings and dates + Information dictionary object (see PDF reference section 10.2.1 + 'Document Information Dictionary'), e.g.: + ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``. + + The standard keys are 'Title', 'Author', 'Subject', 'Keywords', + 'Creator', 'Producer', 'CreationDate', 'ModDate', and + 'Trapped'. Values have been predefined for 'Creator', 'Producer' + and 'CreationDate'. They can be removed by setting them to `None`. + """ + super().__init__() + + self._object_seq = itertools.count(1) # consumed by reserveObject + self.xrefTable = [[0, 65535, 'the zero object']] + self.passed_in_file_object = False + self.original_file_like = None + self.tell_base = 0 + fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True) + if not opened: + try: + self.tell_base = filename.tell() + except OSError: + fh = BytesIO() + self.original_file_like = filename + else: + fh = filename + self.passed_in_file_object = True + + self.fh = fh + self.currentstream = None # stream object to write to, if any + fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha + # Output some eight-bit chars as a comment so various utilities + # recognize the file as binary by looking at the first few + # lines (see note in section 3.4.1 of the PDF reference). + fh.write(b"%\254\334 \253\272\n") + + self.rootObject = self.reserveObject('root') + self.pagesObject = self.reserveObject('pages') + self.pageList = [] + self.fontObject = self.reserveObject('fonts') + self._extGStateObject = self.reserveObject('extended graphics states') + self.hatchObject = self.reserveObject('tiling patterns') + self.gouraudObject = self.reserveObject('Gouraud triangles') + self.XObjectObject = self.reserveObject('external objects') + self.resourceObject = self.reserveObject('resources') + + root = {'Type': Name('Catalog'), + 'Pages': self.pagesObject} + self.writeObject(self.rootObject, root) + + self.infoDict = _create_pdf_info_dict('pdf', metadata or {}) + + self.fontNames = {} # maps filenames to internal font names + self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1)) + self.dviFontInfo = {} # maps dvi font names to embedding information + # differently encoded Type-1 fonts may share the same descriptor + self.type1Descriptors = {} + self._character_tracker = _backend_pdf_ps.CharacterTracker() + + self.alphaStates = {} # maps alpha values to graphics state objects + self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1)) + self._soft_mask_states = {} + self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1)) + self._soft_mask_groups = [] + self._hatch_patterns = {} + self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1)) + self.gouraudTriangles = [] + + self._images = {} + self._image_seq = (Name(f'I{i}') for i in itertools.count(1)) + + self.markers = {} + self.multi_byte_charprocs = {} + + self.paths = [] + + # A list of annotations for each page. Each entry is a tuple of the + # overall Annots object reference that's inserted into the page object, + # followed by a list of the actual annotations. + self._annotations = [] + # For annotations added before a page is created; mostly for the + # purpose of newTextnote. + self.pageAnnotations = [] + + # The PDF spec recommends to include every procset + procsets = [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()] + + # Write resource dictionary. + # Possibly TODO: more general ExtGState (graphics state dictionaries) + # ColorSpace Pattern Shading Properties + resources = {'Font': self.fontObject, + 'XObject': self.XObjectObject, + 'ExtGState': self._extGStateObject, + 'Pattern': self.hatchObject, + 'Shading': self.gouraudObject, + 'ProcSet': procsets} + self.writeObject(self.resourceObject, resources) + + def newPage(self, width, height): + self.endStream() + + self.width, self.height = width, height + contentObject = self.reserveObject('page contents') + annotsObject = self.reserveObject('annotations') + thePage = {'Type': Name('Page'), + 'Parent': self.pagesObject, + 'Resources': self.resourceObject, + 'MediaBox': [0, 0, 72 * width, 72 * height], + 'Contents': contentObject, + 'Annots': annotsObject, + } + pageObject = self.reserveObject('page') + self.writeObject(pageObject, thePage) + self.pageList.append(pageObject) + self._annotations.append((annotsObject, self.pageAnnotations)) + + self.beginStream(contentObject.id, + self.reserveObject('length of content stream')) + # Initialize the pdf graphics state to match the default Matplotlib + # graphics context (colorspace and joinstyle). + self.output(Name('DeviceRGB'), Op.setcolorspace_stroke) + self.output(Name('DeviceRGB'), Op.setcolorspace_nonstroke) + self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin) + + # Clear the list of annotations for the next page + self.pageAnnotations = [] + + def newTextnote(self, text, positionRect=[-100, -100, 0, 0]): + # Create a new annotation of type text + theNote = {'Type': Name('Annot'), + 'Subtype': Name('Text'), + 'Contents': text, + 'Rect': positionRect, + } + self.pageAnnotations.append(theNote) + + def _get_subsetted_psname(self, ps_name, charmap): + def toStr(n, base): + if n < base: + return string.ascii_uppercase[n] + else: + return ( + toStr(n // base, base) + string.ascii_uppercase[n % base] + ) + + # encode to string using base 26 + hashed = hash(frozenset(charmap.keys())) % ((sys.maxsize + 1) * 2) + prefix = toStr(hashed, 26) + + # get first 6 characters from prefix + return prefix[:6] + "+" + ps_name + + def finalize(self): + """Write out the various deferred objects and the pdf end matter.""" + + self.endStream() + self._write_annotations() + self.writeFonts() + self.writeExtGSTates() + self._write_soft_mask_groups() + self.writeHatches() + self.writeGouraudTriangles() + xobjects = { + name: ob for image, name, ob in self._images.values()} + for tup in self.markers.values(): + xobjects[tup[0]] = tup[1] + for name, value in self.multi_byte_charprocs.items(): + xobjects[name] = value + for name, path, trans, ob, join, cap, padding, filled, stroked \ + in self.paths: + xobjects[name] = ob + self.writeObject(self.XObjectObject, xobjects) + self.writeImages() + self.writeMarkers() + self.writePathCollectionTemplates() + self.writeObject(self.pagesObject, + {'Type': Name('Pages'), + 'Kids': self.pageList, + 'Count': len(self.pageList)}) + self.writeInfoDict() + + # Finalize the file + self.writeXref() + self.writeTrailer() + + def close(self): + """Flush all buffers and free all resources.""" + + self.endStream() + if self.passed_in_file_object: + self.fh.flush() + else: + if self.original_file_like is not None: + self.original_file_like.write(self.fh.getvalue()) + self.fh.close() + + def write(self, data): + if self.currentstream is None: + self.fh.write(data) + else: + self.currentstream.write(data) + + def output(self, *data): + self.write(_fill([pdfRepr(x) for x in data])) + self.write(b'\n') + + def beginStream(self, id, len, extra=None, png=None): + assert self.currentstream is None + self.currentstream = Stream(id, len, self, extra, png) + + def endStream(self): + if self.currentstream is not None: + self.currentstream.end() + self.currentstream = None + + def outputStream(self, ref, data, *, extra=None): + self.beginStream(ref.id, None, extra) + self.currentstream.write(data) + self.endStream() + + def _write_annotations(self): + for annotsObject, annotations in self._annotations: + self.writeObject(annotsObject, annotations) + + def fontName(self, fontprop): + """ + Select a font based on fontprop and return a name suitable for + Op.selectfont. If fontprop is a string, it will be interpreted + as the filename of the font. + """ + + if isinstance(fontprop, str): + filenames = [fontprop] + elif mpl.rcParams['pdf.use14corefonts']: + filenames = _fontManager._find_fonts_by_props( + fontprop, fontext='afm', directory=RendererPdf._afm_font_dir + ) + else: + filenames = _fontManager._find_fonts_by_props(fontprop) + first_Fx = None + for fname in filenames: + Fx = self.fontNames.get(fname) + if not first_Fx: + first_Fx = Fx + if Fx is None: + Fx = next(self._internal_font_seq) + self.fontNames[fname] = Fx + _log.debug('Assigning font %s = %r', Fx, fname) + if not first_Fx: + first_Fx = Fx + + # find_fontsprop's first value always adheres to + # findfont's value, so technically no behaviour change + return first_Fx + + def dviFontName(self, dvifont): + """ + Given a dvi font object, return a name suitable for Op.selectfont. + This registers the font information in ``self.dviFontInfo`` if not yet + registered. + """ + + dvi_info = self.dviFontInfo.get(dvifont.texname) + if dvi_info is not None: + return dvi_info.pdfname + + tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) + psfont = tex_font_map[dvifont.texname] + if psfont.filename is None: + raise ValueError( + "No usable font file found for {} (TeX: {}); " + "the font may lack a Type-1 version" + .format(psfont.psname, dvifont.texname)) + + pdfname = next(self._internal_font_seq) + _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) + self.dviFontInfo[dvifont.texname] = types.SimpleNamespace( + dvifont=dvifont, + pdfname=pdfname, + fontfile=psfont.filename, + basefont=psfont.psname, + encodingfile=psfont.encoding, + effects=psfont.effects) + return pdfname + + def writeFonts(self): + fonts = {} + for dviname, info in sorted(self.dviFontInfo.items()): + Fx = info.pdfname + _log.debug('Embedding Type-1 font %s from dvi.', dviname) + fonts[Fx] = self._embedTeXFont(info) + for filename in sorted(self.fontNames): + Fx = self.fontNames[filename] + _log.debug('Embedding font %s.', filename) + if filename.endswith('.afm'): + # from pdf.use14corefonts + _log.debug('Writing AFM font.') + fonts[Fx] = self._write_afm_font(filename) + else: + # a normal TrueType font + _log.debug('Writing TrueType font.') + chars = self._character_tracker.used.get(filename) + if chars: + fonts[Fx] = self.embedTTF(filename, chars) + self.writeObject(self.fontObject, fonts) + + def _write_afm_font(self, filename): + with open(filename, 'rb') as fh: + font = AFM(fh) + fontname = font.get_fontname() + fontdict = {'Type': Name('Font'), + 'Subtype': Name('Type1'), + 'BaseFont': Name(fontname), + 'Encoding': Name('WinAnsiEncoding')} + fontdictObject = self.reserveObject('font dictionary') + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + def _embedTeXFont(self, fontinfo): + _log.debug('Embedding TeX font %s - fontinfo=%s', + fontinfo.dvifont.texname, fontinfo.__dict__) + + # Widths + widthsObject = self.reserveObject('font widths') + self.writeObject(widthsObject, fontinfo.dvifont.widths) + + # Font dictionary + fontdictObject = self.reserveObject('font dictionary') + fontdict = { + 'Type': Name('Font'), + 'Subtype': Name('Type1'), + 'FirstChar': 0, + 'LastChar': len(fontinfo.dvifont.widths) - 1, + 'Widths': widthsObject, + } + + # Encoding (if needed) + if fontinfo.encodingfile is not None: + fontdict['Encoding'] = { + 'Type': Name('Encoding'), + 'Differences': [ + 0, *map(Name, dviread._parse_enc(fontinfo.encodingfile))], + } + + # If no file is specified, stop short + if fontinfo.fontfile is None: + _log.warning( + "Because of TeX configuration (pdftex.map, see updmap option " + "pdftexDownloadBase14) the font %s is not embedded. This is " + "deprecated as of PDF 1.5 and it may cause the consumer " + "application to show something that was not intended.", + fontinfo.basefont) + fontdict['BaseFont'] = Name(fontinfo.basefont) + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + # We have a font file to embed - read it in and apply any effects + t1font = _type1font.Type1Font(fontinfo.fontfile) + if fontinfo.effects: + t1font = t1font.transform(fontinfo.effects) + fontdict['BaseFont'] = Name(t1font.prop['FontName']) + + # Font descriptors may be shared between differently encoded + # Type-1 fonts, so only create a new descriptor if there is no + # existing descriptor for this font. + effects = (fontinfo.effects.get('slant', 0.0), + fontinfo.effects.get('extend', 1.0)) + fontdesc = self.type1Descriptors.get((fontinfo.fontfile, effects)) + if fontdesc is None: + fontdesc = self.createType1Descriptor(t1font, fontinfo.fontfile) + self.type1Descriptors[(fontinfo.fontfile, effects)] = fontdesc + fontdict['FontDescriptor'] = fontdesc + + self.writeObject(fontdictObject, fontdict) + return fontdictObject + + def createType1Descriptor(self, t1font, fontfile): + # Create and write the font descriptor and the font file + # of a Type-1 font + fontdescObject = self.reserveObject('font descriptor') + fontfileObject = self.reserveObject('font file') + + italic_angle = t1font.prop['ItalicAngle'] + fixed_pitch = t1font.prop['isFixedPitch'] + + flags = 0 + # fixed width + if fixed_pitch: + flags |= 1 << 0 + # TODO: serif + if 0: + flags |= 1 << 1 + # TODO: symbolic (most TeX fonts are) + if 1: + flags |= 1 << 2 + # non-symbolic + else: + flags |= 1 << 5 + # italic + if italic_angle: + flags |= 1 << 6 + # TODO: all caps + if 0: + flags |= 1 << 16 + # TODO: small caps + if 0: + flags |= 1 << 17 + # TODO: force bold + if 0: + flags |= 1 << 18 + + ft2font = get_font(fontfile) + + descriptor = { + 'Type': Name('FontDescriptor'), + 'FontName': Name(t1font.prop['FontName']), + 'Flags': flags, + 'FontBBox': ft2font.bbox, + 'ItalicAngle': italic_angle, + 'Ascent': ft2font.ascender, + 'Descent': ft2font.descender, + 'CapHeight': 1000, # TODO: find this out + 'XHeight': 500, # TODO: this one too + 'FontFile': fontfileObject, + 'FontFamily': t1font.prop['FamilyName'], + 'StemV': 50, # TODO + # (see also revision 3874; but not all TeX distros have AFM files!) + # 'FontWeight': a number where 400 = Regular, 700 = Bold + } + + self.writeObject(fontdescObject, descriptor) + + self.outputStream(fontfileObject, b"".join(t1font.parts[:2]), + extra={'Length1': len(t1font.parts[0]), + 'Length2': len(t1font.parts[1]), + 'Length3': 0}) + + return fontdescObject + + def _get_xobject_glyph_name(self, filename, glyph_name): + Fx = self.fontName(filename) + return "-".join([ + Fx.name.decode(), + os.path.splitext(os.path.basename(filename))[0], + glyph_name]) + + _identityToUnicodeCMap = b"""/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CIDSystemInfo +<< /Registry (Adobe) + /Ordering (UCS) + /Supplement 0 +>> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +%d beginbfrange +%s +endbfrange +endcmap +CMapName currentdict /CMap defineresource pop +end +end""" + + def embedTTF(self, filename, characters): + """Embed the TTF font from the named file into the document.""" + + font = get_font(filename) + fonttype = mpl.rcParams['pdf.fonttype'] + + def cvt(length, upe=font.units_per_EM, nearest=True): + """Convert font coordinates to PDF glyph coordinates.""" + value = length / upe * 1000 + if nearest: + return round(value) + # Best(?) to round away from zero for bounding boxes and the like. + if value < 0: + return math.floor(value) + else: + return math.ceil(value) + + def embedTTFType3(font, characters, descriptor): + """The Type 3-specific part of embedding a Truetype font""" + widthsObject = self.reserveObject('font widths') + fontdescObject = self.reserveObject('font descriptor') + fontdictObject = self.reserveObject('font dictionary') + charprocsObject = self.reserveObject('character procs') + differencesArray = [] + firstchar, lastchar = 0, 255 + bbox = [cvt(x, nearest=False) for x in font.bbox] + + fontdict = { + 'Type': Name('Font'), + 'BaseFont': ps_name, + 'FirstChar': firstchar, + 'LastChar': lastchar, + 'FontDescriptor': fontdescObject, + 'Subtype': Name('Type3'), + 'Name': descriptor['FontName'], + 'FontBBox': bbox, + 'FontMatrix': [.001, 0, 0, .001, 0, 0], + 'CharProcs': charprocsObject, + 'Encoding': { + 'Type': Name('Encoding'), + 'Differences': differencesArray}, + 'Widths': widthsObject + } + + from encodings import cp1252 + + # Make the "Widths" array + def get_char_width(charcode): + s = ord(cp1252.decoding_table[charcode]) + width = font.load_char( + s, flags=LoadFlags.NO_SCALE | LoadFlags.NO_HINTING).horiAdvance + return cvt(width) + with warnings.catch_warnings(): + # Ignore 'Required glyph missing from current font' warning + # from ft2font: here we're just building the widths table, but + # the missing glyphs may not even be used in the actual string. + warnings.filterwarnings("ignore") + widths = [get_char_width(charcode) + for charcode in range(firstchar, lastchar+1)] + descriptor['MaxWidth'] = max(widths) + + # Make the "Differences" array, sort the ccodes < 255 from + # the multi-byte ccodes, and build the whole set of glyph ids + # that we need from this font. + glyph_ids = [] + differences = [] + multi_byte_chars = set() + for c in characters: + ccode = c + gind = font.get_char_index(ccode) + glyph_ids.append(gind) + glyph_name = font.get_glyph_name(gind) + if ccode <= 255: + differences.append((ccode, glyph_name)) + else: + multi_byte_chars.add(glyph_name) + differences.sort() + + last_c = -2 + for c, name in differences: + if c != last_c + 1: + differencesArray.append(c) + differencesArray.append(Name(name)) + last_c = c + + # Make the charprocs array. + rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) + charprocs = {} + for charname in sorted(rawcharprocs): + stream = rawcharprocs[charname] + charprocDict = {} + # The 2-byte characters are used as XObjects, so they + # need extra info in their dictionary + if charname in multi_byte_chars: + charprocDict = {'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'BBox': bbox} + # Each glyph includes bounding box information, + # but xpdf and ghostscript can't handle it in a + # Form XObject (they segfault!!!), so we remove it + # from the stream here. It's not needed anyway, + # since the Form XObject includes it in its BBox + # value. + stream = stream[stream.find(b"d1") + 2:] + charprocObject = self.reserveObject('charProc') + self.outputStream(charprocObject, stream, extra=charprocDict) + + # Send the glyphs with ccode > 255 to the XObject dictionary, + # and the others to the font itself + if charname in multi_byte_chars: + name = self._get_xobject_glyph_name(filename, charname) + self.multi_byte_charprocs[name] = charprocObject + else: + charprocs[charname] = charprocObject + + # Write everything out + self.writeObject(fontdictObject, fontdict) + self.writeObject(fontdescObject, descriptor) + self.writeObject(widthsObject, widths) + self.writeObject(charprocsObject, charprocs) + + return fontdictObject + + def embedTTFType42(font, characters, descriptor): + """The Type 42-specific part of embedding a Truetype font""" + fontdescObject = self.reserveObject('font descriptor') + cidFontDictObject = self.reserveObject('CID font dictionary') + type0FontDictObject = self.reserveObject('Type 0 font dictionary') + cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') + fontfileObject = self.reserveObject('font file stream') + wObject = self.reserveObject('Type 0 widths') + toUnicodeMapObject = self.reserveObject('ToUnicode map') + + subset_str = "".join(chr(c) for c in characters) + _log.debug("SUBSET %s characters: %s", filename, subset_str) + with _backend_pdf_ps.get_glyphs_subset(filename, subset_str) as subset: + fontdata = _backend_pdf_ps.font_as_file(subset) + _log.debug( + "SUBSET %s %d -> %d", filename, + os.stat(filename).st_size, fontdata.getbuffer().nbytes + ) + + # We need this ref for XObjects + full_font = font + + # reload the font object from the subset + # (all the necessary data could probably be obtained directly + # using fontLib.ttLib) + font = FT2Font(fontdata) + + cidFontDict = { + 'Type': Name('Font'), + 'Subtype': Name('CIDFontType2'), + 'BaseFont': ps_name, + 'CIDSystemInfo': { + 'Registry': 'Adobe', + 'Ordering': 'Identity', + 'Supplement': 0}, + 'FontDescriptor': fontdescObject, + 'W': wObject, + 'CIDToGIDMap': cidToGidMapObject + } + + type0FontDict = { + 'Type': Name('Font'), + 'Subtype': Name('Type0'), + 'BaseFont': ps_name, + 'Encoding': Name('Identity-H'), + 'DescendantFonts': [cidFontDictObject], + 'ToUnicode': toUnicodeMapObject + } + + # Make fontfile stream + descriptor['FontFile2'] = fontfileObject + self.outputStream( + fontfileObject, fontdata.getvalue(), + extra={'Length1': fontdata.getbuffer().nbytes}) + + # Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap + # at the same time + cid_to_gid_map = ['\0'] * 65536 + widths = [] + max_ccode = 0 + for c in characters: + ccode = c + gind = font.get_char_index(ccode) + glyph = font.load_char(ccode, + flags=LoadFlags.NO_SCALE | LoadFlags.NO_HINTING) + widths.append((ccode, cvt(glyph.horiAdvance))) + if ccode < 65536: + cid_to_gid_map[ccode] = chr(gind) + max_ccode = max(ccode, max_ccode) + widths.sort() + cid_to_gid_map = cid_to_gid_map[:max_ccode + 1] + + last_ccode = -2 + w = [] + max_width = 0 + unicode_groups = [] + for ccode, width in widths: + if ccode != last_ccode + 1: + w.append(ccode) + w.append([width]) + unicode_groups.append([ccode, ccode]) + else: + w[-1].append(width) + unicode_groups[-1][1] = ccode + max_width = max(max_width, width) + last_ccode = ccode + + unicode_bfrange = [] + for start, end in unicode_groups: + # Ensure the CID map contains only chars from BMP + if start > 65535: + continue + end = min(65535, end) + + unicode_bfrange.append( + b"<%04x> <%04x> [%s]" % + (start, end, + b" ".join(b"<%04x>" % x for x in range(start, end+1)))) + unicode_cmap = (self._identityToUnicodeCMap % + (len(unicode_groups), b"\n".join(unicode_bfrange))) + + # Add XObjects for unsupported chars + glyph_ids = [] + for ccode in characters: + if not _font_supports_glyph(fonttype, ccode): + gind = full_font.get_char_index(ccode) + glyph_ids.append(gind) + + bbox = [cvt(x, nearest=False) for x in full_font.bbox] + rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) + for charname in sorted(rawcharprocs): + stream = rawcharprocs[charname] + charprocDict = {'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'BBox': bbox} + # Each glyph includes bounding box information, + # but xpdf and ghostscript can't handle it in a + # Form XObject (they segfault!!!), so we remove it + # from the stream here. It's not needed anyway, + # since the Form XObject includes it in its BBox + # value. + stream = stream[stream.find(b"d1") + 2:] + charprocObject = self.reserveObject('charProc') + self.outputStream(charprocObject, stream, extra=charprocDict) + + name = self._get_xobject_glyph_name(filename, charname) + self.multi_byte_charprocs[name] = charprocObject + + # CIDToGIDMap stream + cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be") + self.outputStream(cidToGidMapObject, cid_to_gid_map) + + # ToUnicode CMap + self.outputStream(toUnicodeMapObject, unicode_cmap) + + descriptor['MaxWidth'] = max_width + + # Write everything out + self.writeObject(cidFontDictObject, cidFontDict) + self.writeObject(type0FontDictObject, type0FontDict) + self.writeObject(fontdescObject, descriptor) + self.writeObject(wObject, w) + + return type0FontDictObject + + # Beginning of main embedTTF function... + + ps_name = self._get_subsetted_psname( + font.postscript_name, + font.get_charmap() + ) + ps_name = ps_name.encode('ascii', 'replace') + ps_name = Name(ps_name) + pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0} + post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)} + ff = font.face_flags + sf = font.style_flags + + flags = 0 + symbolic = False # ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10') + if FaceFlags.FIXED_WIDTH in ff: + flags |= 1 << 0 + if 0: # TODO: serif + flags |= 1 << 1 + if symbolic: + flags |= 1 << 2 + else: + flags |= 1 << 5 + if StyleFlags.ITALIC in sf: + flags |= 1 << 6 + if 0: # TODO: all caps + flags |= 1 << 16 + if 0: # TODO: small caps + flags |= 1 << 17 + if 0: # TODO: force bold + flags |= 1 << 18 + + descriptor = { + 'Type': Name('FontDescriptor'), + 'FontName': ps_name, + 'Flags': flags, + 'FontBBox': [cvt(x, nearest=False) for x in font.bbox], + 'Ascent': cvt(font.ascender, nearest=False), + 'Descent': cvt(font.descender, nearest=False), + 'CapHeight': cvt(pclt['capHeight'], nearest=False), + 'XHeight': cvt(pclt['xHeight']), + 'ItalicAngle': post['italicAngle'][1], # ??? + 'StemV': 0 # ??? + } + + if fonttype == 3: + return embedTTFType3(font, characters, descriptor) + elif fonttype == 42: + return embedTTFType42(font, characters, descriptor) + + def alphaState(self, alpha): + """Return name of an ExtGState that sets alpha to the given value.""" + + state = self.alphaStates.get(alpha, None) + if state is not None: + return state[0] + + name = next(self._alpha_state_seq) + self.alphaStates[alpha] = \ + (name, {'Type': Name('ExtGState'), + 'CA': alpha[0], 'ca': alpha[1]}) + return name + + def _soft_mask_state(self, smask): + """ + Return an ExtGState that sets the soft mask to the given shading. + + Parameters + ---------- + smask : Reference + Reference to a shading in DeviceGray color space, whose luminosity + is to be used as the alpha channel. + + Returns + ------- + Name + """ + + state = self._soft_mask_states.get(smask, None) + if state is not None: + return state[0] + + name = next(self._soft_mask_seq) + groupOb = self.reserveObject('transparency group for soft mask') + self._soft_mask_states[smask] = ( + name, + { + 'Type': Name('ExtGState'), + 'AIS': False, + 'SMask': { + 'Type': Name('Mask'), + 'S': Name('Luminosity'), + 'BC': [1], + 'G': groupOb + } + } + ) + self._soft_mask_groups.append(( + groupOb, + { + 'Type': Name('XObject'), + 'Subtype': Name('Form'), + 'FormType': 1, + 'Group': { + 'S': Name('Transparency'), + 'CS': Name('DeviceGray') + }, + 'Matrix': [1, 0, 0, 1, 0, 0], + 'Resources': {'Shading': {'S': smask}}, + 'BBox': [0, 0, 1, 1] + }, + [Name('S'), Op.shading] + )) + return name + + def writeExtGSTates(self): + self.writeObject( + self._extGStateObject, + dict([ + *self.alphaStates.values(), + *self._soft_mask_states.values() + ]) + ) + + def _write_soft_mask_groups(self): + for ob, attributes, content in self._soft_mask_groups: + self.beginStream(ob.id, None, attributes) + self.output(*content) + self.endStream() + + def hatchPattern(self, hatch_style): + # The colors may come in as numpy arrays, which aren't hashable + edge, face, hatch, lw = hatch_style + if edge is not None: + edge = tuple(edge) + if face is not None: + face = tuple(face) + hatch_style = (edge, face, hatch, lw) + + pattern = self._hatch_patterns.get(hatch_style, None) + if pattern is not None: + return pattern + + name = next(self._hatch_pattern_seq) + self._hatch_patterns[hatch_style] = name + return name + + hatchPatterns = _api.deprecated("3.10")(property(lambda self: { + k: (e, f, h) for k, (e, f, h, l) in self._hatch_patterns.items() + })) + + def writeHatches(self): + hatchDict = dict() + sidelen = 72.0 + for hatch_style, name in self._hatch_patterns.items(): + ob = self.reserveObject('hatch pattern') + hatchDict[name] = ob + res = {'Procsets': + [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]} + self.beginStream( + ob.id, None, + {'Type': Name('Pattern'), + 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, + 'BBox': [0, 0, sidelen, sidelen], + 'XStep': sidelen, 'YStep': sidelen, + 'Resources': res, + # Change origin to match Agg at top-left. + 'Matrix': [1, 0, 0, 1, 0, self.height * 72]}) + + stroke_rgb, fill_rgb, hatch, lw = hatch_style + self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2], + Op.setrgb_stroke) + if fill_rgb is not None: + self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2], + Op.setrgb_nonstroke, + 0, 0, sidelen, sidelen, Op.rectangle, + Op.fill) + + self.output(lw, Op.setlinewidth) + + self.output(*self.pathOperations( + Path.hatch(hatch), + Affine2D().scale(sidelen), + simplify=False)) + self.output(Op.fill_stroke) + + self.endStream() + self.writeObject(self.hatchObject, hatchDict) + + def addGouraudTriangles(self, points, colors): + """ + Add a Gouraud triangle shading. + + Parameters + ---------- + points : np.ndarray + Triangle vertices, shape (n, 3, 2) + where n = number of triangles, 3 = vertices, 2 = x, y. + colors : np.ndarray + Vertex colors, shape (n, 3, 1) or (n, 3, 4) + as with points, but last dimension is either (gray,) + or (r, g, b, alpha). + + Returns + ------- + Name, Reference + """ + name = Name('GT%d' % len(self.gouraudTriangles)) + ob = self.reserveObject(f'Gouraud triangle {name}') + self.gouraudTriangles.append((name, ob, points, colors)) + return name, ob + + def writeGouraudTriangles(self): + gouraudDict = dict() + for name, ob, points, colors in self.gouraudTriangles: + gouraudDict[name] = ob + shape = points.shape + flat_points = points.reshape((shape[0] * shape[1], 2)) + colordim = colors.shape[2] + assert colordim in (1, 4) + flat_colors = colors.reshape((shape[0] * shape[1], colordim)) + if colordim == 4: + # strip the alpha channel + colordim = 3 + points_min = np.min(flat_points, axis=0) - (1 << 8) + points_max = np.max(flat_points, axis=0) + (1 << 8) + factor = 0xffffffff / (points_max - points_min) + + self.beginStream( + ob.id, None, + {'ShadingType': 4, + 'BitsPerCoordinate': 32, + 'BitsPerComponent': 8, + 'BitsPerFlag': 8, + 'ColorSpace': Name( + 'DeviceRGB' if colordim == 3 else 'DeviceGray' + ), + 'AntiAlias': False, + 'Decode': ([points_min[0], points_max[0], + points_min[1], points_max[1]] + + [0, 1] * colordim), + }) + + streamarr = np.empty( + (shape[0] * shape[1],), + dtype=[('flags', 'u1'), + ('points', '>u4', (2,)), + ('colors', 'u1', (colordim,))]) + streamarr['flags'] = 0 + streamarr['points'] = (flat_points - points_min) * factor + streamarr['colors'] = flat_colors[:, :colordim] * 255.0 + + self.write(streamarr.tobytes()) + self.endStream() + self.writeObject(self.gouraudObject, gouraudDict) + + def imageObject(self, image): + """Return name of an image XObject representing the given image.""" + + entry = self._images.get(id(image), None) + if entry is not None: + return entry[1] + + name = next(self._image_seq) + ob = self.reserveObject(f'image {name}') + self._images[id(image)] = (image, name, ob) + return name + + def _unpack(self, im): + """ + Unpack image array *im* into ``(data, alpha)``, which have shape + ``(height, width, 3)`` (RGB) or ``(height, width, 1)`` (grayscale or + alpha), except that alpha is None if the image is fully opaque. + """ + im = im[::-1] + if im.ndim == 2: + return im, None + else: + rgb = im[:, :, :3] + rgb = np.array(rgb, order='C') + # PDF needs a separate alpha image + if im.shape[2] == 4: + alpha = im[:, :, 3][..., None] + if np.all(alpha == 255): + alpha = None + else: + alpha = np.array(alpha, order='C') + else: + alpha = None + return rgb, alpha + + def _writePng(self, img): + """ + Write the image *img* into the pdf file using png + predictors with Flate compression. + """ + buffer = BytesIO() + img.save(buffer, format="png") + buffer.seek(8) + png_data = b'' + bit_depth = palette = None + while True: + length, type = struct.unpack(b'!L4s', buffer.read(8)) + if type in [b'IHDR', b'PLTE', b'IDAT']: + data = buffer.read(length) + if len(data) != length: + raise RuntimeError("truncated data") + if type == b'IHDR': + bit_depth = int(data[8]) + elif type == b'PLTE': + palette = data + elif type == b'IDAT': + png_data += data + elif type == b'IEND': + break + else: + buffer.seek(length, 1) + buffer.seek(4, 1) # skip CRC + return png_data, bit_depth, palette + + def _writeImg(self, data, id, smask=None): + """ + Write the image *data*, of shape ``(height, width, 1)`` (grayscale) or + ``(height, width, 3)`` (RGB), as pdf object *id* and with the soft mask + (alpha channel) *smask*, which should be either None or a ``(height, + width, 1)`` array. + """ + height, width, color_channels = data.shape + obj = {'Type': Name('XObject'), + 'Subtype': Name('Image'), + 'Width': width, + 'Height': height, + 'ColorSpace': Name({1: 'DeviceGray', 3: 'DeviceRGB'}[color_channels]), + 'BitsPerComponent': 8} + if smask: + obj['SMask'] = smask + if mpl.rcParams['pdf.compression']: + if data.shape[-1] == 1: + data = data.squeeze(axis=-1) + png = {'Predictor': 10, 'Colors': color_channels, 'Columns': width} + img = Image.fromarray(data) + img_colors = img.getcolors(maxcolors=256) + if color_channels == 3 and img_colors is not None: + # Convert to indexed color if there are 256 colors or fewer. This can + # significantly reduce the file size. + num_colors = len(img_colors) + palette = np.array([comp for _, color in img_colors for comp in color], + dtype=np.uint8) + palette24 = ((palette[0::3].astype(np.uint32) << 16) | + (palette[1::3].astype(np.uint32) << 8) | + palette[2::3]) + rgb24 = ((data[:, :, 0].astype(np.uint32) << 16) | + (data[:, :, 1].astype(np.uint32) << 8) | + data[:, :, 2]) + indices = np.argsort(palette24).astype(np.uint8) + rgb8 = indices[np.searchsorted(palette24, rgb24, sorter=indices)] + img = Image.fromarray(rgb8, mode='P') + img.putpalette(palette) + png_data, bit_depth, palette = self._writePng(img) + if bit_depth is None or palette is None: + raise RuntimeError("invalid PNG header") + palette = palette[:num_colors * 3] # Trim padding; remove for Pillow>=9 + obj['ColorSpace'] = [Name('Indexed'), Name('DeviceRGB'), + num_colors - 1, palette] + obj['BitsPerComponent'] = bit_depth + png['Colors'] = 1 + png['BitsPerComponent'] = bit_depth + else: + png_data, _, _ = self._writePng(img) + else: + png = None + self.beginStream( + id, + self.reserveObject('length of image stream'), + obj, + png=png + ) + if png: + self.currentstream.write(png_data) + else: + self.currentstream.write(data.tobytes()) + self.endStream() + + def writeImages(self): + for img, name, ob in self._images.values(): + data, adata = self._unpack(img) + if adata is not None: + smaskObject = self.reserveObject("smask") + self._writeImg(adata, smaskObject.id) + else: + smaskObject = None + self._writeImg(data, ob.id, smaskObject) + + def markerObject(self, path, trans, fill, stroke, lw, joinstyle, + capstyle): + """Return name of a marker XObject representing the given path.""" + # self.markers used by markerObject, writeMarkers, close: + # mapping from (path operations, fill?, stroke?) to + # [name, object reference, bounding box, linewidth] + # This enables different draw_markers calls to share the XObject + # if the gc is sufficiently similar: colors etc can vary, but + # the choices of whether to fill and whether to stroke cannot. + # We need a bounding box enclosing all of the XObject path, + # but since line width may vary, we store the maximum of all + # occurring line widths in self.markers. + # close() is somewhat tightly coupled in that it expects the + # first two components of each value in self.markers to be the + # name and object reference. + pathops = self.pathOperations(path, trans, simplify=False) + key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle) + result = self.markers.get(key) + if result is None: + name = Name('M%d' % len(self.markers)) + ob = self.reserveObject('marker %d' % len(self.markers)) + bbox = path.get_extents(trans) + self.markers[key] = [name, ob, bbox, lw] + else: + if result[-1] < lw: + result[-1] = lw + name = result[0] + return name + + def writeMarkers(self): + for ((pathops, fill, stroke, joinstyle, capstyle), + (name, ob, bbox, lw)) in self.markers.items(): + # bbox wraps the exact limits of the control points, so half a line + # will appear outside it. If the join style is miter and the line + # is not parallel to the edge, then the line will extend even + # further. From the PDF specification, Section 8.4.3.5, the miter + # limit is miterLength / lineWidth and from Table 52, the default + # is 10. With half the miter length outside, that works out to the + # following padding: + bbox = bbox.padded(lw * 5) + self.beginStream( + ob.id, None, + {'Type': Name('XObject'), 'Subtype': Name('Form'), + 'BBox': list(bbox.extents)}) + self.output(GraphicsContextPdf.joinstyles[joinstyle], + Op.setlinejoin) + self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) + self.output(*pathops) + self.output(Op.paint_path(fill, stroke)) + self.endStream() + + def pathCollectionObject(self, gc, path, trans, padding, filled, stroked): + name = Name('P%d' % len(self.paths)) + ob = self.reserveObject('path %d' % len(self.paths)) + self.paths.append( + (name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(), + padding, filled, stroked)) + return name + + def writePathCollectionTemplates(self): + for (name, path, trans, ob, joinstyle, capstyle, padding, filled, + stroked) in self.paths: + pathops = self.pathOperations(path, trans, simplify=False) + bbox = path.get_extents(trans) + if not np.all(np.isfinite(bbox.extents)): + extents = [0, 0, 0, 0] + else: + bbox = bbox.padded(padding) + extents = list(bbox.extents) + self.beginStream( + ob.id, None, + {'Type': Name('XObject'), 'Subtype': Name('Form'), + 'BBox': extents}) + self.output(GraphicsContextPdf.joinstyles[joinstyle], + Op.setlinejoin) + self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) + self.output(*pathops) + self.output(Op.paint_path(filled, stroked)) + self.endStream() + + @staticmethod + def pathOperations(path, transform, clip=None, simplify=None, sketch=None): + return [Verbatim(_path.convert_to_string( + path, transform, clip, simplify, sketch, + 6, + [Op.moveto.value, Op.lineto.value, b'', Op.curveto.value, + Op.closepath.value], + True))] + + def writePath(self, path, transform, clip=False, sketch=None): + if clip: + clip = (0.0, 0.0, self.width * 72, self.height * 72) + simplify = path.should_simplify + else: + clip = None + simplify = False + cmds = self.pathOperations(path, transform, clip, simplify=simplify, + sketch=sketch) + self.output(*cmds) + + def reserveObject(self, name=''): + """ + Reserve an ID for an indirect object. + + The name is used for debugging in case we forget to print out + the object with writeObject. + """ + id = next(self._object_seq) + self.xrefTable.append([None, 0, name]) + return Reference(id) + + def recordXref(self, id): + self.xrefTable[id][0] = self.fh.tell() - self.tell_base + + def writeObject(self, object, contents): + self.recordXref(object.id) + object.write(contents, self) + + def writeXref(self): + """Write out the xref table.""" + self.startxref = self.fh.tell() - self.tell_base + self.write(b"xref\n0 %d\n" % len(self.xrefTable)) + for i, (offset, generation, name) in enumerate(self.xrefTable): + if offset is None: + raise AssertionError( + 'No offset for object %d (%s)' % (i, name)) + else: + key = b"f" if name == 'the zero object' else b"n" + text = b"%010d %05d %b \n" % (offset, generation, key) + self.write(text) + + def writeInfoDict(self): + """Write out the info dictionary, checking it for good form""" + + self.infoObject = self.reserveObject('info') + self.writeObject(self.infoObject, self.infoDict) + + def writeTrailer(self): + """Write out the PDF trailer.""" + + self.write(b"trailer\n") + self.write(pdfRepr( + {'Size': len(self.xrefTable), + 'Root': self.rootObject, + 'Info': self.infoObject})) + # Could add 'ID' + self.write(b"\nstartxref\n%d\n%%%%EOF\n" % self.startxref) + + +class RendererPdf(_backend_pdf_ps.RendererPDFPSBase): + + _afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts") + _use_afm_rc_name = "pdf.use14corefonts" + + def __init__(self, file, image_dpi, height, width): + super().__init__(width, height) + self.file = file + self.gc = self.new_gc() + self.image_dpi = image_dpi + + def finalize(self): + self.file.output(*self.gc.finalize()) + + def check_gc(self, gc, fillcolor=None): + orig_fill = getattr(gc, '_fillcolor', (0., 0., 0.)) + gc._fillcolor = fillcolor + + orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0)) + + if gc.get_rgb() is None: + # It should not matter what color here since linewidth should be + # 0 unless affected by global settings in rcParams, hence setting + # zero alpha just in case. + gc.set_foreground((0, 0, 0, 0), isRGBA=True) + + if gc._forced_alpha: + gc._effective_alphas = (gc._alpha, gc._alpha) + elif fillcolor is None or len(fillcolor) < 4: + gc._effective_alphas = (gc._rgb[3], 1.0) + else: + gc._effective_alphas = (gc._rgb[3], fillcolor[3]) + + delta = self.gc.delta(gc) + if delta: + self.file.output(*delta) + + # Restore gc to avoid unwanted side effects + gc._fillcolor = orig_fill + gc._effective_alphas = orig_alphas + + def get_image_magnification(self): + return self.image_dpi/72.0 + + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + if w == 0 or h == 0: + return + + if transform is None: + # If there's no transform, alpha has already been applied + gc.set_alpha(1.0) + + self.check_gc(gc) + + w = 72.0 * w / self.image_dpi + h = 72.0 * h / self.image_dpi + + imob = self.file.imageObject(im) + + if transform is None: + self.file.output(Op.gsave, + w, 0, 0, h, x, y, Op.concat_matrix, + imob, Op.use_xobject, Op.grestore) + else: + tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() + + self.file.output(Op.gsave, + 1, 0, 0, 1, x, y, Op.concat_matrix, + tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix, + imob, Op.use_xobject, Op.grestore) + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + self.check_gc(gc, rgbFace) + self.file.writePath( + path, transform, + rgbFace is None and gc.get_hatch_path() is None, + gc.get_sketch_params()) + self.file.output(self.gc.paint()) + + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # We can only reuse the objects if the presence of fill and + # stroke (and the amount of alpha for each) is the same for + # all of them + can_do_optimization = True + facecolors = np.asarray(facecolors) + edgecolors = np.asarray(edgecolors) + + if not len(facecolors): + filled = False + can_do_optimization = not gc.get_hatch() + else: + if np.all(facecolors[:, 3] == facecolors[0, 3]): + filled = facecolors[0, 3] != 0.0 + else: + can_do_optimization = False + + if not len(edgecolors): + stroked = False + else: + if np.all(np.asarray(linewidths) == 0.0): + stroked = False + elif np.all(edgecolors[:, 3] == edgecolors[0, 3]): + stroked = edgecolors[0, 3] != 0.0 + else: + can_do_optimization = False + + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is len_path * uses_per_path + # cost of XObject is len_path + 5 for the definition, + # uses_per_path for the uses + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + uses_per_path + 5 < len_path * uses_per_path + + if (not can_do_optimization) or (not should_do_optimization): + return RendererBase.draw_path_collection( + self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + padding = np.max(linewidths) + path_codes = [] + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + name = self.file.pathCollectionObject( + gc, path, transform, padding, filled, stroked) + path_codes.append(name) + + output = self.file.output + output(*self.gc.push()) + lastx, lasty = 0, 0 + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + + self.check_gc(gc0, rgbFace) + dx, dy = xo - lastx, yo - lasty + output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id, + Op.use_xobject) + lastx, lasty = xo, yo + output(*self.gc.pop()) + + def draw_markers(self, gc, marker_path, marker_trans, path, trans, + rgbFace=None): + # docstring inherited + + # Same logic as in draw_path_collection + len_marker_path = len(marker_path) + uses = len(path) + if len_marker_path * uses < len_marker_path + uses + 5: + RendererBase.draw_markers(self, gc, marker_path, marker_trans, + path, trans, rgbFace) + return + + self.check_gc(gc, rgbFace) + fill = gc.fill(rgbFace) + stroke = gc.stroke() + + output = self.file.output + marker = self.file.markerObject( + marker_path, marker_trans, fill, stroke, self.gc._linewidth, + gc.get_joinstyle(), gc.get_capstyle()) + + output(Op.gsave) + lastx, lasty = 0, 0 + for vertices, code in path.iter_segments( + trans, + clip=(0, 0, self.file.width*72, self.file.height*72), + simplify=False): + if len(vertices): + x, y = vertices[-2:] + if not (0 <= x <= self.file.width * 72 + and 0 <= y <= self.file.height * 72): + continue + dx, dy = x - lastx, y - lasty + output(1, 0, 0, 1, dx, dy, Op.concat_matrix, + marker, Op.use_xobject) + lastx, lasty = x, y + output(Op.grestore) + + def draw_gouraud_triangles(self, gc, points, colors, trans): + assert len(points) == len(colors) + if len(points) == 0: + return + assert points.ndim == 3 + assert points.shape[1] == 3 + assert points.shape[2] == 2 + assert colors.ndim == 3 + assert colors.shape[1] == 3 + assert colors.shape[2] in (1, 4) + + shape = points.shape + points = points.reshape((shape[0] * shape[1], 2)) + tpoints = trans.transform(points) + tpoints = tpoints.reshape(shape) + name, _ = self.file.addGouraudTriangles(tpoints, colors) + output = self.file.output + + if colors.shape[2] == 1: + # grayscale + gc.set_alpha(1.0) + self.check_gc(gc) + output(name, Op.shading) + return + + alpha = colors[0, 0, 3] + if np.allclose(alpha, colors[:, :, 3]): + # single alpha value + gc.set_alpha(alpha) + self.check_gc(gc) + output(name, Op.shading) + else: + # varying alpha: use a soft mask + alpha = colors[:, :, 3][:, :, None] + _, smask_ob = self.file.addGouraudTriangles(tpoints, alpha) + gstate = self.file._soft_mask_state(smask_ob) + output(Op.gsave, gstate, Op.setgstate, + name, Op.shading, + Op.grestore) + + def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0): + if angle == oldangle == 0: + self.file.output(x - oldx, y - oldy, Op.textpos) + else: + angle = math.radians(angle) + self.file.output(math.cos(angle), math.sin(angle), + -math.sin(angle), math.cos(angle), + x, y, Op.textmatrix) + self.file.output(0, 0, Op.textpos) + + def draw_mathtext(self, gc, x, y, s, prop, angle): + # TODO: fix positioning and encoding + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + + if gc.get_url() is not None: + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, width, height, angle)) + + fonttype = mpl.rcParams['pdf.fonttype'] + + # Set up a global transformation matrix for the whole math expression + a = math.radians(angle) + self.file.output(Op.gsave) + self.file.output(math.cos(a), math.sin(a), + -math.sin(a), math.cos(a), + x, y, Op.concat_matrix) + + self.check_gc(gc, gc._rgb) + prev_font = None, None + oldx, oldy = 0, 0 + unsupported_chars = [] + + self.file.output(Op.begin_text) + for font, fontsize, num, ox, oy in glyphs: + self.file._character_tracker.track_glyph(font, num) + fontname = font.fname + if not _font_supports_glyph(fonttype, num): + # Unsupported chars (i.e. multibyte in Type 3 or beyond BMP in + # Type 42) must be emitted separately (below). + unsupported_chars.append((font, fontsize, ox, oy, num)) + else: + self._setup_textpos(ox, oy, 0, oldx, oldy) + oldx, oldy = ox, oy + if (fontname, fontsize) != prev_font: + self.file.output(self.file.fontName(fontname), fontsize, + Op.selectfont) + prev_font = fontname, fontsize + self.file.output(self.encode_string(chr(num), fonttype), + Op.show) + self.file.output(Op.end_text) + + for font, fontsize, ox, oy, num in unsupported_chars: + self._draw_xobject_glyph( + font, fontsize, font.get_char_index(num), ox, oy) + + # Draw any horizontal lines in the math layout + for ox, oy, width, height in rects: + self.file.output(Op.gsave, ox, oy, width, height, + Op.rectangle, Op.fill, Op.grestore) + + # Pop off the global transformation + self.file.output(Op.grestore) + + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + texmanager = self.get_texmanager() + fontsize = prop.get_size_in_points() + dvifile = texmanager.make_dvi(s, fontsize) + with dviread.Dvi(dvifile, 72) as dvi: + page, = dvi + + if gc.get_url() is not None: + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, page.width, page.height, angle)) + + # Gather font information and do some setup for combining + # characters into strings. The variable seq will contain a + # sequence of font and text entries. A font entry is a list + # ['font', name, size] where name is a Name object for the + # font. A text entry is ['text', x, y, glyphs, x+w] where x + # and y are the starting coordinates, w is the width, and + # glyphs is a list; in this phase it will always contain just + # one single-character string, but later it may have longer + # strings interspersed with kern amounts. + oldfont, seq = None, [] + for x1, y1, dvifont, glyph, width in page.text: + if dvifont != oldfont: + pdfname = self.file.dviFontName(dvifont) + seq += [['font', pdfname, dvifont.size]] + oldfont = dvifont + seq += [['text', x1, y1, [bytes([glyph])], x1+width]] + + # Find consecutive text strings with constant y coordinate and + # combine into a sequence of strings and kerns, or just one + # string (if any kerns would be less than 0.1 points). + i, curx, fontsize = 0, 0, None + while i < len(seq)-1: + elt, nxt = seq[i:i+2] + if elt[0] == 'font': + fontsize = elt[2] + elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]: + offset = elt[4] - nxt[1] + if abs(offset) < 0.1: + elt[3][-1] += nxt[3][0] + elt[4] += nxt[4]-nxt[1] + else: + elt[3] += [offset*1000.0/fontsize, nxt[3][0]] + elt[4] = nxt[4] + del seq[i+1] + continue + i += 1 + + # Create a transform to map the dvi contents to the canvas. + mytrans = Affine2D().rotate_deg(angle).translate(x, y) + + # Output the text. + self.check_gc(gc, gc._rgb) + self.file.output(Op.begin_text) + curx, cury, oldx, oldy = 0, 0, 0, 0 + for elt in seq: + if elt[0] == 'font': + self.file.output(elt[1], elt[2], Op.selectfont) + elif elt[0] == 'text': + curx, cury = mytrans.transform((elt[1], elt[2])) + self._setup_textpos(curx, cury, angle, oldx, oldy) + oldx, oldy = curx, cury + if len(elt[3]) == 1: + self.file.output(elt[3][0], Op.show) + else: + self.file.output(elt[3], Op.showkern) + else: + assert False + self.file.output(Op.end_text) + + # Then output the boxes (e.g., variable-length lines of square + # roots). + boxgc = self.new_gc() + boxgc.copy_properties(gc) + boxgc.set_linewidth(0) + pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + for x1, y1, h, w in page.boxes: + path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h], + [0, 0]], pathops) + self.draw_path(boxgc, path, mytrans, gc._rgb) + + def encode_string(self, s, fonttype): + if fonttype in (1, 3): + return s.encode('cp1252', 'replace') + return s.encode('utf-16be', 'replace') + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + # TODO: combine consecutive texts into one BT/ET delimited section + + self.check_gc(gc, gc._rgb) + if ismath: + return self.draw_mathtext(gc, x, y, s, prop, angle) + + fontsize = prop.get_size_in_points() + + if mpl.rcParams['pdf.use14corefonts']: + font = self._get_font_afm(prop) + fonttype = 1 + else: + font = self._get_font_ttf(prop) + self.file._character_tracker.track(font, s) + fonttype = mpl.rcParams['pdf.fonttype'] + + if gc.get_url() is not None: + font.set_text(s) + width, height = font.get_width_height() + self.file._annotations[-1][1].append(_get_link_annotation( + gc, x, y, width / 64, height / 64, angle)) + + # If fonttype is neither 3 nor 42, emit the whole string at once + # without manual kerning. + if fonttype not in [3, 42]: + self.file.output(Op.begin_text, + self.file.fontName(prop), fontsize, Op.selectfont) + self._setup_textpos(x, y, angle) + self.file.output(self.encode_string(s, fonttype), + Op.show, Op.end_text) + + # A sequence of characters is broken into multiple chunks. The chunking + # serves two purposes: + # - For Type 3 fonts, there is no way to access multibyte characters, + # as they cannot have a CIDMap. Therefore, in this case we break + # the string into chunks, where each chunk contains either a string + # of consecutive 1-byte characters or a single multibyte character. + # - A sequence of 1-byte characters is split into chunks to allow for + # kerning adjustments between consecutive chunks. + # + # Each chunk is emitted with a separate command: 1-byte characters use + # the regular text show command (TJ) with appropriate kerning between + # chunks, whereas multibyte characters use the XObject command (Do). + else: + # List of (ft_object, start_x, [prev_kern, char, char, ...]), + # w/o zero kerns. + singlebyte_chunks = [] + # List of (ft_object, start_x, glyph_index). + multibyte_glyphs = [] + prev_was_multibyte = True + prev_font = font + for item in _text_helpers.layout(s, font, kern_mode=Kerning.UNFITTED): + if _font_supports_glyph(fonttype, ord(item.char)): + if prev_was_multibyte or item.ft_object != prev_font: + singlebyte_chunks.append((item.ft_object, item.x, [])) + prev_font = item.ft_object + if item.prev_kern: + singlebyte_chunks[-1][2].append(item.prev_kern) + singlebyte_chunks[-1][2].append(item.char) + prev_was_multibyte = False + else: + multibyte_glyphs.append((item.ft_object, item.x, item.glyph_idx)) + prev_was_multibyte = True + # Do the rotation and global translation as a single matrix + # concatenation up front + self.file.output(Op.gsave) + a = math.radians(angle) + self.file.output(math.cos(a), math.sin(a), + -math.sin(a), math.cos(a), + x, y, Op.concat_matrix) + # Emit all the 1-byte characters in a BT/ET group. + + self.file.output(Op.begin_text) + prev_start_x = 0 + for ft_object, start_x, kerns_or_chars in singlebyte_chunks: + ft_name = self.file.fontName(ft_object.fname) + self.file.output(ft_name, fontsize, Op.selectfont) + self._setup_textpos(start_x, 0, 0, prev_start_x, 0, 0) + self.file.output( + # See pdf spec "Text space details" for the 1000/fontsize + # (aka. 1000/T_fs) factor. + [-1000 * next(group) / fontsize if tp == float # a kern + else self.encode_string("".join(group), fonttype) + for tp, group in itertools.groupby(kerns_or_chars, type)], + Op.showkern) + prev_start_x = start_x + self.file.output(Op.end_text) + # Then emit all the multibyte characters, one at a time. + for ft_object, start_x, glyph_idx in multibyte_glyphs: + self._draw_xobject_glyph( + ft_object, fontsize, glyph_idx, start_x, 0 + ) + self.file.output(Op.grestore) + + def _draw_xobject_glyph(self, font, fontsize, glyph_idx, x, y): + """Draw a multibyte character from a Type 3 font as an XObject.""" + glyph_name = font.get_glyph_name(glyph_idx) + name = self.file._get_xobject_glyph_name(font.fname, glyph_name) + self.file.output( + Op.gsave, + 0.001 * fontsize, 0, 0, 0.001 * fontsize, x, y, Op.concat_matrix, + Name(name), Op.use_xobject, + Op.grestore, + ) + + def new_gc(self): + # docstring inherited + return GraphicsContextPdf(self.file) + + +class GraphicsContextPdf(GraphicsContextBase): + + def __init__(self, file): + super().__init__() + self._fillcolor = (0.0, 0.0, 0.0) + self._effective_alphas = (1.0, 1.0) + self.file = file + self.parent = None + + def __repr__(self): + d = dict(self.__dict__) + del d['file'] + del d['parent'] + return repr(d) + + def stroke(self): + """ + Predicate: does the path need to be stroked (its outline drawn)? + This tests for the various conditions that disable stroking + the path, in which case it would presumably be filled. + """ + # _linewidth > 0: in pdf a line of width 0 is drawn at minimum + # possible device width, but e.g., agg doesn't draw at all + return (self._linewidth > 0 and self._alpha > 0 and + (len(self._rgb) <= 3 or self._rgb[3] != 0.0)) + + def fill(self, *args): + """ + Predicate: does the path need to be filled? + + An optional argument can be used to specify an alternative + _fillcolor, as needed by RendererPdf.draw_markers. + """ + if len(args): + _fillcolor = args[0] + else: + _fillcolor = self._fillcolor + return (self._hatch or + (_fillcolor is not None and + (len(_fillcolor) <= 3 or _fillcolor[3] != 0.0))) + + def paint(self): + """ + Return the appropriate pdf operator to cause the path to be + stroked, filled, or both. + """ + return Op.paint_path(self.fill(), self.stroke()) + + capstyles = {'butt': 0, 'round': 1, 'projecting': 2} + joinstyles = {'miter': 0, 'round': 1, 'bevel': 2} + + def capstyle_cmd(self, style): + return [self.capstyles[style], Op.setlinecap] + + def joinstyle_cmd(self, style): + return [self.joinstyles[style], Op.setlinejoin] + + def linewidth_cmd(self, width): + return [width, Op.setlinewidth] + + def dash_cmd(self, dashes): + offset, dash = dashes + if dash is None: + dash = [] + offset = 0 + return [list(dash), offset, Op.setdash] + + def alpha_cmd(self, alpha, forced, effective_alphas): + name = self.file.alphaState(effective_alphas) + return [name, Op.setgstate] + + def hatch_cmd(self, hatch, hatch_color, hatch_linewidth): + if not hatch: + if self._fillcolor is not None: + return self.fillcolor_cmd(self._fillcolor) + else: + return [Name('DeviceRGB'), Op.setcolorspace_nonstroke] + else: + hatch_style = (hatch_color, self._fillcolor, hatch, hatch_linewidth) + name = self.file.hatchPattern(hatch_style) + return [Name('Pattern'), Op.setcolorspace_nonstroke, + name, Op.setcolor_nonstroke] + + def rgb_cmd(self, rgb): + if mpl.rcParams['pdf.inheritcolor']: + return [] + if rgb[0] == rgb[1] == rgb[2]: + return [rgb[0], Op.setgray_stroke] + else: + return [*rgb[:3], Op.setrgb_stroke] + + def fillcolor_cmd(self, rgb): + if rgb is None or mpl.rcParams['pdf.inheritcolor']: + return [] + elif rgb[0] == rgb[1] == rgb[2]: + return [rgb[0], Op.setgray_nonstroke] + else: + return [*rgb[:3], Op.setrgb_nonstroke] + + def push(self): + parent = GraphicsContextPdf(self.file) + parent.copy_properties(self) + parent.parent = self.parent + self.parent = parent + return [Op.gsave] + + def pop(self): + assert self.parent is not None + self.copy_properties(self.parent) + self.parent = self.parent.parent + return [Op.grestore] + + def clip_cmd(self, cliprect, clippath): + """Set clip rectangle. Calls `.pop()` and `.push()`.""" + cmds = [] + # Pop graphics state until we hit the right one or the stack is empty + while ((self._cliprect, self._clippath) != (cliprect, clippath) + and self.parent is not None): + cmds.extend(self.pop()) + # Unless we hit the right one, set the clip polygon + if ((self._cliprect, self._clippath) != (cliprect, clippath) or + self.parent is None): + cmds.extend(self.push()) + if self._cliprect != cliprect: + cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) + if self._clippath != clippath: + path, affine = clippath.get_transformed_path_and_affine() + cmds.extend( + PdfFile.pathOperations(path, affine, simplify=False) + + [Op.clip, Op.endpath]) + return cmds + + commands = ( + # must come first since may pop + (('_cliprect', '_clippath'), clip_cmd), + (('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd), + (('_capstyle',), capstyle_cmd), + (('_fillcolor',), fillcolor_cmd), + (('_joinstyle',), joinstyle_cmd), + (('_linewidth',), linewidth_cmd), + (('_dashes',), dash_cmd), + (('_rgb',), rgb_cmd), + # must come after fillcolor and rgb + (('_hatch', '_hatch_color', '_hatch_linewidth'), hatch_cmd), + ) + + def delta(self, other): + """ + Copy properties of other into self and return PDF commands + needed to transform *self* into *other*. + """ + cmds = [] + fill_performed = False + for params, cmd in self.commands: + different = False + for p in params: + ours = getattr(self, p) + theirs = getattr(other, p) + try: + if ours is None or theirs is None: + different = ours is not theirs + else: + different = bool(ours != theirs) + except ValueError: + ours = np.asarray(ours) + theirs = np.asarray(theirs) + different = (ours.shape != theirs.shape or + np.any(ours != theirs)) + if different: + break + + # Need to update hatching if we also updated fillcolor + if cmd.__name__ == 'hatch_cmd' and fill_performed: + different = True + + if different: + if cmd.__name__ == 'fillcolor_cmd': + fill_performed = True + theirs = [getattr(other, p) for p in params] + cmds.extend(cmd(self, *theirs)) + for p in params: + setattr(self, p, getattr(other, p)) + return cmds + + def copy_properties(self, other): + """ + Copy properties of other into self. + """ + super().copy_properties(other) + fillcolor = getattr(other, '_fillcolor', self._fillcolor) + effective_alphas = getattr(other, '_effective_alphas', + self._effective_alphas) + self._fillcolor = fillcolor + self._effective_alphas = effective_alphas + + def finalize(self): + """ + Make sure every pushed graphics state is popped. + """ + cmds = [] + while self.parent is not None: + cmds.extend(self.pop()) + return cmds + + +class PdfPages: + """ + A multi-page PDF file. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> # Initialize: + >>> with PdfPages('foo.pdf') as pdf: + ... # As many times as you like, create a figure fig and save it: + ... fig = plt.figure() + ... pdf.savefig(fig) + ... # When no figure is specified the current figure is saved + ... pdf.savefig() + + Notes + ----- + In reality `PdfPages` is a thin wrapper around `PdfFile`, in order to avoid + confusion when using `~.pyplot.savefig` and forgetting the format argument. + """ + + @_api.delete_parameter("3.10", "keep_empty", + addendum="This parameter does nothing.") + def __init__(self, filename, keep_empty=None, metadata=None): + """ + Create a new PdfPages object. + + Parameters + ---------- + filename : str or path-like or file-like + Plots using `PdfPages.savefig` will be written to a file at this location. + The file is opened when a figure is saved for the first time (overwriting + any older file with the same name). + + metadata : dict, optional + Information dictionary object (see PDF reference section 10.2.1 + 'Document Information Dictionary'), e.g.: + ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``. + + The standard keys are 'Title', 'Author', 'Subject', 'Keywords', + 'Creator', 'Producer', 'CreationDate', 'ModDate', and + 'Trapped'. Values have been predefined for 'Creator', 'Producer' + and 'CreationDate'. They can be removed by setting them to `None`. + """ + self._filename = filename + self._metadata = metadata + self._file = None + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def _ensure_file(self): + if self._file is None: + self._file = PdfFile(self._filename, metadata=self._metadata) # init. + return self._file + + def close(self): + """ + Finalize this object, making the underlying file a complete + PDF file. + """ + if self._file is not None: + self._file.finalize() + self._file.close() + self._file = None + + def infodict(self): + """ + Return a modifiable information dictionary object + (see PDF reference section 10.2.1 'Document Information + Dictionary'). + """ + return self._ensure_file().infoDict + + def savefig(self, figure=None, **kwargs): + """ + Save a `.Figure` to this file as a new page. + + Any other keyword arguments are passed to `~.Figure.savefig`. + + Parameters + ---------- + figure : `.Figure` or int, default: the active figure + The figure, or index of the figure, that is saved to the file. + """ + if not isinstance(figure, Figure): + if figure is None: + manager = Gcf.get_active() + else: + manager = Gcf.get_fig_manager(figure) + if manager is None: + raise ValueError(f"No figure {figure}") + figure = manager.canvas.figure + # Force use of pdf backend, as PdfPages is tightly coupled with it. + figure.savefig(self, format="pdf", backend="pdf", **kwargs) + + def get_pagecount(self): + """Return the current number of pages in the multipage pdf file.""" + return len(self._ensure_file().pageList) + + def attach_note(self, text, positionRect=[-100, -100, 0, 0]): + """ + Add a new text note to the page to be saved next. The optional + positionRect specifies the position of the new note on the + page. It is outside the page per default to make sure it is + invisible on printouts. + """ + self._ensure_file().newTextnote(text, positionRect) + + +class FigureCanvasPdf(FigureCanvasBase): + # docstring inherited + + fixed_dpi = 72 + filetypes = {'pdf': 'Portable Document Format'} + + def get_default_filetype(self): + return 'pdf' + + def print_pdf(self, filename, *, + bbox_inches_restore=None, metadata=None): + + dpi = self.figure.dpi + self.figure.dpi = 72 # there are 72 pdf points to an inch + width, height = self.figure.get_size_inches() + if isinstance(filename, PdfPages): + file = filename._ensure_file() + else: + file = PdfFile(filename, metadata=metadata) + try: + file.newPage(width, height) + renderer = MixedModeRenderer( + self.figure, width, height, dpi, + RendererPdf(file, dpi, height, width), + bbox_inches_restore=bbox_inches_restore) + self.figure.draw(renderer) + renderer.finalize() + if not isinstance(filename, PdfPages): + file.finalize() + finally: + if isinstance(filename, PdfPages): # finish off this page + file.endStream() + else: # we opened the file above; now finish it off + file.close() + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +FigureManagerPdf = FigureManagerBase + + +@_Backend.export +class _BackendPdf(_Backend): + FigureCanvas = FigureCanvasPdf diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_pgf.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_pgf.py new file mode 100644 index 0000000000000000000000000000000000000000..48b6e8ac152c7a7d832dad2691534e1ecc0b2fae --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_pgf.py @@ -0,0 +1,1010 @@ +import codecs +import datetime +import functools +from io import BytesIO +import logging +import math +import os +import pathlib +import shutil +import subprocess +from tempfile import TemporaryDirectory +import weakref + +from PIL import Image + +import matplotlib as mpl +from matplotlib import cbook, font_manager as fm +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase +) +from matplotlib.backends.backend_mixed import MixedModeRenderer +from matplotlib.backends.backend_pdf import ( + _create_pdf_info_dict, _datetime_to_pdf) +from matplotlib.path import Path +from matplotlib.figure import Figure +from matplotlib.font_manager import FontProperties +from matplotlib._pylab_helpers import Gcf + +_log = logging.getLogger(__name__) + + +_DOCUMENTCLASS = r"\documentclass{article}" + + +# Note: When formatting floating point values, it is important to use the +# %f/{:f} format rather than %s/{} to avoid triggering scientific notation, +# which is not recognized by TeX. + +def _get_preamble(): + """Prepare a LaTeX preamble based on the rcParams configuration.""" + font_size_pt = FontProperties( + size=mpl.rcParams["font.size"] + ).get_size_in_points() + return "\n".join([ + # Remove Matplotlib's custom command \mathdefault. (Not using + # \mathnormal instead since this looks odd with Computer Modern.) + r"\def\mathdefault#1{#1}", + # Use displaystyle for all math. + r"\everymath=\expandafter{\the\everymath\displaystyle}", + # Set up font sizes to match font.size setting. + # If present, use the KOMA package scrextend to adjust the standard + # LaTeX font commands (\tiny, ..., \normalsize, ..., \Huge) accordingly. + # Otherwise, only set \normalsize, manually. + r"\IfFileExists{scrextend.sty}{", + r" \usepackage[fontsize=%fpt]{scrextend}" % font_size_pt, + r"}{", + r" \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}" + % (font_size_pt, 1.2 * font_size_pt), + r" \normalsize", + r"}", + # Allow pgf.preamble to override the above definitions. + mpl.rcParams["pgf.preamble"], + *([ + r"\ifdefined\pdftexversion\else % non-pdftex case.", + r" \usepackage{fontspec}", + ] + [ + r" \%s{%s}[Path=\detokenize{%s/}]" + % (command, path.name, path.parent.as_posix()) + for command, path in zip( + ["setmainfont", "setsansfont", "setmonofont"], + [pathlib.Path(fm.findfont(family)) + for family in ["serif", "sans\\-serif", "monospace"]] + ) + ] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []), + # Documented as "must come last". + mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"), + ]) + + +# It's better to use only one unit for all coordinates, since the +# arithmetic in latex seems to produce inaccurate conversions. +latex_pt_to_in = 1. / 72.27 +latex_in_to_pt = 1. / latex_pt_to_in +mpl_pt_to_in = 1. / 72. +mpl_in_to_pt = 1. / mpl_pt_to_in + + +def _tex_escape(text): + r""" + Do some necessary and/or useful substitutions for texts to be included in + LaTeX documents. + """ + return text.replace("\N{MINUS SIGN}", r"\ensuremath{-}") + + +def _writeln(fh, line): + # Ending lines with a % prevents TeX from inserting spurious spaces + # (https://tex.stackexchange.com/questions/7453). + fh.write(line) + fh.write("%\n") + + +def _escape_and_apply_props(s, prop): + """ + Generate a TeX string that renders string *s* with font properties *prop*, + also applying any required escapes to *s*. + """ + commands = [] + + families = {"serif": r"\rmfamily", "sans": r"\sffamily", + "sans-serif": r"\sffamily", "monospace": r"\ttfamily"} + family = prop.get_family()[0] + if family in families: + commands.append(families[family]) + elif not mpl.rcParams["pgf.rcfonts"]: + commands.append(r"\fontfamily{\familydefault}") + elif any(font.name == family for font in fm.fontManager.ttflist): + commands.append( + r"\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fi" % family) + else: + _log.warning("Ignoring unknown font: %s", family) + + size = prop.get_size_in_points() + commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2)) + + styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"} + commands.append(styles[prop.get_style()]) + + boldstyles = ["semibold", "demibold", "demi", "bold", "heavy", + "extra bold", "black"] + if prop.get_weight() in boldstyles: + commands.append(r"\bfseries") + + commands.append(r"\selectfont") + return ( + "{" + + "".join(commands) + + r"\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}" + # It should normally be enough to set the catcode of % to 12 ("normal + # character"); this works on TeXLive 2021 but not on 2018, so we just + # make it active too. + + r"\catcode`\%=\active\def%{\%}" + + _tex_escape(s) + + "}" + ) + + +def _metadata_to_str(key, value): + """Convert metadata key/value to a form that hyperref accepts.""" + if isinstance(value, datetime.datetime): + value = _datetime_to_pdf(value) + elif key == 'Trapped': + value = value.name.decode('ascii') + else: + value = str(value) + return f'{key}={{{value}}}' + + +def make_pdf_to_png_converter(): + """Return a function that converts a pdf file to a png file.""" + try: + mpl._get_executable_info("pdftocairo") + except mpl.ExecutableNotFoundError: + pass + else: + return lambda pdffile, pngfile, dpi: subprocess.check_output( + ["pdftocairo", "-singlefile", "-transp", "-png", "-r", "%d" % dpi, + pdffile, os.path.splitext(pngfile)[0]], + stderr=subprocess.STDOUT) + try: + gs_info = mpl._get_executable_info("gs") + except mpl.ExecutableNotFoundError: + pass + else: + return lambda pdffile, pngfile, dpi: subprocess.check_output( + [gs_info.executable, + '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', + '-dUseCIEColor', '-dTextAlphaBits=4', + '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', + '-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile, + '-r%d' % dpi, pdffile], + stderr=subprocess.STDOUT) + raise RuntimeError("No suitable pdf to png renderer found.") + + +class LatexError(Exception): + def __init__(self, message, latex_output=""): + super().__init__(message) + self.latex_output = latex_output + + def __str__(self): + s, = self.args + if self.latex_output: + s += "\n" + self.latex_output + return s + + +class LatexManager: + """ + The LatexManager opens an instance of the LaTeX application for + determining the metrics of text elements. The LaTeX environment can be + modified by setting fonts and/or a custom preamble in `.rcParams`. + """ + + @staticmethod + def _build_latex_header(): + latex_header = [ + _DOCUMENTCLASS, + # Include TeX program name as a comment for cache invalidation. + # TeX does not allow this to be the first line. + rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}", + # Test whether \includegraphics supports interpolate option. + r"\usepackage{graphicx}", + _get_preamble(), + r"\begin{document}", + r"\typeout{pgf_backend_query_start}", + ] + return "\n".join(latex_header) + + @classmethod + def _get_cached_or_new(cls): + """ + Return the previous LatexManager if the header and tex system did not + change, or a new instance otherwise. + """ + return cls._get_cached_or_new_impl(cls._build_latex_header()) + + @classmethod + @functools.lru_cache(1) + def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new. + return cls() + + def _stdin_writeln(self, s): + if self.latex is None: + self._setup_latex_process() + self.latex.stdin.write(s) + self.latex.stdin.write("\n") + self.latex.stdin.flush() + + def _expect(self, s): + s = list(s) + chars = [] + while True: + c = self.latex.stdout.read(1) + chars.append(c) + if chars[-len(s):] == s: + break + if not c: + self.latex.kill() + self.latex = None + raise LatexError("LaTeX process halted", "".join(chars)) + return "".join(chars) + + def _expect_prompt(self): + return self._expect("\n*") + + def __init__(self): + # create a tmp directory for running latex, register it for deletion + self._tmpdir = TemporaryDirectory() + self.tmpdir = self._tmpdir.name + self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup) + + # test the LaTeX setup to ensure a clean startup of the subprocess + self._setup_latex_process(expect_reply=False) + stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n") + if self.latex.returncode != 0: + raise LatexError( + f"LaTeX errored (probably missing font or error in preamble) " + f"while processing the following input:\n" + f"{self._build_latex_header()}", + stdout) + self.latex = None # Will be set up on first use. + # Per-instance cache. + self._get_box_metrics = functools.lru_cache(self._get_box_metrics) + + def _setup_latex_process(self, *, expect_reply=True): + # Open LaTeX process for real work; register it for deletion. On + # Windows, we must ensure that the subprocess has quit before being + # able to delete the tmpdir in which it runs; in order to do so, we + # must first `kill()` it, and then `communicate()` with or `wait()` on + # it. + try: + self.latex = subprocess.Popen( + [mpl.rcParams["pgf.texsystem"], "-halt-on-error"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + encoding="utf-8", cwd=self.tmpdir) + except FileNotFoundError as err: + raise RuntimeError( + f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change " + f"rcParams['pgf.texsystem'] to an available TeX implementation" + ) from err + except OSError as err: + raise RuntimeError( + f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err + + def finalize_latex(latex): + latex.kill() + try: + latex.communicate() + except RuntimeError: + latex.wait() + + self._finalize_latex = weakref.finalize( + self, finalize_latex, self.latex) + # write header with 'pgf_backend_query_start' token + self._stdin_writeln(self._build_latex_header()) + if expect_reply: # read until 'pgf_backend_query_start' token appears + self._expect("*pgf_backend_query_start") + self._expect_prompt() + + def get_width_height_descent(self, text, prop): + """ + Get the width, total height, and descent (in TeX points) for a text + typeset by the current LaTeX environment. + """ + return self._get_box_metrics(_escape_and_apply_props(text, prop)) + + def _get_box_metrics(self, tex): + """ + Get the width, total height and descent (in TeX points) for a TeX + command's output in the current LaTeX environment. + """ + # This method gets wrapped in __init__ for per-instance caching. + self._stdin_writeln( # Send textbox to TeX & request metrics typeout. + # \sbox doesn't handle catcode assignments inside its argument, + # so repeat the assignment of the catcode of "^" and "%" outside. + r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}" + r"\typeout{\the\wd0,\the\ht0,\the\dp0}}" + % tex) + try: + answer = self._expect_prompt() + except LatexError as err: + # Here and below, use '{}' instead of {!r} to avoid doubling all + # backslashes. + raise ValueError("Error measuring {}\nLaTeX Output:\n{}" + .format(tex, err.latex_output)) from err + try: + # Parse metrics from the answer string. Last line is prompt, and + # next-to-last-line is blank line from \typeout. + width, height, offset = answer.splitlines()[-3].split(",") + except Exception as err: + raise ValueError("Error measuring {}\nLaTeX Output:\n{}" + .format(tex, answer)) from err + w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2]) + # The height returned from LaTeX goes from base to top; + # the height Matplotlib expects goes from bottom to top. + return w, h + o, o + + +@functools.lru_cache(1) +def _get_image_inclusion_command(): + man = LatexManager._get_cached_or_new() + man._stdin_writeln( + r"\includegraphics[interpolate=true]{%s}" + # Don't mess with backslashes on Windows. + % cbook._get_data_path("images/matplotlib.png").as_posix()) + try: + man._expect_prompt() + return r"\includegraphics" + except LatexError: + # Discard the broken manager. + LatexManager._get_cached_or_new_impl.cache_clear() + return r"\pgfimage" + + +class RendererPgf(RendererBase): + + def __init__(self, figure, fh): + """ + Create a new PGF renderer that translates any drawing instruction + into text commands to be interpreted in a latex pgfpicture environment. + + Attributes + ---------- + figure : `~matplotlib.figure.Figure` + Matplotlib figure to initialize height, width and dpi from. + fh : file-like + File handle for the output of the drawing commands. + """ + + super().__init__() + self.dpi = figure.dpi + self.fh = fh + self.figure = figure + self.image_counter = 0 + + def draw_markers(self, gc, marker_path, marker_trans, path, trans, + rgbFace=None): + # docstring inherited + + _writeln(self.fh, r"\begin{pgfscope}") + + # convert from display units to in + f = 1. / self.dpi + + # set style and clip + self._print_pgf_clip(gc) + self._print_pgf_path_styles(gc, rgbFace) + + # build marker definition + bl, tr = marker_path.get_extents(marker_trans).get_points() + coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f + _writeln(self.fh, + r"\pgfsys@defobject{currentmarker}" + r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords) + self._print_pgf_path(None, marker_path, marker_trans) + self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, + fill=rgbFace is not None) + _writeln(self.fh, r"}") + + maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX. + clip = (-maxcoord, -maxcoord, maxcoord, maxcoord) + + # draw marker for each vertex + for point, code in path.iter_segments(trans, simplify=False, + clip=clip): + x, y = point[0] * f, point[1] * f + _writeln(self.fh, r"\begin{pgfscope}") + _writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y)) + _writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}") + _writeln(self.fh, r"\end{pgfscope}") + + _writeln(self.fh, r"\end{pgfscope}") + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + _writeln(self.fh, r"\begin{pgfscope}") + # draw the path + self._print_pgf_clip(gc) + self._print_pgf_path_styles(gc, rgbFace) + self._print_pgf_path(gc, path, transform, rgbFace) + self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, + fill=rgbFace is not None) + _writeln(self.fh, r"\end{pgfscope}") + + # if present, draw pattern on top + if gc.get_hatch(): + _writeln(self.fh, r"\begin{pgfscope}") + self._print_pgf_path_styles(gc, rgbFace) + + # combine clip and path for clipping + self._print_pgf_clip(gc) + self._print_pgf_path(gc, path, transform, rgbFace) + _writeln(self.fh, r"\pgfusepath{clip}") + + # build pattern definition + _writeln(self.fh, + r"\pgfsys@defobject{currentpattern}" + r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{") + _writeln(self.fh, r"\begin{pgfscope}") + _writeln(self.fh, + r"\pgfpathrectangle" + r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}") + _writeln(self.fh, r"\pgfusepath{clip}") + scale = mpl.transforms.Affine2D().scale(self.dpi) + self._print_pgf_path(None, gc.get_hatch_path(), scale) + self._pgf_path_draw(stroke=True) + _writeln(self.fh, r"\end{pgfscope}") + _writeln(self.fh, r"}") + # repeat pattern, filling the bounding rect of the path + f = 1. / self.dpi + (xmin, ymin), (xmax, ymax) = \ + path.get_extents(transform).get_points() + xmin, xmax = f * xmin, f * xmax + ymin, ymax = f * ymin, f * ymax + repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin) + _writeln(self.fh, + r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin)) + for iy in range(repy): + for ix in range(repx): + _writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}") + _writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}") + _writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx) + _writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}") + + _writeln(self.fh, r"\end{pgfscope}") + + def _print_pgf_clip(self, gc): + f = 1. / self.dpi + # check for clip box + bbox = gc.get_clip_rectangle() + if bbox: + p1, p2 = bbox.get_points() + w, h = p2 - p1 + coords = p1[0] * f, p1[1] * f, w * f, h * f + _writeln(self.fh, + r"\pgfpathrectangle" + r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}" + % coords) + _writeln(self.fh, r"\pgfusepath{clip}") + + # check for clip path + clippath, clippath_trans = gc.get_clip_path() + if clippath is not None: + self._print_pgf_path(gc, clippath, clippath_trans) + _writeln(self.fh, r"\pgfusepath{clip}") + + def _print_pgf_path_styles(self, gc, rgbFace): + # cap style + capstyles = {"butt": r"\pgfsetbuttcap", + "round": r"\pgfsetroundcap", + "projecting": r"\pgfsetrectcap"} + _writeln(self.fh, capstyles[gc.get_capstyle()]) + + # join style + joinstyles = {"miter": r"\pgfsetmiterjoin", + "round": r"\pgfsetroundjoin", + "bevel": r"\pgfsetbeveljoin"} + _writeln(self.fh, joinstyles[gc.get_joinstyle()]) + + # filling + has_fill = rgbFace is not None + + if gc.get_forced_alpha(): + fillopacity = strokeopacity = gc.get_alpha() + else: + strokeopacity = gc.get_rgb()[3] + fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0 + + if has_fill: + _writeln(self.fh, + r"\definecolor{currentfill}{rgb}{%f,%f,%f}" + % tuple(rgbFace[:3])) + _writeln(self.fh, r"\pgfsetfillcolor{currentfill}") + if has_fill and fillopacity != 1.0: + _writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity) + + # linewidth and color + lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt + stroke_rgba = gc.get_rgb() + _writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw) + _writeln(self.fh, + r"\definecolor{currentstroke}{rgb}{%f,%f,%f}" + % stroke_rgba[:3]) + _writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}") + if strokeopacity != 1.0: + _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity) + + # line style + dash_offset, dash_list = gc.get_dashes() + if dash_list is None: + _writeln(self.fh, r"\pgfsetdash{}{0pt}") + else: + _writeln(self.fh, + r"\pgfsetdash{%s}{%fpt}" + % ("".join(r"{%fpt}" % dash for dash in dash_list), + dash_offset)) + + def _print_pgf_path(self, gc, path, transform, rgbFace=None): + f = 1. / self.dpi + # check for clip box / ignore clip for filled paths + bbox = gc.get_clip_rectangle() if gc else None + maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX. + if bbox and (rgbFace is None): + p1, p2 = bbox.get_points() + clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord), + min(p2[0], maxcoord), min(p2[1], maxcoord)) + else: + clip = (-maxcoord, -maxcoord, maxcoord, maxcoord) + # build path + for points, code in path.iter_segments(transform, clip=clip): + if code == Path.MOVETO: + x, y = tuple(points) + _writeln(self.fh, + r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" % + (f * x, f * y)) + elif code == Path.CLOSEPOLY: + _writeln(self.fh, r"\pgfpathclose") + elif code == Path.LINETO: + x, y = tuple(points) + _writeln(self.fh, + r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" % + (f * x, f * y)) + elif code == Path.CURVE3: + cx, cy, px, py = tuple(points) + coords = cx * f, cy * f, px * f, py * f + _writeln(self.fh, + r"\pgfpathquadraticcurveto" + r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}" + % coords) + elif code == Path.CURVE4: + c1x, c1y, c2x, c2y, px, py = tuple(points) + coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f + _writeln(self.fh, + r"\pgfpathcurveto" + r"{\pgfqpoint{%fin}{%fin}}" + r"{\pgfqpoint{%fin}{%fin}}" + r"{\pgfqpoint{%fin}{%fin}}" + % coords) + + # apply pgf decorators + sketch_params = gc.get_sketch_params() if gc else None + if sketch_params is not None: + # Only "length" directly maps to "segment length" in PGF's API. + # PGF uses "amplitude" to pass the combined deviation in both x- + # and y-direction, while matplotlib only varies the length of the + # wiggle along the line ("randomness" and "length" parameters) + # and has a separate "scale" argument for the amplitude. + # -> Use "randomness" as PRNG seed to allow the user to force the + # same shape on multiple sketched lines + scale, length, randomness = sketch_params + if scale is not None: + # make matplotlib and PGF rendering visually similar + length *= 0.5 + scale *= 2 + # PGF guarantees that repeated loading is a no-op + _writeln(self.fh, r"\usepgfmodule{decorations}") + _writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}") + _writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, " + f"segment length = {(length * f):f}in, " + f"amplitude = {(scale * f):f}in}}") + _writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}") + _writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}") + + def _pgf_path_draw(self, stroke=True, fill=False): + actions = [] + if stroke: + actions.append("stroke") + if fill: + actions.append("fill") + _writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions)) + + def option_scale_image(self): + # docstring inherited + return True + + def option_image_nocomposite(self): + # docstring inherited + return not mpl.rcParams['image.composite_image'] + + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + if w == 0 or h == 0: + return + + if not os.path.exists(getattr(self.fh, "name", "")): + raise ValueError( + "streamed pgf-code does not support raster graphics, consider " + "using the pgf-to-pdf option") + + # save the images to png files + path = pathlib.Path(self.fh.name) + fname_img = "%s-img%d.png" % (path.stem, self.image_counter) + Image.fromarray(im[::-1]).save(path.parent / fname_img) + self.image_counter += 1 + + # reference the image in the pgf picture + _writeln(self.fh, r"\begin{pgfscope}") + self._print_pgf_clip(gc) + f = 1. / self.dpi # from display coords to inch + if transform is None: + _writeln(self.fh, + r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) + w, h = w * f, h * f + else: + tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() + _writeln(self.fh, + r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % + (tr1 * f, tr2 * f, tr3 * f, tr4 * f, + (tr5 + x) * f, (tr6 + y) * f)) + w = h = 1 # scale is already included in the transform + interp = str(transform is None).lower() # interpolation in PDF reader + _writeln(self.fh, + r"\pgftext[left,bottom]" + r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" % + (_get_image_inclusion_command(), + interp, w, h, fname_img)) + _writeln(self.fh, r"\end{pgfscope}") + + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + self.draw_text(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext) + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + # prepare string for tex + s = _escape_and_apply_props(s, prop) + + _writeln(self.fh, r"\begin{pgfscope}") + self._print_pgf_clip(gc) + + alpha = gc.get_alpha() + if alpha != 1.0: + _writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha) + _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha) + rgb = tuple(gc.get_rgb())[:3] + _writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb) + _writeln(self.fh, r"\pgfsetstrokecolor{textcolor}") + _writeln(self.fh, r"\pgfsetfillcolor{textcolor}") + s = r"\color{textcolor}" + s + + dpi = self.figure.dpi + text_args = [] + if mtext and ( + (angle == 0 or + mtext.get_rotation_mode() == "anchor") and + mtext.get_verticalalignment() != "center_baseline"): + # if text anchoring can be supported, get the original coordinates + # and add alignment information + pos = mtext.get_unitless_position() + x, y = mtext.get_transform().transform(pos) + halign = {"left": "left", "right": "right", "center": ""} + valign = {"top": "top", "bottom": "bottom", + "baseline": "base", "center": ""} + text_args.extend([ + f"x={x/dpi:f}in", + f"y={y/dpi:f}in", + halign[mtext.get_horizontalalignment()], + valign[mtext.get_verticalalignment()], + ]) + else: + # if not, use the text layout provided by Matplotlib. + text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base") + + if angle != 0: + text_args.append("rotate=%f" % angle) + + _writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s)) + _writeln(self.fh, r"\end{pgfscope}") + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + # get text metrics in units of latex pt, convert to display units + w, h, d = (LatexManager._get_cached_or_new() + .get_width_height_descent(s, prop)) + # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in + # but having a little bit more space around the text looks better, + # plus the bounding box reported by LaTeX is VERY narrow + f = mpl_pt_to_in * self.dpi + return w * f, h * f, d * f + + def flipy(self): + # docstring inherited + return False + + def get_canvas_width_height(self): + # docstring inherited + return (self.figure.get_figwidth() * self.dpi, + self.figure.get_figheight() * self.dpi) + + def points_to_pixels(self, points): + # docstring inherited + return points * mpl_pt_to_in * self.dpi + + +class FigureCanvasPgf(FigureCanvasBase): + filetypes = {"pgf": "LaTeX PGF picture", + "pdf": "LaTeX compiled PGF picture", + "png": "Portable Network Graphics", } + + def get_default_filetype(self): + return 'pdf' + + def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None): + + header_text = """%% Creator: Matplotlib, PGF backend +%% +%% To include the figure in your LaTeX document, write +%% \\input{.pgf} +%% +%% Make sure the required packages are loaded in your preamble +%% \\usepackage{pgf} +%% +%% Also ensure that all the required font packages are loaded; for instance, +%% the lmodern package is sometimes necessary when using math font. +%% \\usepackage{lmodern} +%% +%% Figures using additional raster images can only be included by \\input if +%% they are in the same directory as the main LaTeX file. For loading figures +%% from other directories you can use the `import` package +%% \\usepackage{import} +%% +%% and then include the figures with +%% \\import{}{.pgf} +%% +""" + + # append the preamble used by the backend as a comment for debugging + header_info_preamble = ["%% Matplotlib used the following preamble"] + for line in _get_preamble().splitlines(): + header_info_preamble.append("%% " + line) + header_info_preamble.append("%%") + header_info_preamble = "\n".join(header_info_preamble) + + # get figure size in inch + w, h = self.figure.get_figwidth(), self.figure.get_figheight() + dpi = self.figure.dpi + + # create pgfpicture environment and write the pgf code + fh.write(header_text) + fh.write(header_info_preamble) + fh.write("\n") + _writeln(fh, r"\begingroup") + _writeln(fh, r"\makeatletter") + _writeln(fh, r"\begin{pgfpicture}") + _writeln(fh, + r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}" + % (w, h)) + _writeln(fh, r"\pgfusepath{use as bounding box, clip}") + renderer = MixedModeRenderer(self.figure, w, h, dpi, + RendererPgf(self.figure, fh), + bbox_inches_restore=bbox_inches_restore) + self.figure.draw(renderer) + + # end the pgfpicture environment + _writeln(fh, r"\end{pgfpicture}") + _writeln(fh, r"\makeatother") + _writeln(fh, r"\endgroup") + + def print_pgf(self, fname_or_fh, **kwargs): + """ + Output pgf macros for drawing the figure so it can be included and + rendered in latex documents. + """ + with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file: + if not cbook.file_requires_unicode(file): + file = codecs.getwriter("utf-8")(file) + self._print_pgf_to_fh(file, **kwargs) + + def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs): + """Use LaTeX to compile a pgf generated figure to pdf.""" + w, h = self.figure.get_size_inches() + + info_dict = _create_pdf_info_dict('pgf', metadata or {}) + pdfinfo = ','.join( + _metadata_to_str(k, v) for k, v in info_dict.items()) + + # print figure to pgf and compile it with latex + with TemporaryDirectory() as tmpdir: + tmppath = pathlib.Path(tmpdir) + self.print_pgf(tmppath / "figure.pgf", **kwargs) + (tmppath / "figure.tex").write_text( + "\n".join([ + _DOCUMENTCLASS, + r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo, + r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}" + % (w, h), + r"\usepackage{pgf}", + _get_preamble(), + r"\begin{document}", + r"\centering", + r"\input{figure.pgf}", + r"\end{document}", + ]), encoding="utf-8") + texcommand = mpl.rcParams["pgf.texsystem"] + cbook._check_and_log_subprocess( + [texcommand, "-interaction=nonstopmode", "-halt-on-error", + "figure.tex"], _log, cwd=tmpdir) + with ((tmppath / "figure.pdf").open("rb") as orig, + cbook.open_file_cm(fname_or_fh, "wb") as dest): + shutil.copyfileobj(orig, dest) # copy file contents to target + + def print_png(self, fname_or_fh, **kwargs): + """Use LaTeX to compile a pgf figure to pdf and convert it to png.""" + converter = make_pdf_to_png_converter() + with TemporaryDirectory() as tmpdir: + tmppath = pathlib.Path(tmpdir) + pdf_path = tmppath / "figure.pdf" + png_path = tmppath / "figure.png" + self.print_pdf(pdf_path, **kwargs) + converter(pdf_path, png_path, dpi=self.figure.dpi) + with (png_path.open("rb") as orig, + cbook.open_file_cm(fname_or_fh, "wb") as dest): + shutil.copyfileobj(orig, dest) # copy file contents to target + + def get_renderer(self): + return RendererPgf(self.figure, None) + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +FigureManagerPgf = FigureManagerBase + + +@_Backend.export +class _BackendPgf(_Backend): + FigureCanvas = FigureCanvasPgf + + +class PdfPages: + """ + A multi-page PDF file using the pgf backend + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> # Initialize: + >>> with PdfPages('foo.pdf') as pdf: + ... # As many times as you like, create a figure fig and save it: + ... fig = plt.figure() + ... pdf.savefig(fig) + ... # When no figure is specified the current figure is saved + ... pdf.savefig() + """ + + def __init__(self, filename, *, metadata=None): + """ + Create a new PdfPages object. + + Parameters + ---------- + filename : str or path-like + Plots using `PdfPages.savefig` will be written to a file at this + location. Any older file with the same name is overwritten. + + metadata : dict, optional + Information dictionary object (see PDF reference section 10.2.1 + 'Document Information Dictionary'), e.g.: + ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``. + + The standard keys are 'Title', 'Author', 'Subject', 'Keywords', + 'Creator', 'Producer', 'CreationDate', 'ModDate', and + 'Trapped'. Values have been predefined for 'Creator', 'Producer' + and 'CreationDate'. They can be removed by setting them to `None`. + + Note that some versions of LaTeX engines may ignore the 'Producer' + key and set it to themselves. + """ + self._output_name = filename + self._n_figures = 0 + self._metadata = (metadata or {}).copy() + self._info_dict = _create_pdf_info_dict('pgf', self._metadata) + self._file = BytesIO() + + def _write_header(self, width_inches, height_inches): + pdfinfo = ','.join( + _metadata_to_str(k, v) for k, v in self._info_dict.items()) + latex_header = "\n".join([ + _DOCUMENTCLASS, + r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo, + r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}" + % (width_inches, height_inches), + r"\usepackage{pgf}", + _get_preamble(), + r"\setlength{\parindent}{0pt}", + r"\begin{document}%", + ]) + self._file.write(latex_header.encode('utf-8')) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self): + """ + Finalize this object, running LaTeX in a temporary directory + and moving the final pdf file to *filename*. + """ + self._file.write(rb'\end{document}\n') + if self._n_figures > 0: + self._run_latex() + self._file.close() + + def _run_latex(self): + texcommand = mpl.rcParams["pgf.texsystem"] + with TemporaryDirectory() as tmpdir: + tex_source = pathlib.Path(tmpdir, "pdf_pages.tex") + tex_source.write_bytes(self._file.getvalue()) + cbook._check_and_log_subprocess( + [texcommand, "-interaction=nonstopmode", "-halt-on-error", + tex_source], + _log, cwd=tmpdir) + shutil.move(tex_source.with_suffix(".pdf"), self._output_name) + + def savefig(self, figure=None, **kwargs): + """ + Save a `.Figure` to this file as a new page. + + Any other keyword arguments are passed to `~.Figure.savefig`. + + Parameters + ---------- + figure : `.Figure` or int, default: the active figure + The figure, or index of the figure, that is saved to the file. + """ + if not isinstance(figure, Figure): + if figure is None: + manager = Gcf.get_active() + else: + manager = Gcf.get_fig_manager(figure) + if manager is None: + raise ValueError(f"No figure {figure}") + figure = manager.canvas.figure + + width, height = figure.get_size_inches() + if self._n_figures == 0: + self._write_header(width, height) + else: + # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and + # luatex<0.85; they were renamed to \pagewidth and \pageheight + # on luatex>=0.85. + self._file.write( + rb'\newpage' + rb'\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%fin' + rb'\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin' + b'%%\n' % (width, height) + ) + figure.savefig(self._file, format="pgf", backend="pgf", **kwargs) + self._n_figures += 1 + + def get_pagecount(self): + """Return the current number of pages in the multipage pdf file.""" + return self._n_figures diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_ps.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f914ae54205b9b77ae1db910885770cc9bfdec --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_ps.py @@ -0,0 +1,1481 @@ +""" +A PostScript backend, which can produce both PostScript .ps and .eps. +""" + +import bisect +import codecs +import datetime +from enum import Enum +import functools +from io import StringIO +import itertools +import logging +import math +import os +import pathlib +import shutil +import struct +from tempfile import TemporaryDirectory +import textwrap +import time + +import fontTools +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _path, _text_helpers +from matplotlib._afm import AFM +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) +from matplotlib.cbook import is_writable_file_like, file_requires_unicode +from matplotlib.font_manager import get_font +from matplotlib.ft2font import LoadFlags +from matplotlib._mathtext_data import uni2type1 +from matplotlib.path import Path +from matplotlib.texmanager import TexManager +from matplotlib.transforms import Affine2D +from matplotlib.backends.backend_mixed import MixedModeRenderer +from . import _backend_pdf_ps + + +_log = logging.getLogger(__name__) +debugPS = False + + +papersize = {'letter': (8.5, 11), + 'legal': (8.5, 14), + 'ledger': (11, 17), + 'a0': (33.11, 46.81), + 'a1': (23.39, 33.11), + 'a2': (16.54, 23.39), + 'a3': (11.69, 16.54), + 'a4': (8.27, 11.69), + 'a5': (5.83, 8.27), + 'a6': (4.13, 5.83), + 'a7': (2.91, 4.13), + 'a8': (2.05, 2.91), + 'a9': (1.46, 2.05), + 'a10': (1.02, 1.46), + 'b0': (40.55, 57.32), + 'b1': (28.66, 40.55), + 'b2': (20.27, 28.66), + 'b3': (14.33, 20.27), + 'b4': (10.11, 14.33), + 'b5': (7.16, 10.11), + 'b6': (5.04, 7.16), + 'b7': (3.58, 5.04), + 'b8': (2.51, 3.58), + 'b9': (1.76, 2.51), + 'b10': (1.26, 1.76)} + + +def _nums_to_str(*args, sep=" "): + return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args) + + +def _move_path_to_path_or_stream(src, dst): + """ + Move the contents of file at *src* to path-or-filelike *dst*. + + If *dst* is a path, the metadata of *src* are *not* copied. + """ + if is_writable_file_like(dst): + fh = (open(src, encoding='latin-1') + if file_requires_unicode(dst) + else open(src, 'rb')) + with fh: + shutil.copyfileobj(fh, dst) + else: + shutil.move(src, dst, copy_function=shutil.copyfile) + + +def _font_to_ps_type3(font_path, chars): + """ + Subset *chars* from the font at *font_path* into a Type 3 font. + + Parameters + ---------- + font_path : path-like + Path to the font to be subsetted. + chars : str + The characters to include in the subsetted font. + + Returns + ------- + str + The string representation of a Type 3 font, which can be included + verbatim into a PostScript file. + """ + font = get_font(font_path, hinting_factor=1) + glyph_ids = [font.get_char_index(c) for c in chars] + + preamble = """\ +%!PS-Adobe-3.0 Resource-Font +%%Creator: Converted from TrueType to Type 3 by Matplotlib. +10 dict begin +/FontName /{font_name} def +/PaintType 0 def +/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def +/FontBBox [{bbox}] def +/FontType 3 def +/Encoding [{encoding}] def +/CharStrings {num_glyphs} dict dup begin +/.notdef 0 def +""".format(font_name=font.postscript_name, + inv_units_per_em=1 / font.units_per_EM, + bbox=" ".join(map(str, font.bbox)), + encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}" + for glyph_id in glyph_ids), + num_glyphs=len(glyph_ids) + 1) + postamble = """ +end readonly def + +/BuildGlyph { + exch begin + CharStrings exch + 2 copy known not {pop /.notdef} if + true 3 1 roll get exec + end +} _d + +/BuildChar { + 1 index /Encoding get exch get + 1 index /BuildGlyph get exec +} _d + +FontName currentdict end definefont pop +""" + + entries = [] + for glyph_id in glyph_ids: + g = font.load_glyph(glyph_id, LoadFlags.NO_SCALE) + v, c = font.get_path() + entries.append( + "/%(name)s{%(bbox)s sc\n" % { + "name": font.get_glyph_name(glyph_id), + "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])), + } + + _path.convert_to_string( + # Convert back to TrueType's internal units (1/64's). + # (Other dimensions are already in these units.) + Path(v * 64, c), None, None, False, None, 0, + # No code for quad Beziers triggers auto-conversion to cubics. + # Drop intermediate closepolys (relying on the outline + # decomposer always explicitly moving to the closing point + # first). + [b"m", b"l", b"", b"c", b""], True).decode("ascii") + + "ce} _d" + ) + + return preamble + "\n".join(entries) + postamble + + +def _font_to_ps_type42(font_path, chars, fh): + """ + Subset *chars* from the font at *font_path* into a Type 42 font at *fh*. + + Parameters + ---------- + font_path : path-like + Path to the font to be subsetted. + chars : str + The characters to include in the subsetted font. + fh : file-like + Where to write the font. + """ + subset_str = ''.join(chr(c) for c in chars) + _log.debug("SUBSET %s characters: %s", font_path, subset_str) + try: + kw = {} + # fix this once we support loading more fonts from a collection + # https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541 + if font_path.endswith('.ttc'): + kw['fontNumber'] = 0 + with (fontTools.ttLib.TTFont(font_path, **kw) as font, + _backend_pdf_ps.get_glyphs_subset(font_path, subset_str) as subset): + fontdata = _backend_pdf_ps.font_as_file(subset).getvalue() + _log.debug( + "SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size, + len(fontdata) + ) + fh.write(_serialize_type42(font, subset, fontdata)) + except RuntimeError: + _log.warning( + "The PostScript backend does not currently support the selected font (%s).", + font_path) + raise + + +def _serialize_type42(font, subset, fontdata): + """ + Output a PostScript Type-42 format representation of font + + Parameters + ---------- + font : fontTools.ttLib.ttFont.TTFont + The original font object + subset : fontTools.ttLib.ttFont.TTFont + The subset font object + fontdata : bytes + The raw font data in TTF format + + Returns + ------- + str + The Type-42 formatted font + """ + version, breakpoints = _version_and_breakpoints(font.get('loca'), fontdata) + post = font['post'] + name = font['name'] + chars = _generate_charstrings(subset) + sfnts = _generate_sfnts(fontdata, subset, breakpoints) + return textwrap.dedent(f""" + %%!PS-TrueTypeFont-{version[0]}.{version[1]}-{font['head'].fontRevision:.7f} + 10 dict begin + /FontType 42 def + /FontMatrix [1 0 0 1 0 0] def + /FontName /{name.getDebugName(6)} def + /FontInfo 7 dict dup begin + /FullName ({name.getDebugName(4)}) def + /FamilyName ({name.getDebugName(1)}) def + /Version ({name.getDebugName(5)}) def + /ItalicAngle {post.italicAngle} def + /isFixedPitch {'true' if post.isFixedPitch else 'false'} def + /UnderlinePosition {post.underlinePosition} def + /UnderlineThickness {post.underlineThickness} def + end readonly def + /Encoding StandardEncoding def + /FontBBox [{_nums_to_str(*_bounds(font))}] def + /PaintType 0 def + /CIDMap 0 def + {chars} + {sfnts} + FontName currentdict end definefont pop + """) + + +def _version_and_breakpoints(loca, fontdata): + """ + Read the version number of the font and determine sfnts breakpoints. + + When a TrueType font file is written as a Type 42 font, it has to be + broken into substrings of at most 65535 bytes. These substrings must + begin at font table boundaries or glyph boundaries in the glyf table. + This function determines all possible breakpoints and it is the caller's + responsibility to do the splitting. + + Helper function for _font_to_ps_type42. + + Parameters + ---------- + loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None + The loca table of the font if available + fontdata : bytes + The raw data of the font + + Returns + ------- + version : tuple[int, int] + A 2-tuple of the major version number and minor version number. + breakpoints : list[int] + The breakpoints is a sorted list of offsets into fontdata; if loca is not + available, just the table boundaries. + """ + v1, v2, numTables = struct.unpack('>3h', fontdata[:6]) + version = (v1, v2) + + tables = {} + for i in range(numTables): + tag, _, offset, _ = struct.unpack('>4sIII', fontdata[12 + i*16:12 + (i+1)*16]) + tables[tag.decode('ascii')] = offset + if loca is not None: + glyf_breakpoints = {tables['glyf'] + offset for offset in loca.locations[:-1]} + else: + glyf_breakpoints = set() + breakpoints = sorted({*tables.values(), *glyf_breakpoints, len(fontdata)}) + + return version, breakpoints + + +def _bounds(font): + """ + Compute the font bounding box, as if all glyphs were written + at the same start position. + + Helper function for _font_to_ps_type42. + + Parameters + ---------- + font : fontTools.ttLib.ttFont.TTFont + The font + + Returns + ------- + tuple + (xMin, yMin, xMax, yMax) of the combined bounding box + of all the glyphs in the font + """ + gs = font.getGlyphSet(False) + pen = fontTools.pens.boundsPen.BoundsPen(gs) + for name in gs.keys(): + gs[name].draw(pen) + return pen.bounds or (0, 0, 0, 0) + + +def _generate_charstrings(font): + """ + Transform font glyphs into CharStrings + + Helper function for _font_to_ps_type42. + + Parameters + ---------- + font : fontTools.ttLib.ttFont.TTFont + The font + + Returns + ------- + str + A definition of the CharStrings dictionary in PostScript + """ + go = font.getGlyphOrder() + s = f'/CharStrings {len(go)} dict dup begin\n' + for i, name in enumerate(go): + s += f'/{name} {i} def\n' + s += 'end readonly def' + return s + + +def _generate_sfnts(fontdata, font, breakpoints): + """ + Transform font data into PostScript sfnts format. + + Helper function for _font_to_ps_type42. + + Parameters + ---------- + fontdata : bytes + The raw data of the font + font : fontTools.ttLib.ttFont.TTFont + The fontTools font object + breakpoints : list + Sorted offsets of possible breakpoints + + Returns + ------- + str + The sfnts array for the font definition, consisting + of hex-encoded strings in PostScript format + """ + s = '/sfnts[' + pos = 0 + while pos < len(fontdata): + i = bisect.bisect_left(breakpoints, pos + 65534) + newpos = breakpoints[i-1] + if newpos <= pos: + # have to accept a larger string + newpos = breakpoints[-1] + s += f'<{fontdata[pos:newpos].hex()}00>' # Always NUL terminate. + pos = newpos + s += ']def' + return '\n'.join(s[i:i+100] for i in range(0, len(s), 100)) + + +def _log_if_debug_on(meth): + """ + Wrap `RendererPS` method *meth* to emit a PS comment with the method name, + if the global flag `debugPS` is set. + """ + @functools.wraps(meth) + def wrapper(self, *args, **kwargs): + if debugPS: + self._pswriter.write(f"% {meth.__name__}\n") + return meth(self, *args, **kwargs) + + return wrapper + + +class RendererPS(_backend_pdf_ps.RendererPDFPSBase): + """ + The renderer handles all the drawing primitives using a graphics + context instance that controls the colors/styles. + """ + + _afm_font_dir = cbook._get_data_path("fonts/afm") + _use_afm_rc_name = "ps.useafm" + + def __init__(self, width, height, pswriter, imagedpi=72): + # Although postscript itself is dpi independent, we need to inform the + # image code about a requested dpi to generate high resolution images + # and them scale them before embedding them. + super().__init__(width, height) + self._pswriter = pswriter + if mpl.rcParams['text.usetex']: + self.textcnt = 0 + self.psfrag = [] + self.imagedpi = imagedpi + + # current renderer state (None=uninitialised) + self.color = None + self.linewidth = None + self.linejoin = None + self.linecap = None + self.linedash = None + self.fontname = None + self.fontsize = None + self._hatches = {} + self.image_magnification = imagedpi / 72 + self._clip_paths = {} + self._path_collection_id = 0 + + self._character_tracker = _backend_pdf_ps.CharacterTracker() + self._logwarn_once = functools.cache(_log.warning) + + def _is_transparent(self, rgb_or_rgba): + if rgb_or_rgba is None: + return True # Consistent with rgbFace semantics. + elif len(rgb_or_rgba) == 4: + if rgb_or_rgba[3] == 0: + return True + if rgb_or_rgba[3] != 1: + self._logwarn_once( + "The PostScript backend does not support transparency; " + "partially transparent artists will be rendered opaque.") + return False + else: # len() == 3. + return False + + def set_color(self, r, g, b, store=True): + if (r, g, b) != self.color: + self._pswriter.write(f"{_nums_to_str(r)} setgray\n" + if r == g == b else + f"{_nums_to_str(r, g, b)} setrgbcolor\n") + if store: + self.color = (r, g, b) + + def set_linewidth(self, linewidth, store=True): + linewidth = float(linewidth) + if linewidth != self.linewidth: + self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n") + if store: + self.linewidth = linewidth + + @staticmethod + def _linejoin_cmd(linejoin): + # Support for directly passing integer values is for backcompat. + linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[ + linejoin] + return f"{linejoin:d} setlinejoin\n" + + def set_linejoin(self, linejoin, store=True): + if linejoin != self.linejoin: + self._pswriter.write(self._linejoin_cmd(linejoin)) + if store: + self.linejoin = linejoin + + @staticmethod + def _linecap_cmd(linecap): + # Support for directly passing integer values is for backcompat. + linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[ + linecap] + return f"{linecap:d} setlinecap\n" + + def set_linecap(self, linecap, store=True): + if linecap != self.linecap: + self._pswriter.write(self._linecap_cmd(linecap)) + if store: + self.linecap = linecap + + def set_linedash(self, offset, seq, store=True): + if self.linedash is not None: + oldo, oldseq = self.linedash + if np.array_equal(seq, oldseq) and oldo == offset: + return + + self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n" + if seq is not None and len(seq) else + "[] 0 setdash\n") + if store: + self.linedash = (offset, seq) + + def set_font(self, fontname, fontsize, store=True): + if (fontname, fontsize) != (self.fontname, self.fontsize): + self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n") + if store: + self.fontname = fontname + self.fontsize = fontsize + + def create_hatch(self, hatch, linewidth): + sidelen = 72 + if hatch in self._hatches: + return self._hatches[hatch] + name = 'H%d' % len(self._hatches) + pageheight = self.height * 72 + self._pswriter.write(f"""\ + << /PatternType 1 + /PaintType 2 + /TilingType 2 + /BBox[0 0 {sidelen:d} {sidelen:d}] + /XStep {sidelen:d} + /YStep {sidelen:d} + + /PaintProc {{ + pop + {linewidth:g} setlinewidth +{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)} + gsave + fill + grestore + stroke + }} bind + >> + matrix + 0 {pageheight:g} translate + makepattern + /{name} exch def +""") + self._hatches[hatch] = name + return name + + def get_image_magnification(self): + """ + Get the factor by which to magnify images passed to draw_image. + Allows a backend to have images at a different resolution to other + artists. + """ + return self.image_magnification + + def _convert_path(self, path, transform, clip=False, simplify=None): + if clip: + clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0) + else: + clip = None + return _path.convert_to_string( + path, transform, clip, simplify, None, + 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii") + + def _get_clip_cmd(self, gc): + clip = [] + rect = gc.get_clip_rectangle() + if rect is not None: + clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n") + path, trf = gc.get_clip_path() + if path is not None: + key = (path, id(trf)) + custom_clip_cmd = self._clip_paths.get(key) + if custom_clip_cmd is None: + custom_clip_cmd = "c%d" % len(self._clip_paths) + self._pswriter.write(f"""\ +/{custom_clip_cmd} {{ +{self._convert_path(path, trf, simplify=False)} +clip +newpath +}} bind def +""") + self._clip_paths[key] = custom_clip_cmd + clip.append(f"{custom_clip_cmd}\n") + return "".join(clip) + + @_log_if_debug_on + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + imagecmd = "false 3 colorimage" + data = im[::-1, :, :3] # Vertically flipped rgb values. + hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars. + + if transform is None: + matrix = "1 0 0 1 0 0" + xscale = w / self.image_magnification + yscale = h / self.image_magnification + else: + matrix = " ".join(map(str, transform.frozen().to_values())) + xscale = 1.0 + yscale = 1.0 + + self._pswriter.write(f"""\ +gsave +{self._get_clip_cmd(gc)} +{x:g} {y:g} translate +[{matrix}] concat +{xscale:g} {yscale:g} scale +/DataString {w:d} string def +{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ] +{{ +currentfile DataString readhexstring pop +}} bind {imagecmd} +{hexdata} +grestore +""") + + @_log_if_debug_on + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + clip = rgbFace is None and gc.get_hatch_path() is None + simplify = path.should_simplify and clip + ps = self._convert_path(path, transform, clip=clip, simplify=simplify) + self._draw_ps(ps, gc, rgbFace) + + @_log_if_debug_on + def draw_markers( + self, gc, marker_path, marker_trans, path, trans, rgbFace=None): + # docstring inherited + + ps_color = ( + None + if self._is_transparent(rgbFace) + else f'{_nums_to_str(rgbFace[0])} setgray' + if rgbFace[0] == rgbFace[1] == rgbFace[2] + else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor') + + # construct the generic marker command: + + # don't want the translate to be global + ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] + + lw = gc.get_linewidth() + alpha = (gc.get_alpha() + if gc.get_forced_alpha() or len(gc.get_rgb()) == 3 + else gc.get_rgb()[3]) + stroke = lw > 0 and alpha > 0 + if stroke: + ps_cmd.append('%.1f setlinewidth' % lw) + ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle())) + ps_cmd.append(self._linecap_cmd(gc.get_capstyle())) + + ps_cmd.append(self._convert_path(marker_path, marker_trans, + simplify=False)) + + if rgbFace: + if stroke: + ps_cmd.append('gsave') + if ps_color: + ps_cmd.extend([ps_color, 'fill']) + if stroke: + ps_cmd.append('grestore') + + if stroke: + ps_cmd.append('stroke') + ps_cmd.extend(['grestore', '} bind def']) + + for vertices, code in path.iter_segments( + trans, + clip=(0, 0, self.width*72, self.height*72), + simplify=False): + if len(vertices): + x, y = vertices[-2:] + ps_cmd.append(f"{x:g} {y:g} o") + + ps = '\n'.join(ps_cmd) + self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False) + + @_log_if_debug_on + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is + # (len_path + 2) * uses_per_path + # cost of definition+use is + # (len_path + 3) + 3 * uses_per_path + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path + if not should_do_optimization: + return RendererBase.draw_path_collection( + self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + path_codes = [] + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + name = 'p%d_%d' % (self._path_collection_id, i) + path_bytes = self._convert_path(path, transform, simplify=False) + self._pswriter.write(f"""\ +/{name} {{ +newpath +translate +{path_bytes} +}} bind def +""") + path_codes.append(name) + + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + ps = f"{xo:g} {yo:g} {path_id}" + self._draw_ps(ps, gc0, rgbFace) + + self._path_collection_id += 1 + + @_log_if_debug_on + def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): + # docstring inherited + if self._is_transparent(gc.get_rgb()): + return # Special handling for fully transparent. + + if not hasattr(self, "psfrag"): + self._logwarn_once( + "The PS backend determines usetex status solely based on " + "rcParams['text.usetex'] and does not support having " + "usetex=True only for some elements; this element will thus " + "be rendered as if usetex=False.") + self.draw_text(gc, x, y, s, prop, angle, False, mtext) + return + + w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX") + fontsize = prop.get_size_in_points() + thetext = 'psmarker%d' % self.textcnt + color = _nums_to_str(*gc.get_rgb()[:3], sep=',') + fontcmd = {'sans-serif': r'{\sffamily %s}', + 'monospace': r'{\ttfamily %s}'}.get( + mpl.rcParams['font.family'][0], r'{\rmfamily %s}') + s = fontcmd % s + tex = r'\color[rgb]{%s} %s' % (color, s) + + # Stick to bottom-left alignment, so subtract descent from the text-normal + # direction since text is normally positioned by its baseline. + rangle = np.radians(angle + 90) + pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle)) + self.psfrag.append( + r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % ( + thetext, angle, fontsize, fontsize*1.25, tex)) + + self._pswriter.write(f"""\ +gsave +{pos} moveto +({thetext}) +show +grestore +""") + self.textcnt += 1 + + @_log_if_debug_on + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + if self._is_transparent(gc.get_rgb()): + return # Special handling for fully transparent. + + if ismath == 'TeX': + return self.draw_tex(gc, x, y, s, prop, angle) + + if ismath: + return self.draw_mathtext(gc, x, y, s, prop, angle) + + stream = [] # list of (ps_name, x, char_name) + + if mpl.rcParams['ps.useafm']: + font = self._get_font_afm(prop) + ps_name = (font.postscript_name.encode("ascii", "replace") + .decode("ascii")) + scale = 0.001 * prop.get_size_in_points() + thisx = 0 + last_name = None # kerns returns 0 for None. + for c in s: + name = uni2type1.get(ord(c), f"uni{ord(c):04X}") + try: + width = font.get_width_from_char_name(name) + except KeyError: + name = 'question' + width = font.get_width_char('?') + kern = font.get_kern_dist_from_name(last_name, name) + last_name = name + thisx += kern * scale + stream.append((ps_name, thisx, name)) + thisx += width * scale + + else: + font = self._get_font_ttf(prop) + self._character_tracker.track(font, s) + for item in _text_helpers.layout(s, font): + ps_name = (item.ft_object.postscript_name + .encode("ascii", "replace").decode("ascii")) + glyph_name = item.ft_object.get_glyph_name(item.glyph_idx) + stream.append((ps_name, item.x, glyph_name)) + self.set_color(*gc.get_rgb()) + + for ps_name, group in itertools. \ + groupby(stream, lambda entry: entry[0]): + self.set_font(ps_name, prop.get_size_in_points(), False) + thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow" + for _, x, name in group) + self._pswriter.write(f"""\ +gsave +{self._get_clip_cmd(gc)} +{x:g} {y:g} translate +{angle:g} rotate +{thetext} +grestore +""") + + @_log_if_debug_on + def draw_mathtext(self, gc, x, y, s, prop, angle): + """Draw the math text using matplotlib.mathtext.""" + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + self.set_color(*gc.get_rgb()) + self._pswriter.write( + f"gsave\n" + f"{x:g} {y:g} translate\n" + f"{angle:g} rotate\n") + lastfont = None + for font, fontsize, num, ox, oy in glyphs: + self._character_tracker.track_glyph(font, num) + if (font.postscript_name, fontsize) != lastfont: + lastfont = font.postscript_name, fontsize + self._pswriter.write( + f"/{font.postscript_name} {fontsize} selectfont\n") + glyph_name = ( + font.get_name_char(chr(num)) if isinstance(font, AFM) else + font.get_glyph_name(font.get_char_index(num))) + self._pswriter.write( + f"{ox:g} {oy:g} moveto\n" + f"/{glyph_name} glyphshow\n") + for ox, oy, w, h in rects: + self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n") + self._pswriter.write("grestore\n") + + @_log_if_debug_on + def draw_gouraud_triangles(self, gc, points, colors, trans): + assert len(points) == len(colors) + if len(points) == 0: + return + assert points.ndim == 3 + assert points.shape[1] == 3 + assert points.shape[2] == 2 + assert colors.ndim == 3 + assert colors.shape[1] == 3 + assert colors.shape[2] == 4 + + shape = points.shape + flat_points = points.reshape((shape[0] * shape[1], 2)) + flat_points = trans.transform(flat_points) + flat_colors = colors.reshape((shape[0] * shape[1], 4)) + points_min = np.min(flat_points, axis=0) - (1 << 12) + points_max = np.max(flat_points, axis=0) + (1 << 12) + factor = np.ceil((2 ** 32 - 1) / (points_max - points_min)) + + xmin, ymin = points_min + xmax, ymax = points_max + + data = np.empty( + shape[0] * shape[1], + dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')]) + data['flags'] = 0 + data['points'] = (flat_points - points_min) * factor + data['colors'] = flat_colors[:, :3] * 255.0 + hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars. + + self._pswriter.write(f"""\ +gsave +<< /ShadingType 4 + /ColorSpace [/DeviceRGB] + /BitsPerCoordinate 32 + /BitsPerComponent 8 + /BitsPerFlag 8 + /AntiAlias true + /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ] + /DataSource < +{hexdata} +> +>> +shfill +grestore +""") + + def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True): + """ + Emit the PostScript snippet *ps* with all the attributes from *gc* + applied. *ps* must consist of PostScript commands to construct a path. + + The *fill* and/or *stroke* kwargs can be set to False if the *ps* + string already includes filling and/or stroking, in which case + `_draw_ps` is just supplying properties and clipping. + """ + write = self._pswriter.write + mightstroke = (gc.get_linewidth() > 0 + and not self._is_transparent(gc.get_rgb())) + if not mightstroke: + stroke = False + if self._is_transparent(rgbFace): + fill = False + hatch = gc.get_hatch() + + if mightstroke: + self.set_linewidth(gc.get_linewidth()) + self.set_linejoin(gc.get_joinstyle()) + self.set_linecap(gc.get_capstyle()) + self.set_linedash(*gc.get_dashes()) + if mightstroke or hatch: + self.set_color(*gc.get_rgb()[:3]) + write('gsave\n') + + write(self._get_clip_cmd(gc)) + + write(ps.strip()) + write("\n") + + if fill: + if stroke or hatch: + write("gsave\n") + self.set_color(*rgbFace[:3], store=False) + write("fill\n") + if stroke or hatch: + write("grestore\n") + + if hatch: + hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth()) + write("gsave\n") + write(_nums_to_str(*gc.get_hatch_color()[:3])) + write(f" {hatch_name} setpattern fill grestore\n") + + if stroke: + write("stroke\n") + + write("grestore\n") + + +class _Orientation(Enum): + portrait, landscape = range(2) + + def swap_if_landscape(self, shape): + return shape[::-1] if self.name == "landscape" else shape + + +class FigureCanvasPS(FigureCanvasBase): + fixed_dpi = 72 + filetypes = {'ps': 'Postscript', + 'eps': 'Encapsulated Postscript'} + + def get_default_filetype(self): + return 'ps' + + def _print_ps( + self, fmt, outfile, *, + metadata=None, papertype=None, orientation='portrait', + bbox_inches_restore=None, **kwargs): + + dpi = self.figure.dpi + self.figure.dpi = 72 # Override the dpi kwarg + + dsc_comments = {} + if isinstance(outfile, (str, os.PathLike)): + filename = pathlib.Path(outfile).name + dsc_comments["Title"] = \ + filename.encode("ascii", "replace").decode("ascii") + dsc_comments["Creator"] = (metadata or {}).get( + "Creator", + f"Matplotlib v{mpl.__version__}, https://matplotlib.org/") + # See https://reproducible-builds.org/specs/source-date-epoch/ + source_date_epoch = os.getenv("SOURCE_DATE_EPOCH") + dsc_comments["CreationDate"] = ( + datetime.datetime.fromtimestamp( + int(source_date_epoch), + datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y") + if source_date_epoch + else time.ctime()) + dsc_comments = "\n".join( + f"%%{k}: {v}" for k, v in dsc_comments.items()) + + if papertype is None: + papertype = mpl.rcParams['ps.papersize'] + papertype = papertype.lower() + _api.check_in_list(['figure', *papersize], papertype=papertype) + + orientation = _api.check_getitem( + _Orientation, orientation=orientation.lower()) + + printer = (self._print_figure_tex + if mpl.rcParams['text.usetex'] else + self._print_figure) + printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments, + orientation=orientation, papertype=papertype, + bbox_inches_restore=bbox_inches_restore, **kwargs) + + def _print_figure( + self, fmt, outfile, *, + dpi, dsc_comments, orientation, papertype, + bbox_inches_restore=None): + """ + Render the figure to a filesystem path or a file-like object. + + Parameters are as for `.print_figure`, except that *dsc_comments* is a + string containing Document Structuring Convention comments, + generated from the *metadata* parameter to `.print_figure`. + """ + is_eps = fmt == 'eps' + if not (isinstance(outfile, (str, os.PathLike)) + or is_writable_file_like(outfile)): + raise ValueError("outfile must be a path or a file-like object") + + # find the appropriate papertype + width, height = self.figure.get_size_inches() + if is_eps or papertype == 'figure': + paper_width, paper_height = width, height + else: + paper_width, paper_height = orientation.swap_if_landscape( + papersize[papertype]) + + # center the figure on the paper + xo = 72 * 0.5 * (paper_width - width) + yo = 72 * 0.5 * (paper_height - height) + + llx = xo + lly = yo + urx = llx + self.figure.bbox.width + ury = lly + self.figure.bbox.height + rotation = 0 + if orientation is _Orientation.landscape: + llx, lly, urx, ury = lly, llx, ury, urx + xo, yo = 72 * paper_height - yo, xo + rotation = 90 + bbox = (llx, lly, urx, ury) + + self._pswriter = StringIO() + + # mixed mode rendering + ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) + renderer = MixedModeRenderer( + self.figure, width, height, dpi, ps_renderer, + bbox_inches_restore=bbox_inches_restore) + + self.figure.draw(renderer) + + def print_figure_impl(fh): + # write the PostScript headers + if is_eps: + print("%!PS-Adobe-3.0 EPSF-3.0", file=fh) + else: + print("%!PS-Adobe-3.0", file=fh) + if papertype != 'figure': + print(f"%%DocumentPaperSizes: {papertype}", file=fh) + print("%%Pages: 1", file=fh) + print(f"%%LanguageLevel: 3\n" + f"{dsc_comments}\n" + f"%%Orientation: {orientation.name}\n" + f"{_get_bbox_header(bbox)}\n" + f"%%EndComments\n", + end="", file=fh) + + Ndict = len(_psDefs) + print("%%BeginProlog", file=fh) + if not mpl.rcParams['ps.useafm']: + Ndict += len(ps_renderer._character_tracker.used) + print("/mpldict %d dict def" % Ndict, file=fh) + print("mpldict begin", file=fh) + print("\n".join(_psDefs), file=fh) + if not mpl.rcParams['ps.useafm']: + for font_path, chars \ + in ps_renderer._character_tracker.used.items(): + if not chars: + continue + fonttype = mpl.rcParams['ps.fonttype'] + # Can't use more than 255 chars from a single Type 3 font. + if len(chars) > 255: + fonttype = 42 + fh.flush() + if fonttype == 3: + fh.write(_font_to_ps_type3(font_path, chars)) + else: # Type 42 only. + _font_to_ps_type42(font_path, chars, fh) + print("end", file=fh) + print("%%EndProlog", file=fh) + + if not is_eps: + print("%%Page: 1 1", file=fh) + print("mpldict begin", file=fh) + + print("%s translate" % _nums_to_str(xo, yo), file=fh) + if rotation: + print("%d rotate" % rotation, file=fh) + print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh) + + # write the figure + print(self._pswriter.getvalue(), file=fh) + + # write the trailer + print("end", file=fh) + print("showpage", file=fh) + if not is_eps: + print("%%EOF", file=fh) + fh.flush() + + if mpl.rcParams['ps.usedistiller']: + # We are going to use an external program to process the output. + # Write to a temporary file. + with TemporaryDirectory() as tmpdir: + tmpfile = os.path.join(tmpdir, "tmp.ps") + with open(tmpfile, 'w', encoding='latin-1') as fh: + print_figure_impl(fh) + if mpl.rcParams['ps.usedistiller'] == 'ghostscript': + _try_distill(gs_distill, + tmpfile, is_eps, ptype=papertype, bbox=bbox) + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': + _try_distill(xpdf_distill, + tmpfile, is_eps, ptype=papertype, bbox=bbox) + _move_path_to_path_or_stream(tmpfile, outfile) + + else: # Write directly to outfile. + with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file: + if not file_requires_unicode(file): + file = codecs.getwriter("latin-1")(file) + print_figure_impl(file) + + def _print_figure_tex( + self, fmt, outfile, *, + dpi, dsc_comments, orientation, papertype, + bbox_inches_restore=None): + """ + If :rc:`text.usetex` is True, a temporary pair of tex/eps files + are created to allow tex to manage the text layout via the PSFrags + package. These files are processed to yield the final ps or eps file. + + The rest of the behavior is as for `._print_figure`. + """ + is_eps = fmt == 'eps' + + width, height = self.figure.get_size_inches() + xo = 0 + yo = 0 + + llx = xo + lly = yo + urx = llx + self.figure.bbox.width + ury = lly + self.figure.bbox.height + bbox = (llx, lly, urx, ury) + + self._pswriter = StringIO() + + # mixed mode rendering + ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) + renderer = MixedModeRenderer(self.figure, + width, height, dpi, ps_renderer, + bbox_inches_restore=bbox_inches_restore) + + self.figure.draw(renderer) + + # write to a temp file, we'll move it to outfile when done + with TemporaryDirectory() as tmpdir: + tmppath = pathlib.Path(tmpdir, "tmp.ps") + tmppath.write_text( + f"""\ +%!PS-Adobe-3.0 EPSF-3.0 +%%LanguageLevel: 3 +{dsc_comments} +{_get_bbox_header(bbox)} +%%EndComments +%%BeginProlog +/mpldict {len(_psDefs)} dict def +mpldict begin +{"".join(_psDefs)} +end +%%EndProlog +mpldict begin +{_nums_to_str(xo, yo)} translate +0 0 {_nums_to_str(width*72, height*72)} rectclip +{self._pswriter.getvalue()} +end +showpage +""", + encoding="latin-1") + + if orientation is _Orientation.landscape: # now, ready to rotate + width, height = height, width + bbox = (lly, llx, ury, urx) + + # set the paper size to the figure size if is_eps. The + # resulting ps file has the given size with correct bounding + # box so that there is no need to call 'pstoeps' + if is_eps or papertype == 'figure': + paper_width, paper_height = orientation.swap_if_landscape( + self.figure.get_size_inches()) + else: + paper_width, paper_height = papersize[papertype] + + psfrag_rotated = _convert_psfrags( + tmppath, ps_renderer.psfrag, paper_width, paper_height, + orientation.name) + + if (mpl.rcParams['ps.usedistiller'] == 'ghostscript' + or mpl.rcParams['text.usetex']): + _try_distill(gs_distill, + tmppath, is_eps, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': + _try_distill(xpdf_distill, + tmppath, is_eps, ptype=papertype, bbox=bbox, + rotated=psfrag_rotated) + + _move_path_to_path_or_stream(tmppath, outfile) + + print_ps = functools.partialmethod(_print_ps, "ps") + print_eps = functools.partialmethod(_print_ps, "eps") + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation): + """ + When we want to use the LaTeX backend with postscript, we write PSFrag tags + to a temporary postscript file, each one marking a position for LaTeX to + render some text. convert_psfrags generates a LaTeX document containing the + commands to convert those tags to text. LaTeX/dvips produces the postscript + file that includes the actual text. + """ + with mpl.rc_context({ + "text.latex.preamble": + mpl.rcParams["text.latex.preamble"] + + mpl.texmanager._usepackage_if_not_loaded("color") + + mpl.texmanager._usepackage_if_not_loaded("graphicx") + + mpl.texmanager._usepackage_if_not_loaded("psfrag") + + r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}" + % {"width": paper_width, "height": paper_height} + }): + dvifile = TexManager().make_dvi( + "\n" + r"\begin{figure}""\n" + r" \centering\leavevmode""\n" + r" %(psfrags)s""\n" + r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n" + r"\end{figure}" + % { + "psfrags": "\n".join(psfrags), + "angle": 90 if orientation == 'landscape' else 0, + "epsfile": tmppath.resolve().as_posix(), + }, + fontsize=10) # tex's default fontsize. + + with TemporaryDirectory() as tmpdir: + psfile = os.path.join(tmpdir, "tmp.ps") + cbook._check_and_log_subprocess( + ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log) + shutil.move(psfile, tmppath) + + # check if the dvips created a ps in landscape paper. Somehow, + # above latex+dvips results in a ps file in a landscape mode for a + # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the + # bounding box of the final output got messed up. We check see if + # the generated ps file is in landscape and return this + # information. The return value is used in pstoeps step to recover + # the correct bounding box. 2010-06-05 JJL + with open(tmppath) as fh: + psfrag_rotated = "Landscape" in fh.read(1000) + return psfrag_rotated + + +def _try_distill(func, tmppath, *args, **kwargs): + try: + func(str(tmppath), *args, **kwargs) + except mpl.ExecutableNotFoundError as exc: + _log.warning("%s. Distillation step skipped.", exc) + + +def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): + """ + Use ghostscript's pswrite or epswrite device to distill a file. + This yields smaller files without illegal encapsulated postscript + operators. The output is low-level, converting text to outlines. + """ + + if eps: + paper_option = ["-dEPSCrop"] + elif ptype == "figure": + # The bbox will have its lower-left corner at (0, 0), so upper-right + # corner corresponds with paper size. + paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}", + f"-dDEVICEHEIGHTPOINTS={bbox[3]}"] + else: + paper_option = [f"-sPAPERSIZE={ptype}"] + + psfile = tmpfile + '.ps' + dpi = mpl.rcParams['ps.distiller.res'] + + cbook._check_and_log_subprocess( + [mpl._get_executable_info("gs").executable, + "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write", + *paper_option, f"-sOutputFile={psfile}", tmpfile], + _log) + + os.remove(tmpfile) + shutil.move(psfile, tmpfile) + + # While it is best if above steps preserve the original bounding + # box, there seem to be cases when it is not. For those cases, + # the original bbox can be restored during the pstoeps step. + + if eps: + # For some versions of gs, above steps result in a ps file where the + # original bbox is no more correct. Do not adjust bbox for now. + pstoeps(tmpfile, bbox, rotated=rotated) + + +def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): + """ + Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file. + This yields smaller files without illegal encapsulated postscript + operators. This distiller is preferred, generating high-level postscript + output that treats text as text. + """ + mpl._get_executable_info("gs") # Effectively checks for ps2pdf. + mpl._get_executable_info("pdftops") + + if eps: + paper_option = ["-dEPSCrop"] + elif ptype == "figure": + # The bbox will have its lower-left corner at (0, 0), so upper-right + # corner corresponds with paper size. + paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}", + f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"] + else: + paper_option = [f"-sPAPERSIZE#{ptype}"] + + with TemporaryDirectory() as tmpdir: + tmppdf = pathlib.Path(tmpdir, "tmp.pdf") + tmpps = pathlib.Path(tmpdir, "tmp.ps") + # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows + # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows). + cbook._check_and_log_subprocess( + ["ps2pdf", + "-dAutoFilterColorImages#false", + "-dAutoFilterGrayImages#false", + "-sAutoRotatePages#None", + "-sGrayImageFilter#FlateEncode", + "-sColorImageFilter#FlateEncode", + *paper_option, + tmpfile, tmppdf], _log) + cbook._check_and_log_subprocess( + ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log) + shutil.move(tmpps, tmpfile) + if eps: + pstoeps(tmpfile) + + +@_api.deprecated("3.9") +def get_bbox_header(lbrt, rotated=False): + """ + Return a postscript header string for the given bbox lbrt=(l, b, r, t). + Optionally, return rotate command. + """ + return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "") + + +def _get_bbox_header(lbrt): + """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t).""" + l, b, r, t = lbrt + return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n" + f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}") + + +def _get_rotate_command(lbrt): + """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t).""" + l, b, r, t = lbrt + return f"{l+r:.2f} {0:.2f} translate\n90 rotate" + + +def pstoeps(tmpfile, bbox=None, rotated=False): + """ + Convert the postscript to encapsulated postscript. The bbox of + the eps file will be replaced with the given *bbox* argument. If + None, original bbox will be used. + """ + + epsfile = tmpfile + '.eps' + with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph: + write = epsh.write + # Modify the header: + for line in tmph: + if line.startswith(b'%!PS'): + write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + if bbox: + write(_get_bbox_header(bbox).encode('ascii') + b'\n') + elif line.startswith(b'%%EndComments'): + write(line) + write(b'%%BeginProlog\n' + b'save\n' + b'countdictstack\n' + b'mark\n' + b'newpath\n' + b'/showpage {} def\n' + b'/setpagedevice {pop} def\n' + b'%%EndProlog\n' + b'%%Page 1 1\n') + if rotated: # The output eps file need to be rotated. + write(_get_rotate_command(bbox).encode('ascii') + b'\n') + break + elif bbox and line.startswith((b'%%Bound', b'%%HiResBound', + b'%%DocumentMedia', b'%%Pages')): + pass + else: + write(line) + # Now rewrite the rest of the file, and modify the trailer. + # This is done in a second loop such that the header of the embedded + # eps file is not modified. + for line in tmph: + if line.startswith(b'%%EOF'): + write(b'cleartomark\n' + b'countdictstack\n' + b'exch sub { end } repeat\n' + b'restore\n' + b'showpage\n' + b'%%EOF\n') + elif line.startswith(b'%%PageBoundingBox'): + pass + else: + write(line) + + os.remove(tmpfile) + shutil.move(epsfile, tmpfile) + + +FigureManagerPS = FigureManagerBase + + +# The following Python dictionary psDefs contains the entries for the +# PostScript dictionary mpldict. This dictionary implements most of +# the matplotlib primitives and some abbreviations. +# +# References: +# https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf +# http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial +# http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/ +# + +# The usage comments use the notation of the operator summary +# in the PostScript Language reference manual. +_psDefs = [ + # name proc *_d* - + # Note that this cannot be bound to /d, because when embedding a Type3 font + # we may want to define a "d" glyph using "/d{...} d" which would locally + # overwrite the definition. + "/_d { bind def } bind def", + # x y *m* - + "/m { moveto } _d", + # x y *l* - + "/l { lineto } _d", + # x y *r* - + "/r { rlineto } _d", + # x1 y1 x2 y2 x y *c* - + "/c { curveto } _d", + # *cl* - + "/cl { closepath } _d", + # *ce* - + "/ce { closepath eofill } _d", + # wx wy llx lly urx ury *setcachedevice* - + "/sc { setcachedevice } _d", +] + + +@_Backend.export +class _BackendPS(_Backend): + backend_version = 'Level II' + FigureCanvas = FigureCanvasPS diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde4866cad7e7e3f6555f04cbab1bbffb61960d --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt.py @@ -0,0 +1,1074 @@ +import functools +import os +import sys +import traceback + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + TimerBase, cursors, ToolContainerBase, MouseButton, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, + _allow_interrupt) +import matplotlib.backends.qt_editor.figureoptions as figureoptions +from . import qt_compat +from .qt_compat import ( + QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted) + + +# SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name +# instead they have manually specified names. +SPECIAL_KEYS = { + _to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [ + ("Key_Escape", "escape"), + ("Key_Tab", "tab"), + ("Key_Backspace", "backspace"), + ("Key_Return", "enter"), + ("Key_Enter", "enter"), + ("Key_Insert", "insert"), + ("Key_Delete", "delete"), + ("Key_Pause", "pause"), + ("Key_SysReq", "sysreq"), + ("Key_Clear", "clear"), + ("Key_Home", "home"), + ("Key_End", "end"), + ("Key_Left", "left"), + ("Key_Up", "up"), + ("Key_Right", "right"), + ("Key_Down", "down"), + ("Key_PageUp", "pageup"), + ("Key_PageDown", "pagedown"), + ("Key_Shift", "shift"), + # In macOS, the control and super (aka cmd/apple) keys are switched. + ("Key_Control", "control" if sys.platform != "darwin" else "cmd"), + ("Key_Meta", "meta" if sys.platform != "darwin" else "control"), + ("Key_Alt", "alt"), + ("Key_CapsLock", "caps_lock"), + ("Key_F1", "f1"), + ("Key_F2", "f2"), + ("Key_F3", "f3"), + ("Key_F4", "f4"), + ("Key_F5", "f5"), + ("Key_F6", "f6"), + ("Key_F7", "f7"), + ("Key_F8", "f8"), + ("Key_F9", "f9"), + ("Key_F10", "f10"), + ("Key_F10", "f11"), + ("Key_F12", "f12"), + ("Key_Super_L", "super"), + ("Key_Super_R", "super"), + ] +} +# Define which modifier keys are collected on keyboard events. +# Elements are (Qt::KeyboardModifiers, Qt::Key) tuples. +# Order determines the modifier order (ctrl+alt+...) reported by Matplotlib. +_MODIFIER_KEYS = [ + (_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)), + _to_int(getattr(QtCore.Qt.Key, key))) + for mod, key in [ + ("ControlModifier", "Key_Control"), + ("AltModifier", "Key_Alt"), + ("ShiftModifier", "Key_Shift"), + ("MetaModifier", "Key_Meta"), + ] +] +cursord = { + k: getattr(QtCore.Qt.CursorShape, v) for k, v in [ + (cursors.MOVE, "SizeAllCursor"), + (cursors.HAND, "PointingHandCursor"), + (cursors.POINTER, "ArrowCursor"), + (cursors.SELECT_REGION, "CrossCursor"), + (cursors.WAIT, "WaitCursor"), + (cursors.RESIZE_HORIZONTAL, "SizeHorCursor"), + (cursors.RESIZE_VERTICAL, "SizeVerCursor"), + ] +} + + +# lru_cache keeps a reference to the QApplication instance, keeping it from +# being GC'd. +@functools.lru_cache(1) +def _create_qApp(): + app = QtWidgets.QApplication.instance() + + # Create a new QApplication and configure it if none exists yet, as only + # one QApplication can exist at a time. + if app is None: + # display_is_valid returns False only if on Linux and neither X11 + # nor Wayland display can be opened. + if not mpl._c_internal_utils.display_is_valid(): + raise RuntimeError('Invalid DISPLAY variable') + + # Check to make sure a QApplication from a different major version + # of Qt is not instantiated in the process + if QT_API in {'PyQt6', 'PySide6'}: + other_bindings = ('PyQt5', 'PySide2') + qt_version = 6 + elif QT_API in {'PyQt5', 'PySide2'}: + other_bindings = ('PyQt6', 'PySide6') + qt_version = 5 + else: + raise RuntimeError("Should never be here") + + for binding in other_bindings: + mod = sys.modules.get(f'{binding}.QtWidgets') + if mod is not None and mod.QApplication.instance() is not None: + other_core = sys.modules.get(f'{binding}.QtCore') + _api.warn_external( + f'Matplotlib is using {QT_API} which wraps ' + f'{QtCore.qVersion()} however an instantiated ' + f'QApplication from {binding} which wraps ' + f'{other_core.qVersion()} exists. Mixing Qt major ' + 'versions may not work as expected.' + ) + break + if qt_version == 5: + try: + QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) + except AttributeError: # Only for Qt>=5.6, <6. + pass + try: + QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy( + QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) + except AttributeError: # Only for Qt>=5.14. + pass + app = QtWidgets.QApplication(["matplotlib"]) + if sys.platform == "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + app.setWindowIcon(icon) + app.setQuitOnLastWindowClosed(True) + cbook._setup_new_guiapp() + if qt_version == 5: + app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) + + return app + + +def _allow_interrupt_qt(qapp_or_eventloop): + """A context manager that allows terminating a plot by sending a SIGINT.""" + + # Use QSocketNotifier to read the socketpair while the Qt event loop runs. + + def prepare_notifier(rsock): + sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read) + + @sn.activated.connect + def _may_clear_sock(): + # Running a Python function on socket activation gives the interpreter a + # chance to handle the signal in Python land. We also need to drain the + # socket with recv() to re-arm it, because it will be written to as part of + # the wakeup. (We need this in case set_wakeup_fd catches a signal other + # than SIGINT and we shall continue waiting.) + try: + rsock.recv(1) + except BlockingIOError: + # This may occasionally fire too soon or more than once on Windows, so + # be forgiving about reading an empty socket. + pass + + return sn # Actually keep the notifier alive. + + def handle_sigint(): + if hasattr(qapp_or_eventloop, 'closeAllWindows'): + qapp_or_eventloop.closeAllWindows() + qapp_or_eventloop.quit() + + return _allow_interrupt(prepare_notifier, handle_sigint) + + +class TimerQT(TimerBase): + """Subclass of `.TimerBase` using QTimer events.""" + + def __init__(self, *args, **kwargs): + # Create a new timer and connect the timeout() signal to the + # _on_timer method. + self._timer = QtCore.QTimer() + self._timer.timeout.connect(self._on_timer) + super().__init__(*args, **kwargs) + + def __del__(self): + # The check for deletedness is needed to avoid an error at animation + # shutdown with PySide2. + if not _isdeleted(self._timer): + self._timer_stop() + + def _timer_set_single_shot(self): + self._timer.setSingleShot(self._single) + + def _timer_set_interval(self): + self._timer.setInterval(self._interval) + + def _timer_start(self): + self._timer.start() + + def _timer_stop(self): + self._timer.stop() + + +class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget): + required_interactive_framework = "qt" + _timer_cls = TimerQT + manager_class = _api.classproperty(lambda cls: FigureManagerQT) + + buttond = { + getattr(QtCore.Qt.MouseButton, k): v for k, v in [ + ("LeftButton", MouseButton.LEFT), + ("RightButton", MouseButton.RIGHT), + ("MiddleButton", MouseButton.MIDDLE), + ("XButton1", MouseButton.BACK), + ("XButton2", MouseButton.FORWARD), + ] + } + + def __init__(self, figure=None): + _create_qApp() + super().__init__(figure=figure) + + self._draw_pending = False + self._is_drawing = False + self._draw_rect_callback = lambda painter: None + self._in_resize_event = False + + self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent) + self.setMouseTracking(True) + self.resize(*self.get_width_height()) + + palette = QtGui.QPalette(QtGui.QColor("white")) + self.setPalette(palette) + + @QtCore.Slot() + def _update_pixel_ratio(self): + if self._set_device_pixel_ratio( + self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0 + # The easiest way to resize the canvas is to emit a resizeEvent + # since we implement all the logic for resizing the canvas for + # that event. + event = QtGui.QResizeEvent(self.size(), self.size()) + self.resizeEvent(event) + + @QtCore.Slot(QtGui.QScreen) + def _update_screen(self, screen): + # Handler for changes to a window's attached screen. + self._update_pixel_ratio() + if screen is not None: + screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio) + screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio) + + def showEvent(self, event): + # Set up correct pixel ratio, and connect to any signal changes for it, + # once the window is shown (and thus has these attributes). + window = self.window().windowHandle() + window.screenChanged.connect(self._update_screen) + self._update_screen(window.screen()) + + def set_cursor(self, cursor): + # docstring inherited + self.setCursor(_api.check_getitem(cursord, cursor=cursor)) + + def mouseEventCoords(self, pos=None): + """ + Calculate mouse coordinates in physical pixels. + + Qt uses logical pixels, but the figure is scaled to physical + pixels for rendering. Transform to physical pixels so that + all of the down-stream transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if pos is None: + pos = self.mapFromGlobal(QtGui.QCursor.pos()) + elif hasattr(pos, "position"): # qt6 QtGui.QEvent + pos = pos.position() + elif hasattr(pos, "pos"): # qt5 QtCore.QEvent + pos = pos.pos() + # (otherwise, it's already a QPoint) + x = pos.x() + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height / self.device_pixel_ratio - pos.y() + return x * self.device_pixel_ratio, y * self.device_pixel_ratio + + def enterEvent(self, event): + # Force querying of the modifiers, as the cached modifier state can + # have been invalidated while the window was out of focus. + mods = QtWidgets.QApplication.instance().queryKeyboardModifiers() + if self.figure is None: + return + LocationEvent("figure_enter_event", self, + *self.mouseEventCoords(event), + modifiers=self._mpl_modifiers(mods), + guiEvent=event)._process() + + def leaveEvent(self, event): + QtWidgets.QApplication.restoreOverrideCursor() + if self.figure is None: + return + LocationEvent("figure_leave_event", self, + *self.mouseEventCoords(), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mousePressEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseDoubleClickEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, dblclick=True, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseMoveEvent(self, event): + if self.figure is None: + return + MouseEvent("motion_notify_event", self, + *self.mouseEventCoords(event), + buttons=self._mpl_buttons(event.buttons()), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseReleaseEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_release_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def wheelEvent(self, event): + # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not + # provided (`isNull()`) and is unreliable on X11 ("xcb"). + if (event.pixelDelta().isNull() + or QtWidgets.QApplication.instance().platformName() == "xcb"): + steps = event.angleDelta().y() / 120 + else: + steps = event.pixelDelta().y() + if steps and self.figure is not None: + MouseEvent("scroll_event", self, + *self.mouseEventCoords(event), step=steps, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def keyPressEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_press_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def keyReleaseEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_release_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def resizeEvent(self, event): + if self._in_resize_event: # Prevent PyQt6 recursion + return + if self.figure is None: + return + self._in_resize_event = True + try: + w = event.size().width() * self.device_pixel_ratio + h = event.size().height() * self.device_pixel_ratio + dpival = self.figure.dpi + winch = w / dpival + hinch = h / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + # pass back into Qt to let it finish + QtWidgets.QWidget.resizeEvent(self, event) + # emit our resize events + ResizeEvent("resize_event", self)._process() + self.draw_idle() + finally: + self._in_resize_event = False + + def sizeHint(self): + w, h = self.get_width_height() + return QtCore.QSize(w, h) + + def minimumSizeHint(self): + return QtCore.QSize(10, 10) + + @staticmethod + def _mpl_buttons(buttons): + buttons = _to_int(buttons) + # State *after* press/release. + return {button for mask, button in FigureCanvasQT.buttond.items() + if _to_int(mask) & buttons} + + @staticmethod + def _mpl_modifiers(modifiers=None, *, exclude=None): + if modifiers is None: + modifiers = QtWidgets.QApplication.instance().keyboardModifiers() + modifiers = _to_int(modifiers) + # get names of the pressed modifier keys + # 'control' is named 'control' when a standalone key, but 'ctrl' when a + # modifier + # bit twiddling to pick out modifier keys from modifiers bitmask, + # if exclude is a MODIFIER, it should not be duplicated in mods + return [SPECIAL_KEYS[key].replace('control', 'ctrl') + for mask, key in _MODIFIER_KEYS + if exclude != key and modifiers & mask] + + def _get_key(self, event): + event_key = event.key() + mods = self._mpl_modifiers(exclude=event_key) + try: + # for certain keys (enter, left, backspace, etc) use a word for the + # key, rather than Unicode + key = SPECIAL_KEYS[event_key] + except KeyError: + # Unicode defines code points up to 0x10ffff (sys.maxunicode) + # QT will use Key_Codes larger than that for keyboard keys that are + # not Unicode characters (like multimedia keys) + # skip these + # if you really want them, you should add them to SPECIAL_KEYS + if event_key > sys.maxunicode: + return None + + key = chr(event_key) + # qt delivers capitalized letters. fix capitalization + # note that capslock is ignored + if 'shift' in mods: + mods.remove('shift') + else: + key = key.lower() + + return '+'.join(mods + [key]) + + def flush_events(self): + # docstring inherited + QtWidgets.QApplication.instance().processEvents() + + def start_event_loop(self, timeout=0): + # docstring inherited + if hasattr(self, "_event_loop") and self._event_loop.isRunning(): + raise RuntimeError("Event loop already running") + self._event_loop = event_loop = QtCore.QEventLoop() + if timeout > 0: + _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit) + + with _allow_interrupt_qt(event_loop): + qt_compat._exec(event_loop) + + def stop_event_loop(self, event=None): + # docstring inherited + if hasattr(self, "_event_loop"): + self._event_loop.quit() + + def draw(self): + """Render the figure, and queue a request for a Qt draw.""" + # The renderer draw is done here; delaying causes problems with code + # that uses the result of the draw() to update plot elements. + if self._is_drawing: + return + with cbook._setattr_cm(self, _is_drawing=True): + super().draw() + self.update() + + def draw_idle(self): + """Queue redraw of the Agg buffer and request Qt paintEvent.""" + # The Agg draw needs to be handled by the same thread Matplotlib + # modifies the scene graph from. Post Agg draw request to the + # current event loop in order to ensure thread affinity and to + # accumulate multiple draw requests from event handling. + # TODO: queued signal connection might be safer than singleShot + if not (getattr(self, '_draw_pending', False) or + getattr(self, '_is_drawing', False)): + self._draw_pending = True + QtCore.QTimer.singleShot(0, self._draw_idle) + + def blit(self, bbox=None): + # docstring inherited + if bbox is None and self.figure: + bbox = self.figure.bbox # Blit the entire canvas if bbox is None. + # repaint uses logical pixels, not physical pixels like the renderer. + l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds) + t = b + h + self.repaint(l, self.rect().height() - t, w, h) + + def _draw_idle(self): + with self._idle_draw_cntx(): + if not self._draw_pending: + return + self._draw_pending = False + if self.height() <= 0 or self.width() <= 0: + return + try: + self.draw() + except Exception: + # Uncaught exceptions are fatal for PyQt5, so catch them. + traceback.print_exc() + + def drawRectangle(self, rect): + # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs + # to be called at the end of paintEvent. + if rect is not None: + x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect) + x1 = x0 + w + y1 = y0 + h + def _draw_rect_callback(painter): + pen = QtGui.QPen( + QtGui.QColor("black"), + 1 / self.device_pixel_ratio + ) + + pen.setDashPattern([3, 3]) + for color, offset in [ + (QtGui.QColor("black"), 0), + (QtGui.QColor("white"), 3), + ]: + pen.setDashOffset(offset) + pen.setColor(color) + painter.setPen(pen) + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + painter.drawLine(x0, y0, x0, y1) + painter.drawLine(x0, y0, x1, y0) + painter.drawLine(x0, y1, x1, y1) + painter.drawLine(x1, y0, x1, y1) + else: + def _draw_rect_callback(painter): + return + self._draw_rect_callback = _draw_rect_callback + self.update() + + +class MainWindow(QtWidgets.QMainWindow): + closing = QtCore.Signal() + + def closeEvent(self, event): + self.closing.emit() + super().closeEvent(event) + + +class FigureManagerQT(FigureManagerBase): + """ + Attributes + ---------- + canvas : `FigureCanvas` + The FigureCanvas instance + num : int or str + The Figure number + toolbar : qt.QToolBar + The qt.QToolBar + window : qt.QMainWindow + The qt.QMainWindow + """ + + def __init__(self, canvas, num): + self.window = MainWindow() + super().__init__(canvas, num) + self.window.closing.connect(self._widgetclosed) + + if sys.platform != "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + self.window.setWindowIcon(icon) + + self.window._destroying = False + + if self.toolbar: + self.window.addToolBar(self.toolbar) + tbs_height = self.toolbar.sizeHint().height() + else: + tbs_height = 0 + + # resize the main window so it will display the canvas with the + # requested size: + cs = canvas.sizeHint() + cs_height = cs.height() + height = cs_height + tbs_height + self.window.resize(cs.width(), height) + + self.window.setCentralWidget(self.canvas) + + if mpl.is_interactive(): + self.window.show() + self.canvas.draw_idle() + + # Give the keyboard focus to the figure instead of the manager: + # StrongFocus accepts both tab and click to focus and will enable the + # canvas to process event without clicking. + # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum + self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) + self.canvas.setFocus() + + self.window.raise_() + + def full_screen_toggle(self): + if self.window.isFullScreen(): + self.window.showNormal() + else: + self.window.showFullScreen() + + def _widgetclosed(self): + CloseEvent("close_event", self.canvas)._process() + if self.window._destroying: + return + self.window._destroying = True + try: + Gcf.destroy(self) + except AttributeError: + pass + # It seems that when the python session is killed, + # Gcf can get destroyed before the Gcf.destroy + # line is run, leading to a useless AttributeError. + + def resize(self, width, height): + # The Qt methods return sizes in 'virtual' pixels so we do need to + # rescale from physical to logical pixels. + width = int(width / self.canvas.device_pixel_ratio) + height = int(height / self.canvas.device_pixel_ratio) + extra_width = self.window.width() - self.canvas.width() + extra_height = self.window.height() - self.canvas.height() + self.canvas.resize(width, height) + self.window.resize(width + extra_width, height + extra_height) + + @classmethod + def start_main_loop(cls): + qapp = QtWidgets.QApplication.instance() + if qapp: + with _allow_interrupt_qt(qapp): + qt_compat._exec(qapp) + + def show(self): + self.window._destroying = False + self.window.show() + if mpl.rcParams['figure.raise_window']: + self.window.activateWindow() + self.window.raise_() + + def destroy(self, *args): + # check for qApp first, as PySide deletes it in its atexit handler + if QtWidgets.QApplication.instance() is None: + return + if self.window._destroying: + return + self.window._destroying = True + if self.toolbar: + self.toolbar.destroy() + self.window.close() + + def get_window_title(self): + return self.window.windowTitle() + + def set_window_title(self, title): + self.window.setWindowTitle(title) + + +class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): + toolitems = [*NavigationToolbar2.toolitems] + toolitems.insert( + # Add 'customize' action after 'subplots' + [name for name, *_ in toolitems].index("Subplots") + 1, + ("Customize", "Edit axis, curve and image parameters", + "qt4_editor_options", "edit_parameters")) + + def __init__(self, canvas, parent=None, coordinates=True): + """coordinates: should we show the coordinates on the right?""" + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + self.coordinates = coordinates + self._actions = {} # mapping of toolitem method names to QActions. + self._subplot_dialog = None + + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.addSeparator() + else: + slot = getattr(self, callback) + # https://bugreports.qt.io/browse/PYSIDE-2512 + slot = functools.wraps(slot)(functools.partial(slot)) + slot = QtCore.Slot()(slot) + + a = self.addAction(self._icon(image_file + '.png'), + text, slot) + self._actions[callback] = a + if callback in ['zoom', 'pan']: + a.setCheckable(True) + if tooltip_text is not None: + a.setToolTip(tooltip_text) + + # Add the (x, y) location widget at the right side of the toolbar + # The stretch factor is 1 which means any resizing of the toolbar + # will resize this label instead of the buttons. + if self.coordinates: + self.locLabel = QtWidgets.QLabel("", self) + self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + + self.locLabel.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + labelAction = self.addWidget(self.locLabel) + labelAction.setVisible(True) + + NavigationToolbar2.__init__(self, canvas) + + def _icon(self, name): + """ + Construct a `.QIcon` from an image file *name*, including the extension + and relative to Matplotlib's "images" data directory. + """ + # use a high-resolution icon with suffix '_large' if available + # note: user-provided icons may not have '_large' versions + path_regular = cbook._get_data_path('images', name) + path_large = path_regular.with_name( + path_regular.name.replace('.png', '_large.png')) + filename = str(path_large if path_large.exists() else path_regular) + + pm = QtGui.QPixmap(filename) + pm.setDevicePixelRatio( + self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0 + if self.palette().color(self.backgroundRole()).value() < 128: + icon_color = self.palette().color(self.foregroundRole()) + mask = pm.createMaskFromColor( + QtGui.QColor('black'), + QtCore.Qt.MaskMode.MaskOutColor) + pm.fill(icon_color) + pm.setMask(mask) + return QtGui.QIcon(pm) + + def edit_parameters(self): + axes = self.canvas.figure.get_axes() + if not axes: + QtWidgets.QMessageBox.warning( + self.canvas.parent(), "Error", "There are no Axes to edit.") + return + elif len(axes) == 1: + ax, = axes + else: + titles = [ + ax.get_label() or + ax.get_title() or + ax.get_title("left") or + ax.get_title("right") or + " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or + f"" + for ax in axes] + duplicate_titles = [ + title for title in titles if titles.count(title) > 1] + for i, ax in enumerate(axes): + if titles[i] in duplicate_titles: + titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles. + item, ok = QtWidgets.QInputDialog.getItem( + self.canvas.parent(), + 'Customize', 'Select Axes:', titles, 0, False) + if not ok: + return + ax = axes[titles.index(item)] + figureoptions.figure_edit(ax, self) + + def _update_buttons_checked(self): + # sync button checkstates to match active mode + if 'pan' in self._actions: + self._actions['pan'].setChecked(self.mode.name == 'PAN') + if 'zoom' in self._actions: + self._actions['zoom'].setChecked(self.mode.name == 'ZOOM') + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def set_message(self, s): + if self.coordinates: + self.locLabel.setText(s) + + def draw_rubberband(self, event, x0, y0, x1, y1): + height = self.canvas.figure.bbox.height + y1 = height - y1 + y0 = height - y0 + rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] + self.canvas.drawRectangle(rect) + + def remove_rubberband(self): + self.canvas.drawRectangle(None) + + def configure_subplots(self): + if self._subplot_dialog is None: + self._subplot_dialog = SubplotToolQt( + self.canvas.figure, self.canvas.parent()) + self.canvas.mpl_connect( + "close_event", lambda e: self._subplot_dialog.reject()) + self._subplot_dialog.update_from_current_subplotpars() + self._subplot_dialog.setModal(True) + self._subplot_dialog.show() + return self._subplot_dialog + + def save_figure(self, *args): + filetypes = self.canvas.get_supported_filetypes_grouped() + sorted_filetypes = sorted(filetypes.items()) + default_filetype = self.canvas.get_default_filetype() + + startpath = os.path.expanduser(mpl.rcParams['savefig.directory']) + start = os.path.join(startpath, self.canvas.get_default_filename()) + filters = [] + selectedFilter = None + for name, exts in sorted_filetypes: + exts_list = " ".join(['*.%s' % ext for ext in exts]) + filter = f'{name} ({exts_list})' + if default_filetype in exts: + selectedFilter = filter + filters.append(filter) + filters = ';;'.join(filters) + + fname, filter = QtWidgets.QFileDialog.getSaveFileName( + self.canvas.parent(), "Choose a filename to save to", start, + filters, selectedFilter) + if fname: + # Save dir for next time, unless empty str (i.e., use cwd). + if startpath != "": + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) + try: + self.canvas.figure.savefig(fname) + except Exception as e: + QtWidgets.QMessageBox.critical( + self, "Error saving file", str(e), + QtWidgets.QMessageBox.StandardButton.Ok, + QtWidgets.QMessageBox.StandardButton.NoButton) + return fname + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if 'back' in self._actions: + self._actions['back'].setEnabled(can_backward) + if 'forward' in self._actions: + self._actions['forward'].setEnabled(can_forward) + + +class SubplotToolQt(QtWidgets.QDialog): + def __init__(self, targetfig, parent): + super().__init__(parent) + self.setWindowIcon(QtGui.QIcon( + str(cbook._get_data_path("images/matplotlib.png")))) + self.setObjectName("SubplotTool") + self._spinboxes = {} + main_layout = QtWidgets.QHBoxLayout() + self.setLayout(main_layout) + for group, spinboxes, buttons in [ + ("Borders", + ["top", "bottom", "left", "right"], + [("Export values", self._export_values)]), + ("Spacings", + ["hspace", "wspace"], + [("Tight layout", self._tight_layout), + ("Reset", self._reset), + ("Close", self.close)])]: + layout = QtWidgets.QVBoxLayout() + main_layout.addLayout(layout) + box = QtWidgets.QGroupBox(group) + layout.addWidget(box) + inner = QtWidgets.QFormLayout(box) + for name in spinboxes: + self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox() + spinbox.setRange(0, 1) + spinbox.setDecimals(3) + spinbox.setSingleStep(0.005) + spinbox.setKeyboardTracking(False) + spinbox.valueChanged.connect(self._on_value_changed) + inner.addRow(name, spinbox) + layout.addStretch(1) + for name, method in buttons: + button = QtWidgets.QPushButton(name) + # Don't trigger on , which is used to input values. + button.setAutoDefault(False) + button.clicked.connect(method) + layout.addWidget(button) + if name == "Close": + button.setFocus() + self._figure = targetfig + self._defaults = {} + self._export_values_dialog = None + self.update_from_current_subplotpars() + + def update_from_current_subplotpars(self): + self._defaults = {spinbox: getattr(self._figure.subplotpars, name) + for name, spinbox in self._spinboxes.items()} + self._reset() # Set spinbox current values without triggering signals. + + def _export_values(self): + # Explicitly round to 3 decimals (which is also the spinbox precision) + # to avoid numbers of the form 0.100...001. + self._export_values_dialog = QtWidgets.QDialog() + layout = QtWidgets.QVBoxLayout() + self._export_values_dialog.setLayout(layout) + text = QtWidgets.QPlainTextEdit() + text.setReadOnly(True) + layout.addWidget(text) + text.setPlainText( + ",\n".join(f"{attr}={spinbox.value():.3}" + for attr, spinbox in self._spinboxes.items())) + # Adjust the height of the text widget to fit the whole text, plus + # some padding. + size = text.maximumSize() + size.setHeight( + QtGui.QFontMetrics(text.document().defaultFont()) + .size(0, text.toPlainText()).height() + 20) + text.setMaximumSize(size) + self._export_values_dialog.show() + + def _on_value_changed(self): + spinboxes = self._spinboxes + # Set all mins and maxes, so that this can also be used in _reset(). + for lower, higher in [("bottom", "top"), ("left", "right")]: + spinboxes[higher].setMinimum(spinboxes[lower].value() + .001) + spinboxes[lower].setMaximum(spinboxes[higher].value() - .001) + self._figure.subplots_adjust( + **{attr: spinbox.value() for attr, spinbox in spinboxes.items()}) + self._figure.canvas.draw_idle() + + def _tight_layout(self): + self._figure.tight_layout() + for attr, spinbox in self._spinboxes.items(): + spinbox.blockSignals(True) + spinbox.setValue(getattr(self._figure.subplotpars, attr)) + spinbox.blockSignals(False) + self._figure.canvas.draw_idle() + + def _reset(self): + for spinbox, value in self._defaults.items(): + spinbox.setRange(0, 1) + spinbox.blockSignals(True) + spinbox.setValue(value) + spinbox.blockSignals(False) + self._on_value_changed() + + +class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): + def __init__(self, toolmanager, parent=None): + ToolContainerBase.__init__(self, toolmanager) + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + message_label = QtWidgets.QLabel("") + message_label.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + message_label.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + self._message_action = self.addWidget(message_label) + self._toolitems = {} + self._groups = {} + + def add_toolitem( + self, name, group, position, image_file, description, toggle): + + button = QtWidgets.QToolButton(self) + if image_file: + button.setIcon(NavigationToolbar2QT._icon(self, image_file)) + button.setText(name) + if description: + button.setToolTip(description) + + def handler(): + self.trigger_tool(name) + if toggle: + button.setCheckable(True) + button.toggled.connect(handler) + else: + button.clicked.connect(handler) + + self._toolitems.setdefault(name, []) + self._add_to_group(group, name, button, position) + self._toolitems[name].append((button, handler)) + + def _add_to_group(self, group, name, button, position): + gr = self._groups.get(group, []) + if not gr: + sep = self.insertSeparator(self._message_action) + gr.append(sep) + before = gr[position] + widget = self.insertWidget(before, button) + gr.insert(position, widget) + self._groups[group] = gr + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for button, handler in self._toolitems[name]: + button.toggled.disconnect(handler) + button.setChecked(toggled) + button.toggled.connect(handler) + + def remove_toolitem(self, name): + for button, handler in self._toolitems.pop(name, []): + button.setParent(None) + + def set_message(self, s): + self.widgetForAction(self._message_action).setText(s) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._subplot_dialog = None + + def trigger(self, *args): + NavigationToolbar2QT.configure_subplots(self) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class SaveFigureQt(backend_tools.SaveFigureBase): + def trigger(self, *args): + NavigationToolbar2QT.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class RubberbandQt(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + NavigationToolbar2QT.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + NavigationToolbar2QT.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class HelpQt(backend_tools.ToolHelpBase): + def trigger(self, *args): + QtWidgets.QMessageBox.information(None, "Help", self._get_help_html()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + pixmap = self.canvas.grab() + QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap) + + +FigureManagerQT._toolbar2_class = NavigationToolbar2QT +FigureManagerQT._toolmanager_toolbar_class = ToolbarQt + + +@_Backend.export +class _BackendQT(_Backend): + backend_version = __version__ + FigureCanvas = FigureCanvasQT + FigureManager = FigureManagerQT + mainloop = FigureManagerQT.start_main_loop diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5.py new file mode 100644 index 0000000000000000000000000000000000000000..d94062b723f49aa1ff2fb0621748232684feef72 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5.py @@ -0,0 +1,28 @@ +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True + + +from .backend_qt import ( # noqa + SPECIAL_KEYS, + # Public API + cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT, + FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt, + SaveFigureQt, ConfigureSubplotsQt, RubberbandQt, + HelpQt, ToolCopyToClipboardQT, + # internal re-exports + FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2, + TimerBase, ToolContainerBase, figureoptions, Gcf +) +from . import backend_qt as _backend_qt # noqa + + +@_BackendQT.export +class _BackendQT5(_BackendQT): + pass + + +def __getattr__(name): + if name == 'qApp': + return _backend_qt.qApp + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5agg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5agg.py new file mode 100644 index 0000000000000000000000000000000000000000..8a92fd5135d5a3f4b05b3a71d1089e15d031fd59 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5agg.py @@ -0,0 +1,14 @@ +""" +Render to qt from agg +""" +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True +from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611 + _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT, + FigureCanvasAgg, FigureCanvasQT) + + +@_BackendQTAgg.export +class _BackendQT5Agg(_BackendQTAgg): + pass diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5cairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5cairo.py new file mode 100644 index 0000000000000000000000000000000000000000..a4263f5971191a26d849a741a24cf40f7ea8b9ac --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qt5cairo.py @@ -0,0 +1,11 @@ +from .. import backends + +backends._QT_FORCE_QT5_BINDING = True +from .backend_qtcairo import ( # noqa: F401, E402 # pylint: disable=W0611 + _BackendQTCairo, FigureCanvasQTCairo, FigureCanvasCairo, FigureCanvasQT +) + + +@_BackendQTCairo.export +class _BackendQT5Cairo(_BackendQTCairo): + pass diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtagg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtagg.py new file mode 100644 index 0000000000000000000000000000000000000000..256e50a3d1c3305be1b5fd5e9da9cb9807f4ec1f --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtagg.py @@ -0,0 +1,86 @@ +""" +Render to qt from agg. +""" + +import ctypes + +from matplotlib.transforms import Bbox + +from .qt_compat import QT_API, QtCore, QtGui +from .backend_agg import FigureCanvasAgg +from .backend_qt import _BackendQT, FigureCanvasQT +from .backend_qt import ( # noqa: F401 # pylint: disable=W0611 + FigureManagerQT, NavigationToolbar2QT) + + +class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT): + + def paintEvent(self, event): + """ + Copy the image from the Agg canvas to the qt.drawable. + + In Qt, all drawing should be done inside of here when a widget is + shown onscreen. + """ + self._draw_idle() # Only does something if a draw is pending. + + # If the canvas does not have a renderer, then give up and wait for + # FigureCanvasAgg.draw(self) to be called. + if not hasattr(self, 'renderer'): + return + + painter = QtGui.QPainter(self) + try: + # See documentation of QRect: bottom() and right() are off + # by 1, so use left() + width() and top() + height(). + rect = event.rect() + # scale rect dimensions using the screen dpi ratio to get + # correct values for the Figure coordinates (rather than + # QT5's coords) + width = rect.width() * self.device_pixel_ratio + height = rect.height() * self.device_pixel_ratio + left, top = self.mouseEventCoords(rect.topLeft()) + # shift the "top" by the height of the image to get the + # correct corner for our coordinate system + bottom = top - height + # same with the right side of the image + right = left + width + # create a buffer using the image bounding box + bbox = Bbox([[left, bottom], [right, top]]) + buf = memoryview(self.copy_from_bbox(bbox)) + + if QT_API == "PyQt6": + from PyQt6 import sip + ptr = int(sip.voidptr(buf)) + else: + ptr = buf + + painter.eraseRect(rect) # clear the widget canvas + qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0], + QtGui.QImage.Format.Format_RGBA8888) + qimage.setDevicePixelRatio(self.device_pixel_ratio) + # set origin using original QT coordinates + origin = QtCore.QPoint(rect.left(), rect.top()) + painter.drawImage(origin, qimage) + # Adjust the buf reference count to work around a memory + # leak bug in QImage under PySide. + if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12): + ctypes.c_long.from_address(id(buf)).value = 1 + + self._draw_rect_callback(painter) + finally: + painter.end() + + def print_figure(self, *args, **kwargs): + super().print_figure(*args, **kwargs) + # In some cases, Qt will itself trigger a paint event after closing the file + # save dialog. When that happens, we need to be sure that the internal canvas is + # re-drawn. However, if the user is using an automatically-chosen Qt backend but + # saving with a different backend (such as pgf), we do not want to trigger a + # full draw in Qt, so just set the flag for next time. + self._draw_pending = True + + +@_BackendQT.export +class _BackendQTAgg(_BackendQT): + FigureCanvas = FigureCanvasQTAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtcairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtcairo.py new file mode 100644 index 0000000000000000000000000000000000000000..72eb2dc70b906680b65e312a750386f6ed44ec6e --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_qtcairo.py @@ -0,0 +1,46 @@ +import ctypes + +from .backend_cairo import cairo, FigureCanvasCairo +from .backend_qt import _BackendQT, FigureCanvasQT +from .qt_compat import QT_API, QtCore, QtGui + + +class FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT): + def draw(self): + if hasattr(self._renderer.gc, "ctx"): + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + super().draw() + + def paintEvent(self, event): + width = int(self.device_pixel_ratio * self.width()) + height = int(self.device_pixel_ratio * self.height()) + if (width, height) != self._renderer.get_canvas_width_height(): + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) + self._renderer.set_context(cairo.Context(surface)) + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + buf = self._renderer.gc.ctx.get_target().get_data() + if QT_API == "PyQt6": + from PyQt6 import sip + ptr = int(sip.voidptr(buf)) + else: + ptr = buf + qimage = QtGui.QImage( + ptr, width, height, + QtGui.QImage.Format.Format_ARGB32_Premultiplied) + # Adjust the buf reference count to work around a memory leak bug in + # QImage under PySide. + if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12): + ctypes.c_long.from_address(id(buf)).value = 1 + qimage.setDevicePixelRatio(self.device_pixel_ratio) + painter = QtGui.QPainter(self) + painter.eraseRect(event.rect()) + painter.drawImage(0, 0, qimage) + self._draw_rect_callback(painter) + painter.end() + + +@_BackendQT.export +class _BackendQTCairo(_BackendQT): + FigureCanvas = FigureCanvasQTCairo diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_svg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_svg.py new file mode 100644 index 0000000000000000000000000000000000000000..2193dc6b6cdcfd29f6b1e1c9d441afcb638c0cef --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_svg.py @@ -0,0 +1,1380 @@ +import base64 +import codecs +import datetime +import gzip +import hashlib +from io import BytesIO +import itertools +import logging +import os +import re +import uuid + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import cbook, font_manager as fm +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) +from matplotlib.backends.backend_mixed import MixedModeRenderer +from matplotlib.colors import rgb2hex +from matplotlib.dates import UTC +from matplotlib.path import Path +from matplotlib import _path +from matplotlib.transforms import Affine2D, Affine2DBase + + +_log = logging.getLogger(__name__) + + +# ---------------------------------------------------------------------- +# SimpleXMLWriter class +# +# Based on an original by Fredrik Lundh, but modified here to: +# 1. Support modern Python idioms +# 2. Remove encoding support (it's handled by the file writer instead) +# 3. Support proper indentation +# 4. Minify things a little bit + +# -------------------------------------------------------------------- +# The SimpleXMLWriter module is +# +# Copyright (c) 2001-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + + +def _escape_cdata(s): + s = s.replace("&", "&") + s = s.replace("<", "<") + s = s.replace(">", ">") + return s + + +_escape_xml_comment = re.compile(r'-(?=-)') + + +def _escape_comment(s): + s = _escape_cdata(s) + return _escape_xml_comment.sub('- ', s) + + +def _escape_attrib(s): + s = s.replace("&", "&") + s = s.replace("'", "'") + s = s.replace('"', """) + s = s.replace("<", "<") + s = s.replace(">", ">") + return s + + +def _quote_escape_attrib(s): + return ('"' + _escape_cdata(s) + '"' if '"' not in s else + "'" + _escape_cdata(s) + "'" if "'" not in s else + '"' + _escape_attrib(s) + '"') + + +def _short_float_fmt(x): + """ + Create a short string representation of a float, which is %f + formatting with trailing zeros and the decimal point removed. + """ + return f'{x:f}'.rstrip('0').rstrip('.') + + +class XMLWriter: + """ + Parameters + ---------- + file : writable text file-like object + """ + + def __init__(self, file): + self.__write = file.write + if hasattr(file, "flush"): + self.flush = file.flush + self.__open = 0 # true if start tag is open + self.__tags = [] + self.__data = [] + self.__indentation = " " * 64 + + def __flush(self, indent=True): + # flush internal buffers + if self.__open: + if indent: + self.__write(">\n") + else: + self.__write(">") + self.__open = 0 + if self.__data: + data = ''.join(self.__data) + self.__write(_escape_cdata(data)) + self.__data = [] + + def start(self, tag, attrib={}, **extra): + """ + Open a new element. Attributes can be given as keyword + arguments, or as a string/string dictionary. The method returns + an opaque identifier that can be passed to the :meth:`close` + method, to close all open elements up to and including this one. + + Parameters + ---------- + tag + Element tag. + attrib + Attribute dictionary. Alternatively, attributes can be given as + keyword arguments. + + Returns + ------- + An element identifier. + """ + self.__flush() + tag = _escape_cdata(tag) + self.__data = [] + self.__tags.append(tag) + self.__write(self.__indentation[:len(self.__tags) - 1]) + self.__write(f"<{tag}") + for k, v in {**attrib, **extra}.items(): + if v: + k = _escape_cdata(k) + v = _quote_escape_attrib(v) + self.__write(f' {k}={v}') + self.__open = 1 + return len(self.__tags) - 1 + + def comment(self, comment): + """ + Add a comment to the output stream. + + Parameters + ---------- + comment : str + Comment text. + """ + self.__flush() + self.__write(self.__indentation[:len(self.__tags)]) + self.__write(f"\n") + + def data(self, text): + """ + Add character data to the output stream. + + Parameters + ---------- + text : str + Character data. + """ + self.__data.append(text) + + def end(self, tag=None, indent=True): + """ + Close the current element (opened by the most recent call to + :meth:`start`). + + Parameters + ---------- + tag + Element tag. If given, the tag must match the start tag. If + omitted, the current element is closed. + indent : bool, default: True + """ + if tag: + assert self.__tags, f"unbalanced end({tag})" + assert _escape_cdata(tag) == self.__tags[-1], \ + f"expected end({self.__tags[-1]}), got {tag}" + else: + assert self.__tags, "unbalanced end()" + tag = self.__tags.pop() + if self.__data: + self.__flush(indent) + elif self.__open: + self.__open = 0 + self.__write("/>\n") + return + if indent: + self.__write(self.__indentation[:len(self.__tags)]) + self.__write(f"\n") + + def close(self, id): + """ + Close open elements, up to (and including) the element identified + by the given identifier. + + Parameters + ---------- + id + Element identifier, as returned by the :meth:`start` method. + """ + while len(self.__tags) > id: + self.end() + + def element(self, tag, text=None, attrib={}, **extra): + """ + Add an entire element. This is the same as calling :meth:`start`, + :meth:`data`, and :meth:`end` in sequence. The *text* argument can be + omitted. + """ + self.start(tag, attrib, **extra) + if text: + self.data(text) + self.end(indent=False) + + def flush(self): + """Flush the output stream.""" + pass # replaced by the constructor + + +def _generate_transform(transform_list): + parts = [] + for type, value in transform_list: + if (type == 'scale' and (value == (1,) or value == (1, 1)) + or type == 'translate' and value == (0, 0) + or type == 'rotate' and value == (0,)): + continue + if type == 'matrix' and isinstance(value, Affine2DBase): + value = value.to_values() + parts.append('{}({})'.format( + type, ' '.join(_short_float_fmt(x) for x in value))) + return ' '.join(parts) + + +def _generate_css(attrib): + return "; ".join(f"{k}: {v}" for k, v in attrib.items()) + + +_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'} + + +def _check_is_str(info, key): + if not isinstance(info, str): + raise TypeError(f'Invalid type for {key} metadata. Expected str, not ' + f'{type(info)}.') + + +def _check_is_iterable_of_str(infos, key): + if np.iterable(infos): + for info in infos: + if not isinstance(info, str): + raise TypeError(f'Invalid type for {key} metadata. Expected ' + f'iterable of str, not {type(info)}.') + else: + raise TypeError(f'Invalid type for {key} metadata. Expected str or ' + f'iterable of str, not {type(infos)}.') + + +class RendererSVG(RendererBase): + def __init__(self, width, height, svgwriter, basename=None, image_dpi=72, + *, metadata=None): + self.width = width + self.height = height + self.writer = XMLWriter(svgwriter) + self.image_dpi = image_dpi # actual dpi at which we rasterize stuff + + if basename is None: + basename = getattr(svgwriter, "name", "") + if not isinstance(basename, str): + basename = "" + self.basename = basename + + self._groupd = {} + self._image_counter = itertools.count() + self._clip_path_ids = {} + self._clipd = {} + self._markers = {} + self._path_collection_id = 0 + self._hatchd = {} + self._has_gouraud = False + self._n_gradients = 0 + + super().__init__() + self._glyph_map = dict() + str_height = _short_float_fmt(height) + str_width = _short_float_fmt(width) + svgwriter.write(svgProlog) + self._start_id = self.writer.start( + 'svg', + width=f'{str_width}pt', + height=f'{str_height}pt', + viewBox=f'0 0 {str_width} {str_height}', + xmlns="http://www.w3.org/2000/svg", + version="1.1", + id=mpl.rcParams['svg.id'], + attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"}) + self._write_metadata(metadata) + self._write_default_style() + + def _get_clippath_id(self, clippath): + """ + Returns a stable and unique identifier for the *clippath* argument + object within the current rendering context. + + This allows plots that include custom clip paths to produce identical + SVG output on each render, provided that the :rc:`svg.hashsalt` config + setting and the ``SOURCE_DATE_EPOCH`` build-time environment variable + are set to fixed values. + """ + if clippath not in self._clip_path_ids: + self._clip_path_ids[clippath] = len(self._clip_path_ids) + return self._clip_path_ids[clippath] + + def finalize(self): + self._write_clips() + self._write_hatches() + self.writer.close(self._start_id) + self.writer.flush() + + def _write_metadata(self, metadata): + # Add metadata following the Dublin Core Metadata Initiative, and the + # Creative Commons Rights Expression Language. This is mainly for + # compatibility with Inkscape. + if metadata is None: + metadata = {} + metadata = { + 'Format': 'image/svg+xml', + 'Type': 'http://purl.org/dc/dcmitype/StillImage', + 'Creator': + f'Matplotlib v{mpl.__version__}, https://matplotlib.org/', + **metadata + } + writer = self.writer + + if 'Title' in metadata: + title = metadata['Title'] + _check_is_str(title, 'Title') + writer.element('title', text=title) + + # Special handling. + date = metadata.get('Date', None) + if date is not None: + if isinstance(date, str): + dates = [date] + elif isinstance(date, (datetime.datetime, datetime.date)): + dates = [date.isoformat()] + elif np.iterable(date): + dates = [] + for d in date: + if isinstance(d, str): + dates.append(d) + elif isinstance(d, (datetime.datetime, datetime.date)): + dates.append(d.isoformat()) + else: + raise TypeError( + f'Invalid type for Date metadata. ' + f'Expected iterable of str, date, or datetime, ' + f'not {type(d)}.') + else: + raise TypeError(f'Invalid type for Date metadata. ' + f'Expected str, date, datetime, or iterable ' + f'of the same, not {type(date)}.') + metadata['Date'] = '/'.join(dates) + elif 'Date' not in metadata: + # Do not add `Date` if the user explicitly set `Date` to `None` + # Get source date from SOURCE_DATE_EPOCH, if set. + # See https://reproducible-builds.org/specs/source-date-epoch/ + date = os.getenv("SOURCE_DATE_EPOCH") + if date: + date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc) + metadata['Date'] = date.replace(tzinfo=UTC).isoformat() + else: + metadata['Date'] = datetime.datetime.today().isoformat() + + mid = None + def ensure_metadata(mid): + if mid is not None: + return mid + mid = writer.start('metadata') + writer.start('rdf:RDF', attrib={ + 'xmlns:dc': "http://purl.org/dc/elements/1.1/", + 'xmlns:cc': "http://creativecommons.org/ns#", + 'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + }) + writer.start('cc:Work') + return mid + + uri = metadata.pop('Type', None) + if uri is not None: + mid = ensure_metadata(mid) + writer.element('dc:type', attrib={'rdf:resource': uri}) + + # Single value only. + for key in ['Title', 'Coverage', 'Date', 'Description', 'Format', + 'Identifier', 'Language', 'Relation', 'Source']: + info = metadata.pop(key, None) + if info is not None: + mid = ensure_metadata(mid) + _check_is_str(info, key) + writer.element(f'dc:{key.lower()}', text=info) + + # Multiple Agent values. + for key in ['Creator', 'Contributor', 'Publisher', 'Rights']: + agents = metadata.pop(key, None) + if agents is None: + continue + + if isinstance(agents, str): + agents = [agents] + + _check_is_iterable_of_str(agents, key) + # Now we know that we have an iterable of str + mid = ensure_metadata(mid) + writer.start(f'dc:{key.lower()}') + for agent in agents: + writer.start('cc:Agent') + writer.element('dc:title', text=agent) + writer.end('cc:Agent') + writer.end(f'dc:{key.lower()}') + + # Multiple values. + keywords = metadata.pop('Keywords', None) + if keywords is not None: + if isinstance(keywords, str): + keywords = [keywords] + _check_is_iterable_of_str(keywords, 'Keywords') + # Now we know that we have an iterable of str + mid = ensure_metadata(mid) + writer.start('dc:subject') + writer.start('rdf:Bag') + for keyword in keywords: + writer.element('rdf:li', text=keyword) + writer.end('rdf:Bag') + writer.end('dc:subject') + + if mid is not None: + writer.close(mid) + + if metadata: + raise ValueError('Unknown metadata key(s) passed to SVG writer: ' + + ','.join(metadata)) + + def _write_default_style(self): + writer = self.writer + default_style = _generate_css({ + 'stroke-linejoin': 'round', + 'stroke-linecap': 'butt'}) + writer.start('defs') + writer.element('style', type='text/css', text='*{%s}' % default_style) + writer.end('defs') + + def _make_id(self, type, content): + salt = mpl.rcParams['svg.hashsalt'] + if salt is None: + salt = str(uuid.uuid4()) + m = hashlib.sha256() + m.update(salt.encode('utf8')) + m.update(str(content).encode('utf8')) + return f'{type}{m.hexdigest()[:10]}' + + def _make_flip_transform(self, transform): + return transform + Affine2D().scale(1, -1).translate(0, self.height) + + def _get_hatch(self, gc, rgbFace): + """ + Create a new hatch pattern + """ + if rgbFace is not None: + rgbFace = tuple(rgbFace) + edge = gc.get_hatch_color() + if edge is not None: + edge = tuple(edge) + lw = gc.get_hatch_linewidth() + dictkey = (gc.get_hatch(), rgbFace, edge, lw) + oid = self._hatchd.get(dictkey) + if oid is None: + oid = self._make_id('h', dictkey) + self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge, lw), oid) + else: + _, oid = oid + return oid + + def _write_hatches(self): + if not len(self._hatchd): + return + HATCH_SIZE = 72 + writer = self.writer + writer.start('defs') + for (path, face, stroke, lw), oid in self._hatchd.values(): + writer.start( + 'pattern', + id=oid, + patternUnits="userSpaceOnUse", + x="0", y="0", width=str(HATCH_SIZE), + height=str(HATCH_SIZE)) + path_data = self._convert_path( + path, + Affine2D() + .scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), + simplify=False) + if face is None: + fill = 'none' + else: + fill = rgb2hex(face) + writer.element( + 'rect', + x="0", y="0", width=str(HATCH_SIZE+1), + height=str(HATCH_SIZE+1), + fill=fill) + hatch_style = { + 'fill': rgb2hex(stroke), + 'stroke': rgb2hex(stroke), + 'stroke-width': str(lw), + 'stroke-linecap': 'butt', + 'stroke-linejoin': 'miter' + } + if stroke[3] < 1: + hatch_style['stroke-opacity'] = str(stroke[3]) + writer.element( + 'path', + d=path_data, + style=_generate_css(hatch_style) + ) + writer.end('pattern') + writer.end('defs') + + def _get_style_dict(self, gc, rgbFace): + """Generate a style string from the GraphicsContext and rgbFace.""" + attrib = {} + + forced_alpha = gc.get_forced_alpha() + + if gc.get_hatch() is not None: + attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})" + if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0 + and not forced_alpha): + attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) + else: + if rgbFace is None: + attrib['fill'] = 'none' + else: + if tuple(rgbFace[:3]) != (0, 0, 0): + attrib['fill'] = rgb2hex(rgbFace) + if (len(rgbFace) == 4 and rgbFace[3] != 1.0 + and not forced_alpha): + attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) + + if forced_alpha and gc.get_alpha() != 1.0: + attrib['opacity'] = _short_float_fmt(gc.get_alpha()) + + offset, seq = gc.get_dashes() + if seq is not None: + attrib['stroke-dasharray'] = ','.join( + _short_float_fmt(val) for val in seq) + attrib['stroke-dashoffset'] = _short_float_fmt(float(offset)) + + linewidth = gc.get_linewidth() + if linewidth: + rgb = gc.get_rgb() + attrib['stroke'] = rgb2hex(rgb) + if not forced_alpha and rgb[3] != 1.0: + attrib['stroke-opacity'] = _short_float_fmt(rgb[3]) + if linewidth != 1.0: + attrib['stroke-width'] = _short_float_fmt(linewidth) + if gc.get_joinstyle() != 'round': + attrib['stroke-linejoin'] = gc.get_joinstyle() + if gc.get_capstyle() != 'butt': + attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()] + + return attrib + + def _get_style(self, gc, rgbFace): + return _generate_css(self._get_style_dict(gc, rgbFace)) + + def _get_clip_attrs(self, gc): + cliprect = gc.get_clip_rectangle() + clippath, clippath_trans = gc.get_clip_path() + if clippath is not None: + clippath_trans = self._make_flip_transform(clippath_trans) + dictkey = (self._get_clippath_id(clippath), str(clippath_trans)) + elif cliprect is not None: + x, y, w, h = cliprect.bounds + y = self.height-(y+h) + dictkey = (x, y, w, h) + else: + return {} + clip = self._clipd.get(dictkey) + if clip is None: + oid = self._make_id('p', dictkey) + if clippath is not None: + self._clipd[dictkey] = ((clippath, clippath_trans), oid) + else: + self._clipd[dictkey] = (dictkey, oid) + else: + _, oid = clip + return {'clip-path': f'url(#{oid})'} + + def _write_clips(self): + if not len(self._clipd): + return + writer = self.writer + writer.start('defs') + for clip, oid in self._clipd.values(): + writer.start('clipPath', id=oid) + if len(clip) == 2: + clippath, clippath_trans = clip + path_data = self._convert_path( + clippath, clippath_trans, simplify=False) + writer.element('path', d=path_data) + else: + x, y, w, h = clip + writer.element( + 'rect', + x=_short_float_fmt(x), + y=_short_float_fmt(y), + width=_short_float_fmt(w), + height=_short_float_fmt(h)) + writer.end('clipPath') + writer.end('defs') + + def open_group(self, s, gid=None): + # docstring inherited + if gid: + self.writer.start('g', id=gid) + else: + self._groupd[s] = self._groupd.get(s, 0) + 1 + self.writer.start('g', id=f"{s}_{self._groupd[s]:d}") + + def close_group(self, s): + # docstring inherited + self.writer.end('g') + + def option_image_nocomposite(self): + # docstring inherited + return not mpl.rcParams['image.composite_image'] + + def _convert_path(self, path, transform=None, clip=None, simplify=None, + sketch=None): + if clip: + clip = (0.0, 0.0, self.width, self.height) + else: + clip = None + return _path.convert_to_string( + path, transform, clip, simplify, sketch, 6, + [b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii') + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + trans_and_flip = self._make_flip_transform(transform) + clip = (rgbFace is None and gc.get_hatch_path() is None) + simplify = path.should_simplify and clip + path_data = self._convert_path( + path, trans_and_flip, clip=clip, simplify=simplify, + sketch=gc.get_sketch_params()) + + if gc.get_url() is not None: + self.writer.start('a', {'xlink:href': gc.get_url()}) + self.writer.element('path', d=path_data, **self._get_clip_attrs(gc), + style=self._get_style(gc, rgbFace)) + if gc.get_url() is not None: + self.writer.end('a') + + def draw_markers( + self, gc, marker_path, marker_trans, path, trans, rgbFace=None): + # docstring inherited + + if not len(path.vertices): + return + + writer = self.writer + path_data = self._convert_path( + marker_path, + marker_trans + Affine2D().scale(1.0, -1.0), + simplify=False) + style = self._get_style_dict(gc, rgbFace) + dictkey = (path_data, _generate_css(style)) + oid = self._markers.get(dictkey) + style = _generate_css({k: v for k, v in style.items() + if k.startswith('stroke')}) + + if oid is None: + oid = self._make_id('m', dictkey) + writer.start('defs') + writer.element('path', id=oid, d=path_data, style=style) + writer.end('defs') + self._markers[dictkey] = oid + + writer.start('g', **self._get_clip_attrs(gc)) + if gc.get_url() is not None: + self.writer.start('a', {'xlink:href': gc.get_url()}) + trans_and_flip = self._make_flip_transform(trans) + attrib = {'xlink:href': f'#{oid}'} + clip = (0, 0, self.width*72, self.height*72) + for vertices, code in path.iter_segments( + trans_and_flip, clip=clip, simplify=False): + if len(vertices): + x, y = vertices[-2:] + attrib['x'] = _short_float_fmt(x) + attrib['y'] = _short_float_fmt(y) + attrib['style'] = self._get_style(gc, rgbFace) + writer.element('use', attrib=attrib) + if gc.get_url() is not None: + self.writer.end('a') + writer.end('g') + + def draw_path_collection(self, gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position): + # Is the optimization worth it? Rough calculation: + # cost of emitting a path in-line is + # (len_path + 5) * uses_per_path + # cost of definition+use is + # (len_path + 3) + 9 * uses_per_path + len_path = len(paths[0].vertices) if len(paths) > 0 else 0 + uses_per_path = self._iter_collection_uses_per_path( + paths, all_transforms, offsets, facecolors, edgecolors) + should_do_optimization = \ + len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path + if not should_do_optimization: + return super().draw_path_collection( + gc, master_transform, paths, all_transforms, + offsets, offset_trans, facecolors, edgecolors, + linewidths, linestyles, antialiaseds, urls, + offset_position) + + writer = self.writer + path_codes = [] + writer.start('defs') + for i, (path, transform) in enumerate(self._iter_collection_raw_paths( + master_transform, paths, all_transforms)): + transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0) + d = self._convert_path(path, transform, simplify=False) + oid = 'C{:x}_{:x}_{}'.format( + self._path_collection_id, i, self._make_id('', d)) + writer.element('path', id=oid, d=d) + path_codes.append(oid) + writer.end('defs') + + for xo, yo, path_id, gc0, rgbFace in self._iter_collection( + gc, path_codes, offsets, offset_trans, + facecolors, edgecolors, linewidths, linestyles, + antialiaseds, urls, offset_position): + url = gc0.get_url() + if url is not None: + writer.start('a', attrib={'xlink:href': url}) + clip_attrs = self._get_clip_attrs(gc0) + if clip_attrs: + writer.start('g', **clip_attrs) + attrib = { + 'xlink:href': f'#{path_id}', + 'x': _short_float_fmt(xo), + 'y': _short_float_fmt(self.height - yo), + 'style': self._get_style(gc0, rgbFace) + } + writer.element('use', attrib=attrib) + if clip_attrs: + writer.end('g') + if url is not None: + writer.end('a') + + self._path_collection_id += 1 + + def _draw_gouraud_triangle(self, transformed_points, colors): + # This uses a method described here: + # + # http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html + # + # that uses three overlapping linear gradients to simulate a + # Gouraud triangle. Each gradient goes from fully opaque in + # one corner to fully transparent along the opposite edge. + # The line between the stop points is perpendicular to the + # opposite edge. Underlying these three gradients is a solid + # triangle whose color is the average of all three points. + + avg_color = np.average(colors, axis=0) + if avg_color[-1] == 0: + # Skip fully-transparent triangles + return + + writer = self.writer + writer.start('defs') + for i in range(3): + x1, y1 = transformed_points[i] + x2, y2 = transformed_points[(i + 1) % 3] + x3, y3 = transformed_points[(i + 2) % 3] + rgba_color = colors[i] + + if x2 == x3: + xb = x2 + yb = y1 + elif y2 == y3: + xb = x1 + yb = y2 + else: + m1 = (y2 - y3) / (x2 - x3) + b1 = y2 - (m1 * x2) + m2 = -(1.0 / m1) + b2 = y1 - (m2 * x1) + xb = (-b1 + b2) / (m1 - m2) + yb = m2 * xb + b2 + + writer.start( + 'linearGradient', + id=f"GR{self._n_gradients:x}_{i:d}", + gradientUnits="userSpaceOnUse", + x1=_short_float_fmt(x1), y1=_short_float_fmt(y1), + x2=_short_float_fmt(xb), y2=_short_float_fmt(yb)) + writer.element( + 'stop', + offset='1', + style=_generate_css({ + 'stop-color': rgb2hex(avg_color), + 'stop-opacity': _short_float_fmt(rgba_color[-1])})) + writer.element( + 'stop', + offset='0', + style=_generate_css({'stop-color': rgb2hex(rgba_color), + 'stop-opacity': "0"})) + + writer.end('linearGradient') + + writer.end('defs') + + # triangle formation using "path" + dpath = (f"M {_short_float_fmt(x1)},{_short_float_fmt(y1)}" + f" L {_short_float_fmt(x2)},{_short_float_fmt(y2)}" + f" {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z") + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': rgb2hex(avg_color), + 'fill-opacity': '1', + 'shape-rendering': "crispEdges"}) + + writer.start( + 'g', + attrib={'stroke': "none", + 'stroke-width': "0", + 'shape-rendering': "crispEdges", + 'filter': "url(#colorMat)"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_0)', + 'shape-rendering': "crispEdges"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_1)', + 'filter': 'url(#colorAdd)', + 'shape-rendering': "crispEdges"}) + + writer.element( + 'path', + attrib={'d': dpath, + 'fill': f'url(#GR{self._n_gradients:x}_2)', + 'filter': 'url(#colorAdd)', + 'shape-rendering': "crispEdges"}) + + writer.end('g') + + self._n_gradients += 1 + + def draw_gouraud_triangles(self, gc, triangles_array, colors_array, + transform): + writer = self.writer + writer.start('g', **self._get_clip_attrs(gc)) + transform = transform.frozen() + trans_and_flip = self._make_flip_transform(transform) + + if not self._has_gouraud: + self._has_gouraud = True + writer.start( + 'filter', + id='colorAdd') + writer.element( + 'feComposite', + attrib={'in': 'SourceGraphic'}, + in2='BackgroundImage', + operator='arithmetic', + k2="1", k3="1") + writer.end('filter') + # feColorMatrix filter to correct opacity + writer.start( + 'filter', + id='colorMat') + writer.element( + 'feColorMatrix', + attrib={'type': 'matrix'}, + values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ') + writer.end('filter') + + for points, colors in zip(triangles_array, colors_array): + self._draw_gouraud_triangle(trans_and_flip.transform(points), colors) + writer.end('g') + + def option_scale_image(self): + # docstring inherited + return True + + def get_image_magnification(self): + return self.image_dpi / 72.0 + + def draw_image(self, gc, x, y, im, transform=None): + # docstring inherited + + h, w = im.shape[:2] + + if w == 0 or h == 0: + return + + clip_attrs = self._get_clip_attrs(gc) + if clip_attrs: + # Can't apply clip-path directly to the image because the image has + # a transformation, which would also be applied to the clip-path. + self.writer.start('g', **clip_attrs) + + url = gc.get_url() + if url is not None: + self.writer.start('a', attrib={'xlink:href': url}) + + attrib = {} + oid = gc.get_gid() + if mpl.rcParams['svg.image_inline']: + buf = BytesIO() + Image.fromarray(im).save(buf, format="png") + oid = oid or self._make_id('image', buf.getvalue()) + attrib['xlink:href'] = ( + "data:image/png;base64,\n" + + base64.b64encode(buf.getvalue()).decode('ascii')) + else: + if self.basename is None: + raise ValueError("Cannot save image data to filesystem when " + "writing SVG to an in-memory buffer") + filename = f'{self.basename}.image{next(self._image_counter)}.png' + _log.info('Writing image file for inclusion: %s', filename) + Image.fromarray(im).save(filename) + oid = oid or 'Im_' + self._make_id('image', filename) + attrib['xlink:href'] = filename + attrib['id'] = oid + + if transform is None: + w = 72.0 * w / self.image_dpi + h = 72.0 * h / self.image_dpi + + self.writer.element( + 'image', + transform=_generate_transform([ + ('scale', (1, -1)), ('translate', (0, -h))]), + x=_short_float_fmt(x), + y=_short_float_fmt(-(self.height - y - h)), + width=_short_float_fmt(w), height=_short_float_fmt(h), + attrib=attrib) + else: + alpha = gc.get_alpha() + if alpha != 1.0: + attrib['opacity'] = _short_float_fmt(alpha) + + flipped = ( + Affine2D().scale(1.0 / w, 1.0 / h) + + transform + + Affine2D() + .translate(x, y) + .scale(1.0, -1.0) + .translate(0.0, self.height)) + + attrib['transform'] = _generate_transform( + [('matrix', flipped.frozen())]) + attrib['style'] = ( + 'image-rendering:crisp-edges;' + 'image-rendering:pixelated') + self.writer.element( + 'image', + width=_short_float_fmt(w), height=_short_float_fmt(h), + attrib=attrib) + + if url is not None: + self.writer.end('a') + if clip_attrs: + self.writer.end('g') + + def _update_glyph_map_defs(self, glyph_map_new): + """ + Emit definitions for not-yet-defined glyphs, and record them as having + been defined. + """ + writer = self.writer + if glyph_map_new: + writer.start('defs') + for char_id, (vertices, codes) in glyph_map_new.items(): + char_id = self._adjust_char_id(char_id) + # x64 to go back to FreeType's internal (integral) units. + path_data = self._convert_path( + Path(vertices * 64, codes), simplify=False) + writer.element( + 'path', id=char_id, d=path_data, + transform=_generate_transform([('scale', (1 / 64,))])) + writer.end('defs') + self._glyph_map.update(glyph_map_new) + + def _adjust_char_id(self, char_id): + return char_id.replace("%20", "_") + + def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None): + # docstring inherited + writer = self.writer + + writer.comment(s) + + glyph_map = self._glyph_map + + text2path = self._text2path + color = rgb2hex(gc.get_rgb()) + fontsize = prop.get_size_in_points() + + style = {} + if color != '#000000': + style['fill'] = color + alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] + if alpha != 1: + style['opacity'] = _short_float_fmt(alpha) + font_scale = fontsize / text2path.FONT_SCALE + attrib = { + 'style': _generate_css(style), + 'transform': _generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,)), + ('scale', (font_scale, -font_scale))]), + } + writer.start('g', attrib=attrib) + + if not ismath: + font = text2path._get_font(prop) + _glyphs = text2path.get_glyphs_with_font( + font, s, glyph_map=glyph_map, return_new_glyphs_only=True) + glyph_info, glyph_map_new, rects = _glyphs + self._update_glyph_map_defs(glyph_map_new) + + for glyph_id, xposition, yposition, scale in glyph_info: + writer.element( + 'use', + transform=_generate_transform([ + ('translate', (xposition, yposition)), + ('scale', (scale,)), + ]), + attrib={'xlink:href': f'#{glyph_id}'}) + + else: + if ismath == "TeX": + _glyphs = text2path.get_glyphs_tex( + prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) + else: + _glyphs = text2path.get_glyphs_mathtext( + prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) + glyph_info, glyph_map_new, rects = _glyphs + self._update_glyph_map_defs(glyph_map_new) + + for char_id, xposition, yposition, scale in glyph_info: + char_id = self._adjust_char_id(char_id) + writer.element( + 'use', + transform=_generate_transform([ + ('translate', (xposition, yposition)), + ('scale', (scale,)), + ]), + attrib={'xlink:href': f'#{char_id}'}) + + for verts, codes in rects: + path = Path(verts, codes) + path_data = self._convert_path(path, simplify=False) + writer.element('path', d=path_data) + + writer.end('g') + + def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): + # NOTE: If you change the font styling CSS, then be sure the check for + # svg.fonttype = none in `lib/matplotlib/testing/compare.py::convert` remains in + # sync. Also be sure to re-generate any SVG using this mode, or else such tests + # will fail to use the right converter for the expected images, and they will + # fail strangely. + writer = self.writer + + color = rgb2hex(gc.get_rgb()) + font_style = {} + color_style = {} + if color != '#000000': + color_style['fill'] = color + + alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] + if alpha != 1: + color_style['opacity'] = _short_float_fmt(alpha) + + if not ismath: + attrib = {} + + # Separate font style in their separate attributes + if prop.get_style() != 'normal': + font_style['font-style'] = prop.get_style() + if prop.get_variant() != 'normal': + font_style['font-variant'] = prop.get_variant() + weight = fm.weight_dict[prop.get_weight()] + if weight != 400: + font_style['font-weight'] = f'{weight}' + + def _normalize_sans(name): + return 'sans-serif' if name in ['sans', 'sans serif'] else name + + def _expand_family_entry(fn): + fn = _normalize_sans(fn) + # prepend generic font families with all configured font names + if fn in fm.font_family_aliases: + # get all of the font names and fix spelling of sans-serif + # (we accept 3 ways CSS only supports 1) + for name in fm.FontManager._expand_aliases(fn): + yield _normalize_sans(name) + # whether a generic name or a family name, it must appear at + # least once + yield fn + + def _get_all_quoted_names(prop): + # only quote specific names, not generic names + return [name if name in fm.font_family_aliases else repr(name) + for entry in prop.get_family() + for name in _expand_family_entry(entry)] + + font_style['font-size'] = f'{_short_float_fmt(prop.get_size())}px' + # ensure expansion, quoting, and dedupe of font names + font_style['font-family'] = ", ".join( + dict.fromkeys(_get_all_quoted_names(prop)) + ) + + if prop.get_stretch() != 'normal': + font_style['font-stretch'] = prop.get_stretch() + attrib['style'] = _generate_css({**font_style, **color_style}) + + if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"): + # If text anchoring can be supported, get the original + # coordinates and add alignment information. + + # Get anchor coordinates. + transform = mtext.get_transform() + ax, ay = transform.transform(mtext.get_unitless_position()) + ay = self.height - ay + + # Don't do vertical anchor alignment. Most applications do not + # support 'alignment-baseline' yet. Apply the vertical layout + # to the anchor point manually for now. + angle_rad = np.deg2rad(angle) + dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)]) + v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) + ax = ax + v_offset * dir_vert[0] + ay = ay + v_offset * dir_vert[1] + + ha_mpl_to_svg = {'left': 'start', 'right': 'end', + 'center': 'middle'} + font_style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()] + + attrib['x'] = _short_float_fmt(ax) + attrib['y'] = _short_float_fmt(ay) + attrib['style'] = _generate_css({**font_style, **color_style}) + attrib['transform'] = _generate_transform([ + ("rotate", (-angle, ax, ay))]) + + else: + attrib['transform'] = _generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,))]) + + writer.element('text', s, attrib=attrib) + + else: + writer.comment(s) + + width, height, descent, glyphs, rects = \ + self._text2path.mathtext_parser.parse(s, 72, prop) + + # Apply attributes to 'g', not 'text', because we likely have some + # rectangles as well with the same style and transformation. + writer.start('g', + style=_generate_css({**font_style, **color_style}), + transform=_generate_transform([ + ('translate', (x, y)), + ('rotate', (-angle,))]), + ) + + writer.start('text') + + # Sort the characters by font, and output one tspan for each. + spans = {} + for font, fontsize, thetext, new_x, new_y in glyphs: + entry = fm.ttfFontProperty(font) + font_style = {} + # Separate font style in its separate attributes + if entry.style != 'normal': + font_style['font-style'] = entry.style + if entry.variant != 'normal': + font_style['font-variant'] = entry.variant + if entry.weight != 400: + font_style['font-weight'] = f'{entry.weight}' + font_style['font-size'] = f'{_short_float_fmt(fontsize)}px' + font_style['font-family'] = f'{entry.name!r}' # ensure quoting + if entry.stretch != 'normal': + font_style['font-stretch'] = entry.stretch + style = _generate_css({**font_style, **color_style}) + if thetext == 32: + thetext = 0xa0 # non-breaking space + spans.setdefault(style, []).append((new_x, -new_y, thetext)) + + for style, chars in spans.items(): + chars.sort() # Sort by increasing x position + for x, y, t in chars: # Output one tspan for each character + writer.element( + 'tspan', + chr(t), + x=_short_float_fmt(x), + y=_short_float_fmt(y), + style=style) + + writer.end('text') + + for x, y, width, height in rects: + writer.element( + 'rect', + x=_short_float_fmt(x), + y=_short_float_fmt(-y-1), + width=_short_float_fmt(width), + height=_short_float_fmt(height) + ) + + writer.end('g') + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + clip_attrs = self._get_clip_attrs(gc) + if clip_attrs: + # Cannot apply clip-path directly to the text, because + # it has a transformation + self.writer.start('g', **clip_attrs) + + if gc.get_url() is not None: + self.writer.start('a', {'xlink:href': gc.get_url()}) + + if mpl.rcParams['svg.fonttype'] == 'path': + self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext) + else: + self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext) + + if gc.get_url() is not None: + self.writer.end('a') + + if clip_attrs: + self.writer.end('g') + + def flipy(self): + # docstring inherited + return True + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + return self._text2path.get_text_width_height_descent(s, prop, ismath) + + +class FigureCanvasSVG(FigureCanvasBase): + filetypes = {'svg': 'Scalable Vector Graphics', + 'svgz': 'Scalable Vector Graphics'} + + fixed_dpi = 72 + + def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None): + """ + Parameters + ---------- + filename : str or path-like or file-like + Output target; if a string, a file will be opened for writing. + + metadata : dict[str, Any], optional + Metadata in the SVG file defined as key-value pairs of strings, + datetimes, or lists of strings, e.g., ``{'Creator': 'My software', + 'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}``. + + The standard keys and their value types are: + + * *str*: ``'Coverage'``, ``'Description'``, ``'Format'``, + ``'Identifier'``, ``'Language'``, ``'Relation'``, ``'Source'``, + ``'Title'``, and ``'Type'``. + * *str* or *list of str*: ``'Contributor'``, ``'Creator'``, + ``'Keywords'``, ``'Publisher'``, and ``'Rights'``. + * *str*, *date*, *datetime*, or *tuple* of same: ``'Date'``. If a + non-*str*, then it will be formatted as ISO 8601. + + Values have been predefined for ``'Creator'``, ``'Date'``, + ``'Format'``, and ``'Type'``. They can be removed by setting them + to `None`. + + Information is encoded as `Dublin Core Metadata`__. + + .. _DC: https://www.dublincore.org/specifications/dublin-core/ + + __ DC_ + """ + with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh: + if not cbook.file_requires_unicode(fh): + fh = codecs.getwriter('utf-8')(fh) + dpi = self.figure.dpi + self.figure.dpi = 72 + width, height = self.figure.get_size_inches() + w, h = width * 72, height * 72 + renderer = MixedModeRenderer( + self.figure, width, height, dpi, + RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata), + bbox_inches_restore=bbox_inches_restore) + self.figure.draw(renderer) + renderer.finalize() + + def print_svgz(self, filename, **kwargs): + with (cbook.open_file_cm(filename, "wb") as fh, + gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter): + return self.print_svg(gzipwriter, **kwargs) + + def get_default_filetype(self): + return 'svg' + + def draw(self): + self.figure.draw_without_rendering() + return super().draw() + + +FigureManagerSVG = FigureManagerBase + + +svgProlog = """\ + + +""" + + +@_Backend.export +class _BackendSVG(_Backend): + backend_version = mpl.__version__ + FigureCanvas = FigureCanvasSVG diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_template.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_template.py new file mode 100644 index 0000000000000000000000000000000000000000..83aa6bb567c1c2519974253b6d50c52e84c4dfaf --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_template.py @@ -0,0 +1,213 @@ +""" +A fully functional, do-nothing backend intended as a template for backend +writers. It is fully functional in that you can select it as a backend e.g. +with :: + + import matplotlib + matplotlib.use("template") + +and your program will (should!) run without error, though no output is +produced. This provides a starting point for backend writers; you can +selectively implement drawing methods (`~.RendererTemplate.draw_path`, +`~.RendererTemplate.draw_image`, etc.) and slowly see your figure come to life +instead having to have a full-blown implementation before getting any results. + +Copy this file to a directory outside the Matplotlib source tree, somewhere +where Python can import it (by adding the directory to your ``sys.path`` or by +packaging it as a normal Python package); if the backend is importable as +``import my.backend`` you can then select it using :: + + import matplotlib + matplotlib.use("module://my.backend") + +If your backend implements support for saving figures (i.e. has a ``print_xyz`` method), +you can register it as the default handler for a given file type:: + + from matplotlib.backend_bases import register_backend + register_backend('xyz', 'my_backend', 'XYZ File Format') + ... + plt.savefig("figure.xyz") +""" + +from matplotlib import _api +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) +from matplotlib.figure import Figure + + +class RendererTemplate(RendererBase): + """ + The renderer handles drawing/rendering operations. + + This is a minimal do-nothing class that can be used to get started when + writing a new backend. Refer to `.backend_bases.RendererBase` for + documentation of the methods. + """ + + def __init__(self, dpi): + super().__init__() + self.dpi = dpi + + def draw_path(self, gc, path, transform, rgbFace=None): + pass + + # draw_markers is optional, and we get more correct relative + # timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_markers(self, gc, marker_path, marker_trans, path, trans, +# rgbFace=None): +# pass + + # draw_path_collection is optional, and we get more correct + # relative timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_path_collection(self, gc, master_transform, paths, +# all_transforms, offsets, offset_trans, +# facecolors, edgecolors, linewidths, linestyles, +# antialiaseds): +# pass + + # draw_quad_mesh is optional, and we get more correct + # relative timings by leaving it out. backend implementers concerned with + # performance will probably want to implement it +# def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, +# coordinates, offsets, offsetTrans, facecolors, +# antialiased, edgecolors): +# pass + + def draw_image(self, gc, x, y, im): + pass + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + pass + + def flipy(self): + # docstring inherited + return True + + def get_canvas_width_height(self): + # docstring inherited + return 100, 100 + + def get_text_width_height_descent(self, s, prop, ismath): + return 1, 1, 1 + + def new_gc(self): + # docstring inherited + return GraphicsContextTemplate() + + def points_to_pixels(self, points): + # if backend doesn't have dpi, e.g., postscript or svg + return points + # elif backend assumes a value for pixels_per_inch + # return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 + # else + # return points/72.0 * self.dpi.get() + + +class GraphicsContextTemplate(GraphicsContextBase): + """ + The graphics context provides the color, line styles, etc. See the cairo + and postscript backends for examples of mapping the graphics context + attributes (cap styles, join styles, line widths, colors) to a particular + backend. In cairo this is done by wrapping a cairo.Context object and + forwarding the appropriate calls to it using a dictionary mapping styles + to gdk constants. In Postscript, all the work is done by the renderer, + mapping line styles to postscript calls. + + If it's more appropriate to do the mapping at the renderer level (as in + the postscript backend), you don't need to override any of the GC methods. + If it's more appropriate to wrap an instance (as in the cairo backend) and + do the mapping here, you'll need to override several of the setter + methods. + + The base GraphicsContext stores colors as an RGB tuple on the unit + interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors + appropriate for your backend. + """ + + +######################################################################## +# +# The following functions and classes are for pyplot and implement +# window/figure managers, etc. +# +######################################################################## + + +class FigureManagerTemplate(FigureManagerBase): + """ + Helper class for pyplot mode, wraps everything up into a neat bundle. + + For non-interactive backends, the base class is sufficient. For + interactive backends, see the documentation of the `.FigureManagerBase` + class for the list of methods that can/should be overridden. + """ + + +class FigureCanvasTemplate(FigureCanvasBase): + """ + The canvas the figure renders into. Calls the draw and print fig + methods, creates the renderers, etc. + + Note: GUI templates will want to connect events for button presses, + mouse movements and key presses to functions that call the base + class methods button_press_event, button_release_event, + motion_notify_event, key_press_event, and key_release_event. See the + implementations of the interactive backends for examples. + + Attributes + ---------- + figure : `~matplotlib.figure.Figure` + A high-level Figure instance + """ + + # The instantiated manager class. For further customization, + # ``FigureManager.create_with_canvas`` can also be overridden; see the + # wx-based backends for an example. + manager_class = FigureManagerTemplate + + def draw(self): + """ + Draw the figure using the renderer. + + It is important that this method actually walk the artist tree + even if not output is produced because this will trigger + deferred work (like computing limits auto-limits and tick + values) that users may want access to before saving to disk. + """ + renderer = RendererTemplate(self.figure.dpi) + self.figure.draw(renderer) + + # You should provide a print_xxx function for every file format + # you can write. + + # If the file type is not in the base set of filetypes, + # you should add it to the class-scope filetypes dictionary as follows: + filetypes = {**FigureCanvasBase.filetypes, 'foo': 'My magic Foo format'} + + def print_foo(self, filename, **kwargs): + """ + Write out format foo. + + This method is normally called via `.Figure.savefig` and + `.FigureCanvasBase.print_figure`, which take care of setting the figure + facecolor, edgecolor, and dpi to the desired output values, and will + restore them to the original values. Therefore, `print_foo` does not + need to handle these settings. + """ + self.draw() + + def get_default_filetype(self): + return 'foo' + + +######################################################################## +# +# Now just provide the standard names that backend.__init__ is expecting +# +######################################################################## + +FigureCanvas = FigureCanvasTemplate +FigureManager = FigureManagerTemplate diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkagg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkagg.py new file mode 100644 index 0000000000000000000000000000000000000000..f95b6011eadffe72dfc1dc092f3d20b44fba24a9 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkagg.py @@ -0,0 +1,20 @@ +from . import _backend_tk +from .backend_agg import FigureCanvasAgg +from ._backend_tk import _BackendTk, FigureCanvasTk +from ._backend_tk import ( # noqa: F401 # pylint: disable=W0611 + FigureManagerTk, NavigationToolbar2Tk) + + +class FigureCanvasTkAgg(FigureCanvasAgg, FigureCanvasTk): + def draw(self): + super().draw() + self.blit() + + def blit(self, bbox=None): + _backend_tk.blit(self._tkphoto, self.renderer.buffer_rgba(), + (0, 1, 2, 3), bbox=bbox) + + +@_BackendTk.export +class _BackendTkAgg(_BackendTk): + FigureCanvas = FigureCanvasTkAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkcairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkcairo.py new file mode 100644 index 0000000000000000000000000000000000000000..a6951c03c65a328bc9c46a369aed65ad7df259bb --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_tkcairo.py @@ -0,0 +1,26 @@ +import sys + +import numpy as np + +from . import _backend_tk +from .backend_cairo import cairo, FigureCanvasCairo +from ._backend_tk import _BackendTk, FigureCanvasTk + + +class FigureCanvasTkCairo(FigureCanvasCairo, FigureCanvasTk): + def draw(self): + width = int(self.figure.bbox.width) + height = int(self.figure.bbox.height) + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) + self._renderer.set_context(cairo.Context(surface)) + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + buf = np.reshape(surface.get_data(), (height, width, 4)) + _backend_tk.blit( + self._tkphoto, buf, + (2, 1, 0, 3) if sys.byteorder == "little" else (1, 2, 3, 0)) + + +@_BackendTk.export +class _BackendTkCairo(_BackendTk): + FigureCanvas = FigureCanvasTkCairo diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc5747ef77cb4123d1a8d35657f22952d378df2 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg.py @@ -0,0 +1,328 @@ +"""Displays Agg images in the browser, with interactivity.""" + +# The WebAgg backend is divided into two modules: +# +# - `backend_webagg_core.py` contains code necessary to embed a WebAgg +# plot inside of a web application, and communicate in an abstract +# way over a web socket. +# +# - `backend_webagg.py` contains a concrete implementation of a basic +# application, implemented with tornado. + +from contextlib import contextmanager +import errno +from io import BytesIO +import json +import mimetypes +from pathlib import Path +import random +import sys +import signal +import threading + +try: + import tornado +except ImportError as err: + raise RuntimeError("The WebAgg backend requires Tornado.") from err + +import tornado.web +import tornado.ioloop +import tornado.websocket + +import matplotlib as mpl +from matplotlib.backend_bases import _Backend +from matplotlib._pylab_helpers import Gcf +from . import backend_webagg_core as core +from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611 + TimerAsyncio, TimerTornado) + + +webagg_server_thread = threading.Thread( + target=lambda: tornado.ioloop.IOLoop.instance().start()) + + +class FigureManagerWebAgg(core.FigureManagerWebAgg): + _toolbar2_class = core.NavigationToolbar2WebAgg + + @classmethod + def pyplot_show(cls, *, block=None): + WebAggApplication.initialize() + + url = "http://{address}:{port}{prefix}".format( + address=WebAggApplication.address, + port=WebAggApplication.port, + prefix=WebAggApplication.url_prefix) + + if mpl.rcParams['webagg.open_in_browser']: + import webbrowser + if not webbrowser.open(url): + print(f"To view figure, visit {url}") + else: + print(f"To view figure, visit {url}") + + WebAggApplication.start() + + +class FigureCanvasWebAgg(core.FigureCanvasWebAggCore): + manager_class = FigureManagerWebAgg + + +class WebAggApplication(tornado.web.Application): + initialized = False + started = False + + class FavIcon(tornado.web.RequestHandler): + def get(self): + self.set_header('Content-Type', 'image/png') + self.write(Path(mpl.get_data_path(), + 'images/matplotlib.png').read_bytes()) + + class SingleFigurePage(tornado.web.RequestHandler): + def __init__(self, application, request, *, url_prefix='', **kwargs): + self.url_prefix = url_prefix + super().__init__(application, request, **kwargs) + + def get(self, fignum): + fignum = int(fignum) + manager = Gcf.get_fig_manager(fignum) + + ws_uri = f'ws://{self.request.host}{self.url_prefix}/' + self.render( + "single_figure.html", + prefix=self.url_prefix, + ws_uri=ws_uri, + fig_id=fignum, + toolitems=core.NavigationToolbar2WebAgg.toolitems, + canvas=manager.canvas) + + class AllFiguresPage(tornado.web.RequestHandler): + def __init__(self, application, request, *, url_prefix='', **kwargs): + self.url_prefix = url_prefix + super().__init__(application, request, **kwargs) + + def get(self): + ws_uri = f'ws://{self.request.host}{self.url_prefix}/' + self.render( + "all_figures.html", + prefix=self.url_prefix, + ws_uri=ws_uri, + figures=sorted(Gcf.figs.items()), + toolitems=core.NavigationToolbar2WebAgg.toolitems) + + class MplJs(tornado.web.RequestHandler): + def get(self): + self.set_header('Content-Type', 'application/javascript') + + js_content = core.FigureManagerWebAgg.get_javascript() + + self.write(js_content) + + class Download(tornado.web.RequestHandler): + def get(self, fignum, fmt): + fignum = int(fignum) + manager = Gcf.get_fig_manager(fignum) + self.set_header( + 'Content-Type', mimetypes.types_map.get(fmt, 'binary')) + buff = BytesIO() + manager.canvas.figure.savefig(buff, format=fmt) + self.write(buff.getvalue()) + + class WebSocket(tornado.websocket.WebSocketHandler): + supports_binary = True + + def open(self, fignum): + self.fignum = int(fignum) + self.manager = Gcf.get_fig_manager(self.fignum) + self.manager.add_web_socket(self) + if hasattr(self, 'set_nodelay'): + self.set_nodelay(True) + + def on_close(self): + self.manager.remove_web_socket(self) + + def on_message(self, message): + message = json.loads(message) + # The 'supports_binary' message is on a client-by-client + # basis. The others affect the (shared) canvas as a + # whole. + if message['type'] == 'supports_binary': + self.supports_binary = message['value'] + else: + manager = Gcf.get_fig_manager(self.fignum) + # It is possible for a figure to be closed, + # but a stale figure UI is still sending messages + # from the browser. + if manager is not None: + manager.handle_json(message) + + def send_json(self, content): + self.write_message(json.dumps(content)) + + def send_binary(self, blob): + if self.supports_binary: + self.write_message(blob, binary=True) + else: + data_uri = "data:image/png;base64,{}".format( + blob.encode('base64').replace('\n', '')) + self.write_message(data_uri) + + def __init__(self, url_prefix=''): + if url_prefix: + assert url_prefix[0] == '/' and url_prefix[-1] != '/', \ + 'url_prefix must start with a "/" and not end with one.' + + super().__init__( + [ + # Static files for the CSS and JS + (url_prefix + r'/_static/(.*)', + tornado.web.StaticFileHandler, + {'path': core.FigureManagerWebAgg.get_static_file_path()}), + + # Static images for the toolbar + (url_prefix + r'/_images/(.*)', + tornado.web.StaticFileHandler, + {'path': Path(mpl.get_data_path(), 'images')}), + + # A Matplotlib favicon + (url_prefix + r'/favicon.ico', self.FavIcon), + + # The page that contains all of the pieces + (url_prefix + r'/([0-9]+)', self.SingleFigurePage, + {'url_prefix': url_prefix}), + + # The page that contains all of the figures + (url_prefix + r'/?', self.AllFiguresPage, + {'url_prefix': url_prefix}), + + (url_prefix + r'/js/mpl.js', self.MplJs), + + # Sends images and events to the browser, and receives + # events from the browser + (url_prefix + r'/([0-9]+)/ws', self.WebSocket), + + # Handles the downloading (i.e., saving) of static images + (url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)', + self.Download), + ], + template_path=core.FigureManagerWebAgg.get_static_file_path()) + + @classmethod + def initialize(cls, url_prefix='', port=None, address=None): + if cls.initialized: + return + + # Create the class instance + app = cls(url_prefix=url_prefix) + + cls.url_prefix = url_prefix + + # This port selection algorithm is borrowed, more or less + # verbatim, from IPython. + def random_ports(port, n): + """ + Generate a list of n random ports near the given port. + + The first 5 ports will be sequential, and the remaining n-5 will be + randomly selected in the range [port-2*n, port+2*n]. + """ + for i in range(min(5, n)): + yield port + i + for i in range(n - 5): + yield port + random.randint(-2 * n, 2 * n) + + if address is None: + cls.address = mpl.rcParams['webagg.address'] + else: + cls.address = address + cls.port = mpl.rcParams['webagg.port'] + for port in random_ports(cls.port, + mpl.rcParams['webagg.port_retries']): + try: + app.listen(port, cls.address) + except OSError as e: + if e.errno != errno.EADDRINUSE: + raise + else: + cls.port = port + break + else: + raise SystemExit( + "The webagg server could not be started because an available " + "port could not be found") + + cls.initialized = True + + @classmethod + def start(cls): + import asyncio + try: + asyncio.get_running_loop() + except RuntimeError: + pass + else: + cls.started = True + + if cls.started: + return + + """ + IOLoop.running() was removed as of Tornado 2.4; see for example + https://groups.google.com/forum/#!topic/python-tornado/QLMzkpQBGOY + Thus there is no correct way to check if the loop has already been + launched. We may end up with two concurrently running loops in that + unlucky case with all the expected consequences. + """ + ioloop = tornado.ioloop.IOLoop.instance() + + def shutdown(): + ioloop.stop() + print("Server is stopped") + sys.stdout.flush() + cls.started = False + + @contextmanager + def catch_sigint(): + old_handler = signal.signal( + signal.SIGINT, + lambda sig, frame: ioloop.add_callback_from_signal(shutdown)) + try: + yield + finally: + signal.signal(signal.SIGINT, old_handler) + + # Set the flag to True *before* blocking on ioloop.start() + cls.started = True + + print("Press Ctrl+C to stop WebAgg server") + sys.stdout.flush() + with catch_sigint(): + ioloop.start() + + +def ipython_inline_display(figure): + import tornado.template + + WebAggApplication.initialize() + import asyncio + try: + asyncio.get_running_loop() + except RuntimeError: + if not webagg_server_thread.is_alive(): + webagg_server_thread.start() + + fignum = figure.number + tpl = Path(core.FigureManagerWebAgg.get_static_file_path(), + "ipython_inline_figure.html").read_text() + t = tornado.template.Template(tpl) + return t.generate( + prefix=WebAggApplication.url_prefix, + fig_id=fignum, + toolitems=core.NavigationToolbar2WebAgg.toolitems, + canvas=figure.canvas, + port=WebAggApplication.port).decode('utf-8') + + +@_Backend.export +class _BackendWebAgg(_Backend): + FigureCanvas = FigureCanvasWebAgg + FigureManager = FigureManagerWebAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg_core.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg_core.py new file mode 100644 index 0000000000000000000000000000000000000000..12906827a4663deb6c927e25dfc9127878bf1897 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_webagg_core.py @@ -0,0 +1,527 @@ +"""Displays Agg images in the browser, with interactivity.""" +# The WebAgg backend is divided into two modules: +# +# - `backend_webagg_core.py` contains code necessary to embed a WebAgg +# plot inside of a web application, and communicate in an abstract +# way over a web socket. +# +# - `backend_webagg.py` contains a concrete implementation of a basic +# application, implemented with asyncio. + +import asyncio +import datetime +from io import BytesIO, StringIO +import json +import logging +import os +from pathlib import Path + +import numpy as np +from PIL import Image + +from matplotlib import _api, backend_bases, backend_tools +from matplotlib.backends import backend_agg +from matplotlib.backend_bases import ( + _Backend, MouseButton, KeyEvent, LocationEvent, MouseEvent, ResizeEvent) + +_log = logging.getLogger(__name__) + +_SPECIAL_KEYS_LUT = {'Alt': 'alt', + 'AltGraph': 'alt', + 'CapsLock': 'caps_lock', + 'Control': 'control', + 'Meta': 'meta', + 'NumLock': 'num_lock', + 'ScrollLock': 'scroll_lock', + 'Shift': 'shift', + 'Super': 'super', + 'Enter': 'enter', + 'Tab': 'tab', + 'ArrowDown': 'down', + 'ArrowLeft': 'left', + 'ArrowRight': 'right', + 'ArrowUp': 'up', + 'End': 'end', + 'Home': 'home', + 'PageDown': 'pagedown', + 'PageUp': 'pageup', + 'Backspace': 'backspace', + 'Delete': 'delete', + 'Insert': 'insert', + 'Escape': 'escape', + 'Pause': 'pause', + 'Select': 'select', + 'Dead': 'dead', + 'F1': 'f1', + 'F2': 'f2', + 'F3': 'f3', + 'F4': 'f4', + 'F5': 'f5', + 'F6': 'f6', + 'F7': 'f7', + 'F8': 'f8', + 'F9': 'f9', + 'F10': 'f10', + 'F11': 'f11', + 'F12': 'f12'} + + +def _handle_key(key): + """Handle key values""" + value = key[key.index('k') + 1:] + if 'shift+' in key: + if len(value) == 1: + key = key.replace('shift+', '') + if value in _SPECIAL_KEYS_LUT: + value = _SPECIAL_KEYS_LUT[value] + key = key[:key.index('k')] + value + return key + + +class TimerTornado(backend_bases.TimerBase): + def __init__(self, *args, **kwargs): + self._timer = None + super().__init__(*args, **kwargs) + + def _timer_start(self): + import tornado + + self._timer_stop() + if self._single: + ioloop = tornado.ioloop.IOLoop.instance() + self._timer = ioloop.add_timeout( + datetime.timedelta(milliseconds=self.interval), + self._on_timer) + else: + self._timer = tornado.ioloop.PeriodicCallback( + self._on_timer, + max(self.interval, 1e-6)) + self._timer.start() + + def _timer_stop(self): + import tornado + + if self._timer is None: + return + elif self._single: + ioloop = tornado.ioloop.IOLoop.instance() + ioloop.remove_timeout(self._timer) + else: + self._timer.stop() + self._timer = None + + def _timer_set_interval(self): + # Only stop and restart it if the timer has already been started + if self._timer is not None: + self._timer_stop() + self._timer_start() + + +class TimerAsyncio(backend_bases.TimerBase): + def __init__(self, *args, **kwargs): + self._task = None + super().__init__(*args, **kwargs) + + async def _timer_task(self, interval): + while True: + try: + await asyncio.sleep(interval) + self._on_timer() + + if self._single: + break + except asyncio.CancelledError: + break + + def _timer_start(self): + self._timer_stop() + + self._task = asyncio.ensure_future( + self._timer_task(max(self.interval / 1_000., 1e-6)) + ) + + def _timer_stop(self): + if self._task is not None: + self._task.cancel() + self._task = None + + def _timer_set_interval(self): + # Only stop and restart it if the timer has already been started + if self._task is not None: + self._timer_stop() + self._timer_start() + + +class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg): + manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg) + _timer_cls = TimerAsyncio + # Webagg and friends having the right methods, but still + # having bugs in practice. Do not advertise that it works until + # we can debug this. + supports_blit = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Set to True when the renderer contains data that is newer + # than the PNG buffer. + self._png_is_old = True + # Set to True by the `refresh` message so that the next frame + # sent to the clients will be a full frame. + self._force_full = True + # The last buffer, for diff mode. + self._last_buff = np.empty((0, 0)) + # Store the current image mode so that at any point, clients can + # request the information. This should be changed by calling + # self.set_image_mode(mode) so that the notification can be given + # to the connected clients. + self._current_image_mode = 'full' + # Track mouse events to fill in the x, y position of key events. + self._last_mouse_xy = (None, None) + + def show(self): + # show the figure window + from matplotlib.pyplot import show + show() + + def draw(self): + self._png_is_old = True + try: + super().draw() + finally: + self.manager.refresh_all() # Swap the frames. + + def blit(self, bbox=None): + self._png_is_old = True + self.manager.refresh_all() + + def draw_idle(self): + self.send_event("draw") + + def set_cursor(self, cursor): + # docstring inherited + cursor = _api.check_getitem({ + backend_tools.Cursors.HAND: 'pointer', + backend_tools.Cursors.POINTER: 'default', + backend_tools.Cursors.SELECT_REGION: 'crosshair', + backend_tools.Cursors.MOVE: 'move', + backend_tools.Cursors.WAIT: 'wait', + backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize', + backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize', + }, cursor=cursor) + self.send_event('cursor', cursor=cursor) + + def set_image_mode(self, mode): + """ + Set the image mode for any subsequent images which will be sent + to the clients. The modes may currently be either 'full' or 'diff'. + + Note: diff images may not contain transparency, therefore upon + draw this mode may be changed if the resulting image has any + transparent component. + """ + _api.check_in_list(['full', 'diff'], mode=mode) + if self._current_image_mode != mode: + self._current_image_mode = mode + self.handle_send_image_mode(None) + + def get_diff_image(self): + if self._png_is_old: + renderer = self.get_renderer() + + pixels = np.asarray(renderer.buffer_rgba()) + # The buffer is created as type uint32 so that entire + # pixels can be compared in one numpy call, rather than + # needing to compare each plane separately. + buff = pixels.view(np.uint32).squeeze(2) + + if (self._force_full + # If the buffer has changed size we need to do a full draw. + or buff.shape != self._last_buff.shape + # If any pixels have transparency, we need to force a full + # draw as we cannot overlay new on top of old. + or (pixels[:, :, 3] != 255).any()): + self.set_image_mode('full') + output = buff + else: + self.set_image_mode('diff') + diff = buff != self._last_buff + output = np.where(diff, buff, 0) + + # Store the current buffer so we can compute the next diff. + self._last_buff = buff.copy() + self._force_full = False + self._png_is_old = False + + data = output.view(dtype=np.uint8).reshape((*output.shape, 4)) + with BytesIO() as png: + Image.fromarray(data).save(png, format="png") + return png.getvalue() + + def handle_event(self, event): + e_type = event['type'] + handler = getattr(self, f'handle_{e_type}', + self.handle_unknown_event) + return handler(event) + + def handle_unknown_event(self, event): + _log.warning('Unhandled message type %s. %s', event["type"], event) + + def handle_ack(self, event): + # Network latency tends to decrease if traffic is flowing + # in both directions. Therefore, the browser sends back + # an "ack" message after each image frame is received. + # This could also be used as a simple sanity check in the + # future, but for now the performance increase is enough + # to justify it, even if the server does nothing with it. + pass + + def handle_draw(self, event): + self.draw() + + def _handle_mouse(self, event): + x = event['x'] + y = event['y'] + y = self.get_renderer().height - y + self._last_mouse_xy = x, y + e_type = event['type'] + button = event['button'] + 1 # JS numbers off by 1 compared to mpl. + buttons = { # JS ordering different compared to mpl. + button for button, mask in [ + (MouseButton.LEFT, 1), + (MouseButton.RIGHT, 2), + (MouseButton.MIDDLE, 4), + (MouseButton.BACK, 8), + (MouseButton.FORWARD, 16), + ] if event['buttons'] & mask # State *after* press/release. + } + modifiers = event['modifiers'] + guiEvent = event.get('guiEvent') + if e_type in ['button_press', 'button_release']: + MouseEvent(e_type + '_event', self, x, y, button, + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'dblclick': + MouseEvent('button_press_event', self, x, y, button, dblclick=True, + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'scroll': + MouseEvent('scroll_event', self, x, y, step=event['step'], + modifiers=modifiers, guiEvent=guiEvent)._process() + elif e_type == 'motion_notify': + MouseEvent(e_type + '_event', self, x, y, + buttons=buttons, modifiers=modifiers, guiEvent=guiEvent, + )._process() + elif e_type in ['figure_enter', 'figure_leave']: + LocationEvent(e_type + '_event', self, x, y, + modifiers=modifiers, guiEvent=guiEvent)._process() + + handle_button_press = handle_button_release = handle_dblclick = \ + handle_figure_enter = handle_figure_leave = handle_motion_notify = \ + handle_scroll = _handle_mouse + + def _handle_key(self, event): + KeyEvent(event['type'] + '_event', self, + _handle_key(event['key']), *self._last_mouse_xy, + guiEvent=event.get('guiEvent'))._process() + handle_key_press = handle_key_release = _handle_key + + def handle_toolbar_button(self, event): + # TODO: Be more suspicious of the input + getattr(self.toolbar, event['name'])() + + def handle_refresh(self, event): + figure_label = self.figure.get_label() + if not figure_label: + figure_label = f"Figure {self.manager.num}" + self.send_event('figure_label', label=figure_label) + self._force_full = True + if self.toolbar: + # Normal toolbar init would refresh this, but it happens before the + # browser canvas is set up. + self.toolbar.set_history_buttons() + self.draw_idle() + + def handle_resize(self, event): + x = int(event.get('width', 800)) * self.device_pixel_ratio + y = int(event.get('height', 800)) * self.device_pixel_ratio + fig = self.figure + # An attempt at approximating the figure size in pixels. + fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False) + # Acknowledge the resize, and force the viewer to update the + # canvas size to the figure's new size (which is hopefully + # identical or within a pixel or so). + self._png_is_old = True + self.manager.resize(*fig.bbox.size, forward=False) + ResizeEvent('resize_event', self)._process() + self.draw_idle() + + def handle_send_image_mode(self, event): + # The client requests notification of what the current image mode is. + self.send_event('image_mode', mode=self._current_image_mode) + + def handle_set_device_pixel_ratio(self, event): + self._handle_set_device_pixel_ratio(event.get('device_pixel_ratio', 1)) + + def handle_set_dpi_ratio(self, event): + # This handler is for backwards-compatibility with older ipympl. + self._handle_set_device_pixel_ratio(event.get('dpi_ratio', 1)) + + def _handle_set_device_pixel_ratio(self, device_pixel_ratio): + if self._set_device_pixel_ratio(device_pixel_ratio): + self._force_full = True + self.draw_idle() + + def send_event(self, event_type, **kwargs): + if self.manager: + self.manager._send_event(event_type, **kwargs) + + +_ALLOWED_TOOL_ITEMS = { + 'home', + 'back', + 'forward', + 'pan', + 'zoom', + 'download', + None, +} + + +class NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2): + + # Use the standard toolbar items + download button + toolitems = [ + (text, tooltip_text, image_file, name_of_method) + for text, tooltip_text, image_file, name_of_method + in (*backend_bases.NavigationToolbar2.toolitems, + ('Download', 'Download plot', 'filesave', 'download')) + if name_of_method in _ALLOWED_TOOL_ITEMS + ] + + def __init__(self, canvas): + self.message = '' + super().__init__(canvas) + + def set_message(self, message): + if message != self.message: + self.canvas.send_event("message", message=message) + self.message = message + + def draw_rubberband(self, event, x0, y0, x1, y1): + self.canvas.send_event("rubberband", x0=x0, y0=y0, x1=x1, y1=y1) + + def remove_rubberband(self): + self.canvas.send_event("rubberband", x0=-1, y0=-1, x1=-1, y1=-1) + + def save_figure(self, *args): + """Save the current figure.""" + self.canvas.send_event('save') + return self.UNKNOWN_SAVED_STATUS + + def pan(self): + super().pan() + self.canvas.send_event('navigate_mode', mode=self.mode.name) + + def zoom(self): + super().zoom() + self.canvas.send_event('navigate_mode', mode=self.mode.name) + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + self.canvas.send_event('history_buttons', + Back=can_backward, Forward=can_forward) + + +class FigureManagerWebAgg(backend_bases.FigureManagerBase): + # This must be None to not break ipympl + _toolbar2_class = None + ToolbarCls = NavigationToolbar2WebAgg + _window_title = "Matplotlib" + + def __init__(self, canvas, num): + self.web_sockets = set() + super().__init__(canvas, num) + + def show(self): + pass + + def resize(self, w, h, forward=True): + self._send_event( + 'resize', + size=(w / self.canvas.device_pixel_ratio, + h / self.canvas.device_pixel_ratio), + forward=forward) + + def set_window_title(self, title): + self._send_event('figure_label', label=title) + self._window_title = title + + def get_window_title(self): + return self._window_title + + # The following methods are specific to FigureManagerWebAgg + + def add_web_socket(self, web_socket): + assert hasattr(web_socket, 'send_binary') + assert hasattr(web_socket, 'send_json') + self.web_sockets.add(web_socket) + self.resize(*self.canvas.figure.bbox.size) + self._send_event('refresh') + + def remove_web_socket(self, web_socket): + self.web_sockets.remove(web_socket) + + def handle_json(self, content): + self.canvas.handle_event(content) + + def refresh_all(self): + if self.web_sockets: + diff = self.canvas.get_diff_image() + if diff is not None: + for s in self.web_sockets: + s.send_binary(diff) + + @classmethod + def get_javascript(cls, stream=None): + if stream is None: + output = StringIO() + else: + output = stream + + output.write((Path(__file__).parent / "web_backend/js/mpl.js") + .read_text(encoding="utf-8")) + + toolitems = [] + for name, tooltip, image, method in cls.ToolbarCls.toolitems: + if name is None: + toolitems.append(['', '', '', '']) + else: + toolitems.append([name, tooltip, image, method]) + output.write(f"mpl.toolbar_items = {json.dumps(toolitems)};\n\n") + + extensions = [] + for filetype, ext in sorted(FigureCanvasWebAggCore. + get_supported_filetypes_grouped(). + items()): + extensions.append(ext[0]) + output.write(f"mpl.extensions = {json.dumps(extensions)};\n\n") + + output.write("mpl.default_extension = {};".format( + json.dumps(FigureCanvasWebAggCore.get_default_filetype()))) + + if stream is None: + return output.getvalue() + + @classmethod + def get_static_file_path(cls): + return os.path.join(os.path.dirname(__file__), 'web_backend') + + def _send_event(self, event_type, **kwargs): + payload = {'type': event_type, **kwargs} + for s in self.web_sockets: + s.send_json(payload) + + +@_Backend.export +class _BackendWebAggCoreAgg(_Backend): + FigureCanvas = FigureCanvasWebAggCore + FigureManager = FigureManagerWebAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_wx.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wx.py new file mode 100644 index 0000000000000000000000000000000000000000..f83a69d8361e74e7cc05853535155661ec71878a --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wx.py @@ -0,0 +1,1381 @@ +""" +A wxPython backend for matplotlib. + +Originally contributed by Jeremy O'Donoghue (jeremy@o-donoghue.com) and John +Hunter (jdhunter@ace.bsd.uchicago.edu). + +Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4. +""" + +import functools +import logging +import math +import pathlib +import sys +import weakref + +import numpy as np +import PIL.Image + +import matplotlib as mpl +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, + GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase, + TimerBase, ToolContainerBase, cursors, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent) + +from matplotlib import _api, cbook, backend_tools, _c_internal_utils +from matplotlib._pylab_helpers import Gcf +from matplotlib.path import Path +from matplotlib.transforms import Affine2D + +import wx +import wx.svg + +_log = logging.getLogger(__name__) + +# the True dots per inch on the screen; should be display dependent; see +# http://groups.google.com/d/msg/comp.lang.postscript/-/omHAc9FEuAsJ?hl=en +# for some info about screen dpi +PIXELS_PER_INCH = 75 + + +# lru_cache holds a reference to the App and prevents it from being gc'ed. +@functools.lru_cache(1) +def _create_wxapp(): + wxapp = wx.App(False) + wxapp.SetExitOnFrameDelete(True) + cbook._setup_new_guiapp() + # Set per-process DPI awareness. This is a NoOp except in MSW + _c_internal_utils.Win32_SetProcessDpiAwareness_max() + return wxapp + + +class TimerWx(TimerBase): + """Subclass of `.TimerBase` using wx.Timer events.""" + + def __init__(self, *args, **kwargs): + self._timer = wx.Timer() + self._timer.Notify = self._on_timer + super().__init__(*args, **kwargs) + + def _timer_start(self): + self._timer.Start(self._interval, self._single) + + def _timer_stop(self): + self._timer.Stop() + + def _timer_set_interval(self): + if self._timer.IsRunning(): + self._timer_start() # Restart with new interval. + + +@_api.deprecated( + "2.0", name="wx", obj_type="backend", removal="the future", + alternative="wxagg", + addendum="See the Matplotlib usage FAQ for more info on backends.") +class RendererWx(RendererBase): + """ + The renderer handles all the drawing primitives using a graphics + context instance that controls the colors/styles. It acts as the + 'renderer' instance used by many classes in the hierarchy. + """ + # In wxPython, drawing is performed on a wxDC instance, which will + # generally be mapped to the client area of the window displaying + # the plot. Under wxPython, the wxDC instance has a wx.Pen which + # describes the colour and weight of any lines drawn, and a wxBrush + # which describes the fill colour of any closed polygon. + + # Font styles, families and weight. + fontweights = { + 100: wx.FONTWEIGHT_LIGHT, + 200: wx.FONTWEIGHT_LIGHT, + 300: wx.FONTWEIGHT_LIGHT, + 400: wx.FONTWEIGHT_NORMAL, + 500: wx.FONTWEIGHT_NORMAL, + 600: wx.FONTWEIGHT_NORMAL, + 700: wx.FONTWEIGHT_BOLD, + 800: wx.FONTWEIGHT_BOLD, + 900: wx.FONTWEIGHT_BOLD, + 'ultralight': wx.FONTWEIGHT_LIGHT, + 'light': wx.FONTWEIGHT_LIGHT, + 'normal': wx.FONTWEIGHT_NORMAL, + 'medium': wx.FONTWEIGHT_NORMAL, + 'semibold': wx.FONTWEIGHT_NORMAL, + 'bold': wx.FONTWEIGHT_BOLD, + 'heavy': wx.FONTWEIGHT_BOLD, + 'ultrabold': wx.FONTWEIGHT_BOLD, + 'black': wx.FONTWEIGHT_BOLD, + } + fontangles = { + 'italic': wx.FONTSTYLE_ITALIC, + 'normal': wx.FONTSTYLE_NORMAL, + 'oblique': wx.FONTSTYLE_SLANT, + } + + # wxPython allows for portable font styles, choosing them appropriately for + # the target platform. Map some standard font names to the portable styles. + # QUESTION: Is it wise to agree to standard fontnames across all backends? + fontnames = { + 'Sans': wx.FONTFAMILY_SWISS, + 'Roman': wx.FONTFAMILY_ROMAN, + 'Script': wx.FONTFAMILY_SCRIPT, + 'Decorative': wx.FONTFAMILY_DECORATIVE, + 'Modern': wx.FONTFAMILY_MODERN, + 'Courier': wx.FONTFAMILY_MODERN, + 'courier': wx.FONTFAMILY_MODERN, + } + + def __init__(self, bitmap, dpi): + """Initialise a wxWindows renderer instance.""" + super().__init__() + _log.debug("%s - __init__()", type(self)) + self.width = bitmap.GetWidth() + self.height = bitmap.GetHeight() + self.bitmap = bitmap + self.fontd = {} + self.dpi = dpi + self.gc = None + + def flipy(self): + # docstring inherited + return True + + def get_text_width_height_descent(self, s, prop, ismath): + # docstring inherited + + if ismath: + s = cbook.strip_math(s) + + if self.gc is None: + gc = self.new_gc() + else: + gc = self.gc + gfx_ctx = gc.gfx_ctx + font = self.get_wx_font(s, prop) + gfx_ctx.SetFont(font, wx.BLACK) + w, h, descent, leading = gfx_ctx.GetFullTextExtent(s) + + return w, h, descent + + def get_canvas_width_height(self): + # docstring inherited + return self.width, self.height + + def handle_clip_rectangle(self, gc): + new_bounds = gc.get_clip_rectangle() + if new_bounds is not None: + new_bounds = new_bounds.bounds + gfx_ctx = gc.gfx_ctx + if gfx_ctx._lastcliprect != new_bounds: + gfx_ctx._lastcliprect = new_bounds + if new_bounds is None: + gfx_ctx.ResetClip() + else: + gfx_ctx.Clip(new_bounds[0], + self.height - new_bounds[1] - new_bounds[3], + new_bounds[2], new_bounds[3]) + + @staticmethod + def convert_path(gfx_ctx, path, transform): + wxpath = gfx_ctx.CreatePath() + for points, code in path.iter_segments(transform): + if code == Path.MOVETO: + wxpath.MoveToPoint(*points) + elif code == Path.LINETO: + wxpath.AddLineToPoint(*points) + elif code == Path.CURVE3: + wxpath.AddQuadCurveToPoint(*points) + elif code == Path.CURVE4: + wxpath.AddCurveToPoint(*points) + elif code == Path.CLOSEPOLY: + wxpath.CloseSubpath() + return wxpath + + def draw_path(self, gc, path, transform, rgbFace=None): + # docstring inherited + gc.select() + self.handle_clip_rectangle(gc) + gfx_ctx = gc.gfx_ctx + transform = transform + \ + Affine2D().scale(1.0, -1.0).translate(0.0, self.height) + wxpath = self.convert_path(gfx_ctx, path, transform) + if rgbFace is not None: + gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace))) + gfx_ctx.DrawPath(wxpath) + else: + gfx_ctx.StrokePath(wxpath) + gc.unselect() + + def draw_image(self, gc, x, y, im): + bbox = gc.get_clip_rectangle() + if bbox is not None: + l, b, w, h = bbox.bounds + else: + l = 0 + b = 0 + w = self.width + h = self.height + rows, cols = im.shape[:2] + bitmap = wx.Bitmap.FromBufferRGBA(cols, rows, im.tobytes()) + gc.select() + gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b), + int(w), int(-h)) + gc.unselect() + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): + # docstring inherited + + if ismath: + s = cbook.strip_math(s) + _log.debug("%s - draw_text()", type(self)) + gc.select() + self.handle_clip_rectangle(gc) + gfx_ctx = gc.gfx_ctx + + font = self.get_wx_font(s, prop) + color = gc.get_wxcolour(gc.get_rgb()) + gfx_ctx.SetFont(font, color) + + w, h, d = self.get_text_width_height_descent(s, prop, ismath) + x = int(x) + y = int(y - h) + + if angle == 0.0: + gfx_ctx.DrawText(s, x, y) + else: + rads = math.radians(angle) + xo = h * math.sin(rads) + yo = h * math.cos(rads) + gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads) + + gc.unselect() + + def new_gc(self): + # docstring inherited + _log.debug("%s - new_gc()", type(self)) + self.gc = GraphicsContextWx(self.bitmap, self) + self.gc.select() + self.gc.unselect() + return self.gc + + def get_wx_font(self, s, prop): + """Return a wx font. Cache font instances for efficiency.""" + _log.debug("%s - get_wx_font()", type(self)) + key = hash(prop) + font = self.fontd.get(key) + if font is not None: + return font + size = self.points_to_pixels(prop.get_size_in_points()) + # Font colour is determined by the active wx.Pen + # TODO: It may be wise to cache font information + self.fontd[key] = font = wx.Font( # Cache the font and gc. + pointSize=round(size), + family=self.fontnames.get(prop.get_name(), wx.ROMAN), + style=self.fontangles[prop.get_style()], + weight=self.fontweights[prop.get_weight()]) + return font + + def points_to_pixels(self, points): + # docstring inherited + return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0) + + +class GraphicsContextWx(GraphicsContextBase): + """ + The graphics context provides the color, line styles, etc. + + This class stores a reference to a wxMemoryDC, and a + wxGraphicsContext that draws to it. Creating a wxGraphicsContext + seems to be fairly heavy, so these objects are cached based on the + bitmap object that is passed in. + + The base GraphicsContext stores colors as an RGB tuple on the unit + interval, e.g., (0.5, 0.0, 1.0). wxPython uses an int interval, but + since wxPython colour management is rather simple, I have not chosen + to implement a separate colour manager class. + """ + _capd = {'butt': wx.CAP_BUTT, + 'projecting': wx.CAP_PROJECTING, + 'round': wx.CAP_ROUND} + + _joind = {'bevel': wx.JOIN_BEVEL, + 'miter': wx.JOIN_MITER, + 'round': wx.JOIN_ROUND} + + _cache = weakref.WeakKeyDictionary() + + def __init__(self, bitmap, renderer): + super().__init__() + # assert self.Ok(), "wxMemoryDC not OK to use" + _log.debug("%s - __init__(): %s", type(self), bitmap) + + dc, gfx_ctx = self._cache.get(bitmap, (None, None)) + if dc is None: + dc = wx.MemoryDC(bitmap) + gfx_ctx = wx.GraphicsContext.Create(dc) + gfx_ctx._lastcliprect = None + self._cache[bitmap] = dc, gfx_ctx + + self.bitmap = bitmap + self.dc = dc + self.gfx_ctx = gfx_ctx + self._pen = wx.Pen('BLACK', 1, wx.SOLID) + gfx_ctx.SetPen(self._pen) + self.renderer = renderer + + def select(self): + """Select the current bitmap into this wxDC instance.""" + if sys.platform == 'win32': + self.dc.SelectObject(self.bitmap) + self.IsSelected = True + + def unselect(self): + """Select a Null bitmap into this wxDC instance.""" + if sys.platform == 'win32': + self.dc.SelectObject(wx.NullBitmap) + self.IsSelected = False + + def set_foreground(self, fg, isRGBA=None): + # docstring inherited + # Implementation note: wxPython has a separate concept of pen and + # brush - the brush fills any outline trace left by the pen. + # Here we set both to the same colour - if a figure is not to be + # filled, the renderer will set the brush to be transparent + # Same goes for text foreground... + _log.debug("%s - set_foreground()", type(self)) + self.select() + super().set_foreground(fg, isRGBA) + + self._pen.SetColour(self.get_wxcolour(self.get_rgb())) + self.gfx_ctx.SetPen(self._pen) + self.unselect() + + def set_linewidth(self, w): + # docstring inherited + w = float(w) + _log.debug("%s - set_linewidth()", type(self)) + self.select() + if 0 < w < 1: + w = 1 + super().set_linewidth(w) + lw = int(self.renderer.points_to_pixels(self._linewidth)) + if lw == 0: + lw = 1 + self._pen.SetWidth(lw) + self.gfx_ctx.SetPen(self._pen) + self.unselect() + + def set_capstyle(self, cs): + # docstring inherited + _log.debug("%s - set_capstyle()", type(self)) + self.select() + super().set_capstyle(cs) + self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) + self.gfx_ctx.SetPen(self._pen) + self.unselect() + + def set_joinstyle(self, js): + # docstring inherited + _log.debug("%s - set_joinstyle()", type(self)) + self.select() + super().set_joinstyle(js) + self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) + self.gfx_ctx.SetPen(self._pen) + self.unselect() + + def get_wxcolour(self, color): + """Convert an RGB(A) color to a wx.Colour.""" + _log.debug("%s - get_wx_color()", type(self)) + return wx.Colour(*[int(255 * x) for x in color]) + + +class _FigureCanvasWxBase(FigureCanvasBase, wx.Panel): + """ + The FigureCanvas contains the figure and does event handling. + + In the wxPython backend, it is derived from wxPanel, and (usually) lives + inside a frame instantiated by a FigureManagerWx. The parent window + probably implements a wx.Sizer to control the displayed control size - but + we give a hint as to our preferred minimum size. + """ + + required_interactive_framework = "wx" + _timer_cls = TimerWx + manager_class = _api.classproperty(lambda cls: FigureManagerWx) + + keyvald = { + wx.WXK_CONTROL: 'control', + wx.WXK_SHIFT: 'shift', + wx.WXK_ALT: 'alt', + wx.WXK_CAPITAL: 'caps_lock', + wx.WXK_LEFT: 'left', + wx.WXK_UP: 'up', + wx.WXK_RIGHT: 'right', + wx.WXK_DOWN: 'down', + wx.WXK_ESCAPE: 'escape', + wx.WXK_F1: 'f1', + wx.WXK_F2: 'f2', + wx.WXK_F3: 'f3', + wx.WXK_F4: 'f4', + wx.WXK_F5: 'f5', + wx.WXK_F6: 'f6', + wx.WXK_F7: 'f7', + wx.WXK_F8: 'f8', + wx.WXK_F9: 'f9', + wx.WXK_F10: 'f10', + wx.WXK_F11: 'f11', + wx.WXK_F12: 'f12', + wx.WXK_SCROLL: 'scroll_lock', + wx.WXK_PAUSE: 'break', + wx.WXK_BACK: 'backspace', + wx.WXK_RETURN: 'enter', + wx.WXK_INSERT: 'insert', + wx.WXK_DELETE: 'delete', + wx.WXK_HOME: 'home', + wx.WXK_END: 'end', + wx.WXK_PAGEUP: 'pageup', + wx.WXK_PAGEDOWN: 'pagedown', + wx.WXK_NUMPAD0: '0', + wx.WXK_NUMPAD1: '1', + wx.WXK_NUMPAD2: '2', + wx.WXK_NUMPAD3: '3', + wx.WXK_NUMPAD4: '4', + wx.WXK_NUMPAD5: '5', + wx.WXK_NUMPAD6: '6', + wx.WXK_NUMPAD7: '7', + wx.WXK_NUMPAD8: '8', + wx.WXK_NUMPAD9: '9', + wx.WXK_NUMPAD_ADD: '+', + wx.WXK_NUMPAD_SUBTRACT: '-', + wx.WXK_NUMPAD_MULTIPLY: '*', + wx.WXK_NUMPAD_DIVIDE: '/', + wx.WXK_NUMPAD_DECIMAL: 'dec', + wx.WXK_NUMPAD_ENTER: 'enter', + wx.WXK_NUMPAD_UP: 'up', + wx.WXK_NUMPAD_RIGHT: 'right', + wx.WXK_NUMPAD_DOWN: 'down', + wx.WXK_NUMPAD_LEFT: 'left', + wx.WXK_NUMPAD_PAGEUP: 'pageup', + wx.WXK_NUMPAD_PAGEDOWN: 'pagedown', + wx.WXK_NUMPAD_HOME: 'home', + wx.WXK_NUMPAD_END: 'end', + wx.WXK_NUMPAD_INSERT: 'insert', + wx.WXK_NUMPAD_DELETE: 'delete', + } + + def __init__(self, parent, id, figure=None): + """ + Initialize a FigureWx instance. + + - Initialize the FigureCanvasBase and wxPanel parents. + - Set event handlers for resize, paint, and keyboard and mouse + interaction. + """ + + FigureCanvasBase.__init__(self, figure) + size = wx.Size(*map(math.ceil, self.figure.bbox.size)) + if wx.Platform != '__WXMSW__': + size = parent.FromDIP(size) + # Set preferred window size hint - helps the sizer, if one is connected + wx.Panel.__init__(self, parent, id, size=size) + self.bitmap = None + self._isDrawn = False + self._rubberband_rect = None + self._rubberband_pen_black = wx.Pen('BLACK', 1, wx.PENSTYLE_SHORT_DASH) + self._rubberband_pen_white = wx.Pen('WHITE', 1, wx.PENSTYLE_SOLID) + + self.Bind(wx.EVT_SIZE, self._on_size) + self.Bind(wx.EVT_PAINT, self._on_paint) + self.Bind(wx.EVT_CHAR_HOOK, self._on_key_down) + self.Bind(wx.EVT_KEY_UP, self._on_key_up) + self.Bind(wx.EVT_LEFT_DOWN, self._on_mouse_button) + self.Bind(wx.EVT_LEFT_DCLICK, self._on_mouse_button) + self.Bind(wx.EVT_LEFT_UP, self._on_mouse_button) + self.Bind(wx.EVT_MIDDLE_DOWN, self._on_mouse_button) + self.Bind(wx.EVT_MIDDLE_DCLICK, self._on_mouse_button) + self.Bind(wx.EVT_MIDDLE_UP, self._on_mouse_button) + self.Bind(wx.EVT_RIGHT_DOWN, self._on_mouse_button) + self.Bind(wx.EVT_RIGHT_DCLICK, self._on_mouse_button) + self.Bind(wx.EVT_RIGHT_UP, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX1_DOWN, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX1_UP, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX2_DOWN, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX2_UP, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX1_DCLICK, self._on_mouse_button) + self.Bind(wx.EVT_MOUSE_AUX2_DCLICK, self._on_mouse_button) + self.Bind(wx.EVT_MOUSEWHEEL, self._on_mouse_wheel) + self.Bind(wx.EVT_MOTION, self._on_motion) + self.Bind(wx.EVT_ENTER_WINDOW, self._on_enter) + self.Bind(wx.EVT_LEAVE_WINDOW, self._on_leave) + + self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._on_capture_lost) + self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._on_capture_lost) + + self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker. + self.SetBackgroundColour(wx.WHITE) + + if wx.Platform == '__WXMAC__': + # Initial scaling. Other platforms handle this automatically + dpiScale = self.GetDPIScaleFactor() + self.SetInitialSize(self.GetSize()*(1/dpiScale)) + self._set_device_pixel_ratio(dpiScale) + + def Copy_to_Clipboard(self, event=None): + """Copy bitmap of canvas to system clipboard.""" + bmp_obj = wx.BitmapDataObject() + bmp_obj.SetBitmap(self.bitmap) + + if not wx.TheClipboard.IsOpened(): + open_success = wx.TheClipboard.Open() + if open_success: + wx.TheClipboard.SetData(bmp_obj) + wx.TheClipboard.Flush() + wx.TheClipboard.Close() + + def _update_device_pixel_ratio(self, *args, **kwargs): + # We need to be careful in cases with mixed resolution displays if + # device_pixel_ratio changes. + if self._set_device_pixel_ratio(self.GetDPIScaleFactor()): + self.draw() + + def draw_idle(self): + # docstring inherited + _log.debug("%s - draw_idle()", type(self)) + self._isDrawn = False # Force redraw + # Triggering a paint event is all that is needed to defer drawing + # until later. The platform will send the event when it thinks it is + # a good time (usually as soon as there are no other events pending). + self.Refresh(eraseBackground=False) + + def flush_events(self): + # docstring inherited + wx.Yield() + + def start_event_loop(self, timeout=0): + # docstring inherited + if hasattr(self, '_event_loop'): + raise RuntimeError("Event loop already running") + timer = wx.Timer(self, id=wx.ID_ANY) + if timeout > 0: + timer.Start(int(timeout * 1000), oneShot=True) + self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=timer.GetId()) + # Event loop handler for start/stop event loop + self._event_loop = wx.GUIEventLoop() + self._event_loop.Run() + timer.Stop() + + def stop_event_loop(self, event=None): + # docstring inherited + if hasattr(self, '_event_loop'): + if self._event_loop.IsRunning(): + self._event_loop.Exit() + del self._event_loop + + def _get_imagesave_wildcards(self): + """Return the wildcard string for the filesave dialog.""" + default_filetype = self.get_default_filetype() + filetypes = self.get_supported_filetypes_grouped() + sorted_filetypes = sorted(filetypes.items()) + wildcards = [] + extensions = [] + filter_index = 0 + for i, (name, exts) in enumerate(sorted_filetypes): + ext_list = ';'.join(['*.%s' % ext for ext in exts]) + extensions.append(exts[0]) + wildcard = f'{name} ({ext_list})|{ext_list}' + if default_filetype in exts: + filter_index = i + wildcards.append(wildcard) + wildcards = '|'.join(wildcards) + return wildcards, extensions, filter_index + + def gui_repaint(self, drawDC=None): + """ + Update the displayed image on the GUI canvas, using the supplied + wx.PaintDC device context. + """ + _log.debug("%s - gui_repaint()", type(self)) + # The "if self" check avoids a "wrapped C/C++ object has been deleted" + # RuntimeError if doing things after window is closed. + if not (self and self.IsShownOnScreen()): + return + if not drawDC: # not called from OnPaint use a ClientDC + drawDC = wx.ClientDC(self) + # For 'WX' backend on Windows, the bitmap cannot be in use by another + # DC (see GraphicsContextWx._cache). + bmp = (self.bitmap.ConvertToImage().ConvertToBitmap() + if wx.Platform == '__WXMSW__' + and isinstance(self.figure.canvas.get_renderer(), RendererWx) + else self.bitmap) + drawDC.DrawBitmap(bmp, 0, 0) + if self._rubberband_rect is not None: + # Some versions of wx+python don't support numpy.float64 here. + x0, y0, x1, y1 = map(round, self._rubberband_rect) + rect = [(x0, y0, x1, y0), (x1, y0, x1, y1), + (x0, y0, x0, y1), (x0, y1, x1, y1)] + drawDC.DrawLineList(rect, self._rubberband_pen_white) + drawDC.DrawLineList(rect, self._rubberband_pen_black) + + filetypes = { + **FigureCanvasBase.filetypes, + 'bmp': 'Windows bitmap', + 'jpeg': 'JPEG', + 'jpg': 'JPEG', + 'pcx': 'PCX', + 'png': 'Portable Network Graphics', + 'tif': 'Tagged Image Format File', + 'tiff': 'Tagged Image Format File', + 'xpm': 'X pixmap', + } + + def _on_paint(self, event): + """Called when wxPaintEvt is generated.""" + _log.debug("%s - _on_paint()", type(self)) + drawDC = wx.PaintDC(self) + if not self._isDrawn: + self.draw(drawDC=drawDC) + else: + self.gui_repaint(drawDC=drawDC) + drawDC.Destroy() + + def _on_size(self, event): + """ + Called when wxEventSize is generated. + + In this application we attempt to resize to fit the window, so it + is better to take the performance hit and redraw the whole window. + """ + self._update_device_pixel_ratio() + _log.debug("%s - _on_size()", type(self)) + sz = self.GetParent().GetSizer() + if sz: + si = sz.GetItem(self) + if sz and si and not si.Proportion and not si.Flag & wx.EXPAND: + # managed by a sizer, but with a fixed size + size = self.GetMinSize() + else: + # variable size + size = self.GetClientSize() + # Do not allow size to become smaller than MinSize + size.IncTo(self.GetMinSize()) + if getattr(self, "_width", None): + if size == (self._width, self._height): + # no change in size + return + self._width, self._height = size + self._isDrawn = False + + if self._width <= 1 or self._height <= 1: + return # Empty figure + + # Create a new, correctly sized bitmap + dpival = self.figure.dpi + if not wx.Platform == '__WXMSW__': + scale = self.GetDPIScaleFactor() + dpival /= scale + winch = self._width / dpival + hinch = self._height / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + + # Rendering will happen on the associated paint event + # so no need to do anything here except to make sure + # the whole background is repainted. + self.Refresh(eraseBackground=False) + ResizeEvent("resize_event", self)._process() + self.draw_idle() + + @staticmethod + def _mpl_buttons(): + state = wx.GetMouseState() + # NOTE: Alternatively, we could use event.LeftIsDown() / etc. but this + # fails to report multiclick drags on macOS (other OSes have not been + # verified). + mod_table = [ + (MouseButton.LEFT, state.LeftIsDown()), + (MouseButton.RIGHT, state.RightIsDown()), + (MouseButton.MIDDLE, state.MiddleIsDown()), + (MouseButton.BACK, state.Aux1IsDown()), + (MouseButton.FORWARD, state.Aux2IsDown()), + ] + # State *after* press/release. + return {button for button, flag in mod_table if flag} + + @staticmethod + def _mpl_modifiers(event=None, *, exclude=None): + mod_table = [ + ("ctrl", wx.MOD_CONTROL, wx.WXK_CONTROL), + ("alt", wx.MOD_ALT, wx.WXK_ALT), + ("shift", wx.MOD_SHIFT, wx.WXK_SHIFT), + ] + if event is not None: + modifiers = event.GetModifiers() + return [name for name, mod, key in mod_table + if modifiers & mod and exclude != key] + else: + return [name for name, mod, key in mod_table + if wx.GetKeyState(key)] + + def _get_key(self, event): + keyval = event.KeyCode + if keyval in self.keyvald: + key = self.keyvald[keyval] + elif keyval < 256: + key = chr(keyval) + # wx always returns an uppercase, so make it lowercase if the shift + # key is not depressed (NOTE: this will not handle Caps Lock) + if not event.ShiftDown(): + key = key.lower() + else: + return None + mods = self._mpl_modifiers(event, exclude=keyval) + if "shift" in mods and key.isupper(): + mods.remove("shift") + return "+".join([*mods, key]) + + def _mpl_coords(self, pos=None): + """ + Convert a wx position, defaulting to the current cursor position, to + Matplotlib coordinates. + """ + if pos is None: + pos = wx.GetMouseState() + x, y = self.ScreenToClient(pos.X, pos.Y) + else: + x, y = pos.X, pos.Y + # flip y so y=0 is bottom of canvas + if not wx.Platform == '__WXMSW__': + scale = self.GetDPIScaleFactor() + return x*scale, self.figure.bbox.height - y*scale + else: + return x, self.figure.bbox.height - y + + def _on_key_down(self, event): + """Capture key press.""" + KeyEvent("key_press_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + if self: + event.Skip() + + def _on_key_up(self, event): + """Release key.""" + KeyEvent("key_release_event", self, + self._get_key(event), *self._mpl_coords(), + guiEvent=event)._process() + if self: + event.Skip() + + def set_cursor(self, cursor): + # docstring inherited + cursor = wx.Cursor(_api.check_getitem({ + cursors.MOVE: wx.CURSOR_HAND, + cursors.HAND: wx.CURSOR_HAND, + cursors.POINTER: wx.CURSOR_ARROW, + cursors.SELECT_REGION: wx.CURSOR_CROSS, + cursors.WAIT: wx.CURSOR_WAIT, + cursors.RESIZE_HORIZONTAL: wx.CURSOR_SIZEWE, + cursors.RESIZE_VERTICAL: wx.CURSOR_SIZENS, + }, cursor=cursor)) + self.SetCursor(cursor) + self.Refresh() + + def _set_capture(self, capture=True): + """Control wx mouse capture.""" + if self.HasCapture(): + self.ReleaseMouse() + if capture: + self.CaptureMouse() + + def _on_capture_lost(self, event): + """Capture changed or lost""" + self._set_capture(False) + + def _on_mouse_button(self, event): + """Start measuring on an axis.""" + event.Skip() + self._set_capture(event.ButtonDown() or event.ButtonDClick()) + x, y = self._mpl_coords(event) + button_map = { + wx.MOUSE_BTN_LEFT: MouseButton.LEFT, + wx.MOUSE_BTN_MIDDLE: MouseButton.MIDDLE, + wx.MOUSE_BTN_RIGHT: MouseButton.RIGHT, + wx.MOUSE_BTN_AUX1: MouseButton.BACK, + wx.MOUSE_BTN_AUX2: MouseButton.FORWARD, + } + button = event.GetButton() + button = button_map.get(button, button) + modifiers = self._mpl_modifiers(event) + if event.ButtonDown(): + MouseEvent("button_press_event", self, x, y, button, + modifiers=modifiers, guiEvent=event)._process() + elif event.ButtonDClick(): + MouseEvent("button_press_event", self, x, y, button, dblclick=True, + modifiers=modifiers, guiEvent=event)._process() + elif event.ButtonUp(): + MouseEvent("button_release_event", self, x, y, button, + modifiers=modifiers, guiEvent=event)._process() + + def _on_mouse_wheel(self, event): + """Translate mouse wheel events into matplotlib events""" + x, y = self._mpl_coords(event) + # Convert delta/rotation/rate into a floating point step size + step = event.LinesPerAction * event.WheelRotation / event.WheelDelta + # Done handling event + event.Skip() + # Mac gives two events for every wheel event; skip every second one. + if wx.Platform == '__WXMAC__': + if not hasattr(self, '_skipwheelevent'): + self._skipwheelevent = True + elif self._skipwheelevent: + self._skipwheelevent = False + return # Return without processing event + else: + self._skipwheelevent = True + MouseEvent("scroll_event", self, x, y, step=step, + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def _on_motion(self, event): + """Start measuring on an axis.""" + event.Skip() + MouseEvent("motion_notify_event", self, + *self._mpl_coords(event), + buttons=self._mpl_buttons(), + modifiers=self._mpl_modifiers(event), + guiEvent=event)._process() + + def _on_enter(self, event): + """Mouse has entered the window.""" + event.Skip() + LocationEvent("figure_enter_event", self, + *self._mpl_coords(event), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def _on_leave(self, event): + """Mouse has left the window.""" + event.Skip() + LocationEvent("figure_leave_event", self, + *self._mpl_coords(event), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + +class FigureCanvasWx(_FigureCanvasWxBase): + # Rendering to a Wx canvas using the deprecated Wx renderer. + + def draw(self, drawDC=None): + """ + Render the figure using RendererWx instance renderer, or using a + previously defined renderer if none is specified. + """ + _log.debug("%s - draw()", type(self)) + self.renderer = RendererWx(self.bitmap, self.figure.dpi) + self.figure.draw(self.renderer) + self._isDrawn = True + self.gui_repaint(drawDC=drawDC) + + def _print_image(self, filetype, filename): + bitmap = wx.Bitmap(math.ceil(self.figure.bbox.width), + math.ceil(self.figure.bbox.height)) + self.figure.draw(RendererWx(bitmap, self.figure.dpi)) + saved_obj = (bitmap.ConvertToImage() + if cbook.is_writable_file_like(filename) + else bitmap) + if not saved_obj.SaveFile(filename, filetype): + raise RuntimeError(f'Could not save figure to {filename}') + # draw() is required here since bits of state about the last renderer + # are strewn about the artist draw methods. Do not remove the draw + # without first verifying that these have been cleaned up. The artist + # contains() methods will fail otherwise. + if self._isDrawn: + self.draw() + # The "if self" check avoids a "wrapped C/C++ object has been deleted" + # RuntimeError if doing things after window is closed. + if self: + self.Refresh() + + print_bmp = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_BMP) + print_jpeg = print_jpg = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_JPEG) + print_pcx = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_PCX) + print_png = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_PNG) + print_tiff = print_tif = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_TIF) + print_xpm = functools.partialmethod( + _print_image, wx.BITMAP_TYPE_XPM) + + +class FigureFrameWx(wx.Frame): + def __init__(self, num, fig, *, canvas_class): + # On non-Windows platform, explicitly set the position - fix + # positioning bug on some Linux platforms + if wx.Platform == '__WXMSW__': + pos = wx.DefaultPosition + else: + pos = wx.Point(20, 20) + super().__init__(parent=None, id=-1, pos=pos) + # Frame will be sized later by the Fit method + _log.debug("%s - __init__()", type(self)) + _set_frame_icon(self) + + self.canvas = canvas_class(self, -1, fig) + # Auto-attaches itself to self.canvas.manager + manager = FigureManagerWx(self.canvas, num, self) + + toolbar = self.canvas.manager.toolbar + if toolbar is not None: + self.SetToolBar(toolbar) + + # On Windows, canvas sizing must occur after toolbar addition; + # otherwise the toolbar further resizes the canvas. + w, h = map(math.ceil, fig.bbox.size) + self.canvas.SetInitialSize(self.FromDIP(wx.Size(w, h))) + self.canvas.SetMinSize(self.FromDIP(wx.Size(2, 2))) + self.canvas.SetFocus() + + self.Fit() + + self.Bind(wx.EVT_CLOSE, self._on_close) + + def _on_close(self, event): + _log.debug("%s - on_close()", type(self)) + CloseEvent("close_event", self.canvas)._process() + self.canvas.stop_event_loop() + # set FigureManagerWx.frame to None to prevent repeated attempts to + # close this frame from FigureManagerWx.destroy() + self.canvas.manager.frame = None + # remove figure manager from Gcf.figs + Gcf.destroy(self.canvas.manager) + try: # See issue 2941338. + self.canvas.mpl_disconnect(self.canvas.toolbar._id_drag) + except AttributeError: # If there's no toolbar. + pass + # Carry on with close event propagation, frame & children destruction + event.Skip() + + +class FigureManagerWx(FigureManagerBase): + """ + Container/controller for the FigureCanvas and GUI frame. + + It is instantiated by Gcf whenever a new figure is created. Gcf is + responsible for managing multiple instances of FigureManagerWx. + + Attributes + ---------- + canvas : `FigureCanvas` + a FigureCanvasWx(wx.Panel) instance + window : wxFrame + a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html + """ + + def __init__(self, canvas, num, frame): + _log.debug("%s - __init__()", type(self)) + self.frame = self.window = frame + super().__init__(canvas, num) + + @classmethod + def create_with_canvas(cls, canvas_class, figure, num): + # docstring inherited + wxapp = wx.GetApp() or _create_wxapp() + frame = FigureFrameWx(num, figure, canvas_class=canvas_class) + manager = figure.canvas.manager + if mpl.is_interactive(): + manager.frame.Show() + figure.canvas.draw_idle() + return manager + + @classmethod + def start_main_loop(cls): + if not wx.App.IsMainLoopRunning(): + wxapp = wx.GetApp() + if wxapp is not None: + wxapp.MainLoop() + + def show(self): + # docstring inherited + self.frame.Show() + self.canvas.draw() + if mpl.rcParams['figure.raise_window']: + self.frame.Raise() + + def destroy(self, *args): + # docstring inherited + _log.debug("%s - destroy()", type(self)) + frame = self.frame + if frame: # Else, may have been already deleted, e.g. when closing. + # As this can be called from non-GUI thread from plt.close use + # wx.CallAfter to ensure thread safety. + wx.CallAfter(frame.Close) + + def full_screen_toggle(self): + # docstring inherited + self.frame.ShowFullScreen(not self.frame.IsFullScreen()) + + def get_window_title(self): + # docstring inherited + return self.window.GetTitle() + + def set_window_title(self, title): + # docstring inherited + self.window.SetTitle(title) + + def resize(self, width, height): + # docstring inherited + # Directly using SetClientSize doesn't handle the toolbar on Windows. + self.window.SetSize(self.window.ClientToWindowSize(wx.Size( + math.ceil(width), math.ceil(height)))) + + +def _load_bitmap(filename): + """ + Load a wx.Bitmap from a file in the "images" directory of the Matplotlib + data. + """ + return wx.Bitmap(str(cbook._get_data_path('images', filename))) + + +def _set_frame_icon(frame): + bundle = wx.IconBundle() + for image in ('matplotlib.png', 'matplotlib_large.png'): + icon = wx.Icon(_load_bitmap(image)) + if not icon.IsOk(): + return + bundle.AddIcon(icon) + frame.SetIcons(bundle) + + +class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): + def __init__(self, canvas, coordinates=True, *, style=wx.TB_BOTTOM): + wx.ToolBar.__init__(self, canvas.GetParent(), -1, style=style) + if wx.Platform == '__WXMAC__': + self.SetToolBitmapSize(self.GetToolBitmapSize()*self.GetDPIScaleFactor()) + + self.wx_ids = {} + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.AddSeparator() + continue + self.wx_ids[text] = ( + self.AddTool( + -1, + bitmap=self._icon(f"{image_file}.svg"), + bmpDisabled=wx.NullBitmap, + label=text, shortHelp=tooltip_text, + kind=(wx.ITEM_CHECK if text in ["Pan", "Zoom"] + else wx.ITEM_NORMAL)) + .Id) + self.Bind(wx.EVT_TOOL, getattr(self, callback), + id=self.wx_ids[text]) + + self._coordinates = coordinates + if self._coordinates: + self.AddStretchableSpace() + self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT) + self.AddControl(self._label_text) + + self.Realize() + + NavigationToolbar2.__init__(self, canvas) + + @staticmethod + def _icon(name): + """ + Construct a `wx.Bitmap` suitable for use as icon from an image file + *name*, including the extension and relative to Matplotlib's "images" + data directory. + """ + try: + dark = wx.SystemSettings.GetAppearance().IsDark() + except AttributeError: # wxpython < 4.1 + # copied from wx's IsUsingDarkBackground / GetLuminance. + bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) + fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) + # See wx.Colour.GetLuminance. + bg_lum = (.299 * bg.red + .587 * bg.green + .114 * bg.blue) / 255 + fg_lum = (.299 * fg.red + .587 * fg.green + .114 * fg.blue) / 255 + dark = fg_lum - bg_lum > .2 + + path = cbook._get_data_path('images', name) + if path.suffix == '.svg': + svg = path.read_bytes() + if dark: + svg = svg.replace(b'fill:black;', b'fill:white;') + toolbarIconSize = wx.ArtProvider().GetDIPSizeHint(wx.ART_TOOLBAR) + return wx.BitmapBundle.FromSVG(svg, toolbarIconSize) + else: + pilimg = PIL.Image.open(path) + # ensure RGBA as wx BitMap expects RGBA format + image = np.array(pilimg.convert("RGBA")) + if dark: + fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) + black_mask = (image[..., :3] == 0).all(axis=-1) + image[black_mask, :3] = (fg.Red(), fg.Green(), fg.Blue()) + return wx.Bitmap.FromBufferRGBA( + image.shape[1], image.shape[0], image.tobytes()) + + def _update_buttons_checked(self): + if "Pan" in self.wx_ids: + self.ToggleTool(self.wx_ids["Pan"], self.mode.name == "PAN") + if "Zoom" in self.wx_ids: + self.ToggleTool(self.wx_ids["Zoom"], self.mode.name == "ZOOM") + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def save_figure(self, *args): + # Fetch the required filename and file type. + filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() + default_file = self.canvas.get_default_filename() + dialog = wx.FileDialog( + self.canvas.GetParent(), "Save to file", + mpl.rcParams["savefig.directory"], default_file, filetypes, + wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) + dialog.SetFilterIndex(filter_index) + if dialog.ShowModal() == wx.ID_OK: + path = pathlib.Path(dialog.GetPath()) + _log.debug('%s - Save file path: %s', type(self), path) + fmt = exts[dialog.GetFilterIndex()] + ext = path.suffix[1:] + if ext in self.canvas.get_supported_filetypes() and fmt != ext: + # looks like they forgot to set the image type drop + # down, going with the extension. + _log.warning('extension %s did not match the selected ' + 'image type %s; going with %s', + ext, fmt, ext) + fmt = ext + # Save dir for next time, unless empty str (which means use cwd). + if mpl.rcParams["savefig.directory"]: + mpl.rcParams["savefig.directory"] = str(path.parent) + try: + self.canvas.figure.savefig(path, format=fmt) + return path + except Exception as e: + dialog = wx.MessageDialog( + parent=self.canvas.GetParent(), message=str(e), + caption='Matplotlib error') + dialog.ShowModal() + dialog.Destroy() + + def draw_rubberband(self, event, x0, y0, x1, y1): + height = self.canvas.figure.bbox.height + sf = 1 if wx.Platform == '__WXMSW__' else self.canvas.GetDPIScaleFactor() + self.canvas._rubberband_rect = (x0/sf, (height - y0)/sf, + x1/sf, (height - y1)/sf) + self.canvas.Refresh() + + def remove_rubberband(self): + self.canvas._rubberband_rect = None + self.canvas.Refresh() + + def set_message(self, s): + if self._coordinates: + self._label_text.SetLabel(s) + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if 'Back' in self.wx_ids: + self.EnableTool(self.wx_ids['Back'], can_backward) + if 'Forward' in self.wx_ids: + self.EnableTool(self.wx_ids['Forward'], can_forward) + + +# tools for matplotlib.backend_managers.ToolManager: + +class ToolbarWx(ToolContainerBase, wx.ToolBar): + _icon_extension = '.svg' + + def __init__(self, toolmanager, parent=None, style=wx.TB_BOTTOM): + if parent is None: + parent = toolmanager.canvas.GetParent() + ToolContainerBase.__init__(self, toolmanager) + wx.ToolBar.__init__(self, parent, -1, style=style) + self._space = self.AddStretchableSpace() + self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT) + self.AddControl(self._label_text) + self._toolitems = {} + self._groups = {} # Mapping of groups to the separator after them. + + def _get_tool_pos(self, tool): + """ + Find the position (index) of a wx.ToolBarToolBase in a ToolBar. + + ``ToolBar.GetToolPos`` is not useful because wx assigns the same Id to + all Separators and StretchableSpaces. + """ + pos, = (pos for pos in range(self.ToolsCount) + if self.GetToolByPos(pos) == tool) + return pos + + def add_toolitem(self, name, group, position, image_file, description, + toggle): + # Find or create the separator that follows this group. + if group not in self._groups: + self._groups[group] = self.InsertSeparator( + self._get_tool_pos(self._space)) + sep = self._groups[group] + # List all separators. + seps = [t for t in map(self.GetToolByPos, range(self.ToolsCount)) + if t.IsSeparator() and not t.IsStretchableSpace()] + # Find where to insert the tool. + if position >= 0: + # Find the start of the group by looking for the separator + # preceding this one; then move forward from it. + start = (0 if sep == seps[0] + else self._get_tool_pos(seps[seps.index(sep) - 1]) + 1) + else: + # Move backwards from this separator. + start = self._get_tool_pos(sep) + 1 + idx = start + position + if image_file: + bmp = NavigationToolbar2Wx._icon(image_file) + kind = wx.ITEM_NORMAL if not toggle else wx.ITEM_CHECK + tool = self.InsertTool(idx, -1, name, bmp, wx.NullBitmap, kind, + description or "") + else: + size = (self.GetTextExtent(name)[0] + 10, -1) + if toggle: + control = wx.ToggleButton(self, -1, name, size=size) + else: + control = wx.Button(self, -1, name, size=size) + tool = self.InsertControl(idx, control, label=name) + self.Realize() + + def handler(event): + self.trigger_tool(name) + + if image_file: + self.Bind(wx.EVT_TOOL, handler, tool) + else: + control.Bind(wx.EVT_LEFT_DOWN, handler) + + self._toolitems.setdefault(name, []) + self._toolitems[name].append((tool, handler)) + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for tool, handler in self._toolitems[name]: + if not tool.IsControl(): + self.ToggleTool(tool.Id, toggled) + else: + tool.GetControl().SetValue(toggled) + self.Refresh() + + def remove_toolitem(self, name): + for tool, handler in self._toolitems.pop(name, []): + self.DeleteTool(tool.Id) + + def set_message(self, s): + self._label_text.SetLabel(s) + + +@backend_tools._register_tool_class(_FigureCanvasWxBase) +class ConfigureSubplotsWx(backend_tools.ConfigureSubplotsBase): + def trigger(self, *args): + NavigationToolbar2Wx.configure_subplots(self) + + +@backend_tools._register_tool_class(_FigureCanvasWxBase) +class SaveFigureWx(backend_tools.SaveFigureBase): + def trigger(self, *args): + NavigationToolbar2Wx.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(_FigureCanvasWxBase) +class RubberbandWx(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + NavigationToolbar2Wx.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + NavigationToolbar2Wx.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +class _HelpDialog(wx.Dialog): + _instance = None # a reference to an open dialog singleton + headers = [("Action", "Shortcuts", "Description")] + widths = [100, 140, 300] + + def __init__(self, parent, help_entries): + super().__init__(parent, title="Help", + style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) + + sizer = wx.BoxSizer(wx.VERTICAL) + grid_sizer = wx.FlexGridSizer(0, 3, 8, 6) + # create and add the entries + bold = self.GetFont().MakeBold() + for r, row in enumerate(self.headers + help_entries): + for (col, width) in zip(row, self.widths): + label = wx.StaticText(self, label=col) + if r == 0: + label.SetFont(bold) + label.Wrap(width) + grid_sizer.Add(label, 0, 0, 0) + # finalize layout, create button + sizer.Add(grid_sizer, 0, wx.ALL, 6) + ok = wx.Button(self, wx.ID_OK) + sizer.Add(ok, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 8) + self.SetSizer(sizer) + sizer.Fit(self) + self.Layout() + self.Bind(wx.EVT_CLOSE, self._on_close) + ok.Bind(wx.EVT_BUTTON, self._on_close) + + def _on_close(self, event): + _HelpDialog._instance = None # remove global reference + self.DestroyLater() + event.Skip() + + @classmethod + def show(cls, parent, help_entries): + # if no dialog is shown, create one; otherwise just re-raise it + if cls._instance: + cls._instance.Raise() + return + cls._instance = cls(parent, help_entries) + cls._instance.Show() + + +@backend_tools._register_tool_class(_FigureCanvasWxBase) +class HelpWx(backend_tools.ToolHelpBase): + def trigger(self, *args): + _HelpDialog.show(self.figure.canvas.GetTopLevelParent(), + self._get_help_entries()) + + +@backend_tools._register_tool_class(_FigureCanvasWxBase) +class ToolCopyToClipboardWx(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + if not self.canvas._isDrawn: + self.canvas.draw() + if not self.canvas.bitmap.IsOk() or not wx.TheClipboard.Open(): + return + try: + wx.TheClipboard.SetData(wx.BitmapDataObject(self.canvas.bitmap)) + finally: + wx.TheClipboard.Close() + + +FigureManagerWx._toolbar2_class = NavigationToolbar2Wx +FigureManagerWx._toolmanager_toolbar_class = ToolbarWx + + +@_Backend.export +class _BackendWx(_Backend): + FigureCanvas = FigureCanvasWx + FigureManager = FigureManagerWx + mainloop = FigureManagerWx.start_main_loop diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxagg.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxagg.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7703ffa02b8e85b845321f52a9ecdc09b2dfa8 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxagg.py @@ -0,0 +1,45 @@ +import wx + +from .backend_agg import FigureCanvasAgg +from .backend_wx import _BackendWx, _FigureCanvasWxBase +from .backend_wx import ( # noqa: F401 # pylint: disable=W0611 + NavigationToolbar2Wx as NavigationToolbar2WxAgg) + + +class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase): + def draw(self, drawDC=None): + """ + Render the figure using agg. + """ + FigureCanvasAgg.draw(self) + self.bitmap = self._create_bitmap() + self._isDrawn = True + self.gui_repaint(drawDC=drawDC) + + def blit(self, bbox=None): + # docstring inherited + bitmap = self._create_bitmap() + if bbox is None: + self.bitmap = bitmap + else: + srcDC = wx.MemoryDC(bitmap) + destDC = wx.MemoryDC(self.bitmap) + x = int(bbox.x0) + y = int(self.bitmap.GetHeight() - bbox.y1) + destDC.Blit(x, y, int(bbox.width), int(bbox.height), srcDC, x, y) + destDC.SelectObject(wx.NullBitmap) + srcDC.SelectObject(wx.NullBitmap) + self.gui_repaint() + + def _create_bitmap(self): + """Create a wx.Bitmap from the renderer RGBA buffer""" + rgba = self.get_renderer().buffer_rgba() + h, w, _ = rgba.shape + bitmap = wx.Bitmap.FromBufferRGBA(w, h, rgba) + bitmap.SetScaleFactor(self.GetDPIScaleFactor()) + return bitmap + + +@_BackendWx.export +class _BackendWxAgg(_BackendWx): + FigureCanvas = FigureCanvasWxAgg diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxcairo.py b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxcairo.py new file mode 100644 index 0000000000000000000000000000000000000000..c53e6af4b87390455d02fab1bd3060648cac7fe8 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/backend_wxcairo.py @@ -0,0 +1,23 @@ +import wx.lib.wxcairo as wxcairo + +from .backend_cairo import cairo, FigureCanvasCairo +from .backend_wx import _BackendWx, _FigureCanvasWxBase +from .backend_wx import ( # noqa: F401 # pylint: disable=W0611 + NavigationToolbar2Wx as NavigationToolbar2WxCairo) + + +class FigureCanvasWxCairo(FigureCanvasCairo, _FigureCanvasWxBase): + def draw(self, drawDC=None): + size = self.figure.bbox.size.astype(int) + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size) + self._renderer.set_context(cairo.Context(surface)) + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + self.bitmap = wxcairo.BitmapFromImageSurface(surface) + self._isDrawn = True + self.gui_repaint(drawDC=drawDC) + + +@_BackendWx.export +class _BackendWxCairo(_BackendWx): + FigureCanvas = FigureCanvasWxCairo diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/qt_compat.py b/python_embeded/Lib/site-packages/matplotlib/backends/qt_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..b57a98b1138aa60bf4ae55d4fe5e5da44f068306 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/qt_compat.py @@ -0,0 +1,159 @@ +""" +Qt binding and backend selector. + +The selection logic is as follows: +- if any of PyQt6, PySide6, PyQt5, or PySide2 have already been + imported (checked in that order), use it; +- otherwise, if the QT_API environment variable (used by Enthought) is set, use + it to determine which binding to use; +- otherwise, use whatever the rcParams indicate. +""" + +import operator +import os +import platform +import sys + +from packaging.version import parse as parse_version + +import matplotlib as mpl + +from . import _QT_FORCE_QT5_BINDING + +QT_API_PYQT6 = "PyQt6" +QT_API_PYSIDE6 = "PySide6" +QT_API_PYQT5 = "PyQt5" +QT_API_PYSIDE2 = "PySide2" +QT_API_ENV = os.environ.get("QT_API") +if QT_API_ENV is not None: + QT_API_ENV = QT_API_ENV.lower() +_ETS = { # Mapping of QT_API_ENV to requested binding. + "pyqt6": QT_API_PYQT6, "pyside6": QT_API_PYSIDE6, + "pyqt5": QT_API_PYQT5, "pyside2": QT_API_PYSIDE2, +} +# First, check if anything is already imported. +if sys.modules.get("PyQt6.QtCore"): + QT_API = QT_API_PYQT6 +elif sys.modules.get("PySide6.QtCore"): + QT_API = QT_API_PYSIDE6 +elif sys.modules.get("PyQt5.QtCore"): + QT_API = QT_API_PYQT5 +elif sys.modules.get("PySide2.QtCore"): + QT_API = QT_API_PYSIDE2 +# Otherwise, check the QT_API environment variable (from Enthought). This can +# only override the binding, not the backend (in other words, we check that the +# requested backend actually matches). Use _get_backend_or_none to avoid +# triggering backend resolution (which can result in a partially but +# incompletely imported backend_qt5). +elif (mpl.rcParams._get_backend_or_none() or "").lower().startswith("qt5"): + if QT_API_ENV in ["pyqt5", "pyside2"]: + QT_API = _ETS[QT_API_ENV] + else: + _QT_FORCE_QT5_BINDING = True # noqa: F811 + QT_API = None +# A non-Qt backend was selected but we still got there (possible, e.g., when +# fully manually embedding Matplotlib in a Qt app without using pyplot). +elif QT_API_ENV is None: + QT_API = None +elif QT_API_ENV in _ETS: + QT_API = _ETS[QT_API_ENV] +else: + raise RuntimeError( + "The environment variable QT_API has the unrecognized value {!r}; " + "valid values are {}".format(QT_API_ENV, ", ".join(_ETS))) + + +def _setup_pyqt5plus(): + global QtCore, QtGui, QtWidgets, __version__ + global _isdeleted, _to_int + + if QT_API == QT_API_PYQT6: + from PyQt6 import QtCore, QtGui, QtWidgets, sip + __version__ = QtCore.PYQT_VERSION_STR + QtCore.Signal = QtCore.pyqtSignal + QtCore.Slot = QtCore.pyqtSlot + QtCore.Property = QtCore.pyqtProperty + _isdeleted = sip.isdeleted + _to_int = operator.attrgetter('value') + elif QT_API == QT_API_PYSIDE6: + from PySide6 import QtCore, QtGui, QtWidgets, __version__ + import shiboken6 + def _isdeleted(obj): return not shiboken6.isValid(obj) + if parse_version(__version__) >= parse_version('6.4'): + _to_int = operator.attrgetter('value') + else: + _to_int = int + elif QT_API == QT_API_PYQT5: + from PyQt5 import QtCore, QtGui, QtWidgets + import sip + __version__ = QtCore.PYQT_VERSION_STR + QtCore.Signal = QtCore.pyqtSignal + QtCore.Slot = QtCore.pyqtSlot + QtCore.Property = QtCore.pyqtProperty + _isdeleted = sip.isdeleted + _to_int = int + elif QT_API == QT_API_PYSIDE2: + from PySide2 import QtCore, QtGui, QtWidgets, __version__ + try: + from PySide2 import shiboken2 + except ImportError: + import shiboken2 + def _isdeleted(obj): + return not shiboken2.isValid(obj) + _to_int = int + else: + raise AssertionError(f"Unexpected QT_API: {QT_API}") + + +if QT_API in [QT_API_PYQT6, QT_API_PYQT5, QT_API_PYSIDE6, QT_API_PYSIDE2]: + _setup_pyqt5plus() +elif QT_API is None: # See above re: dict.__getitem__. + if _QT_FORCE_QT5_BINDING: + _candidates = [ + (_setup_pyqt5plus, QT_API_PYQT5), + (_setup_pyqt5plus, QT_API_PYSIDE2), + ] + else: + _candidates = [ + (_setup_pyqt5plus, QT_API_PYQT6), + (_setup_pyqt5plus, QT_API_PYSIDE6), + (_setup_pyqt5plus, QT_API_PYQT5), + (_setup_pyqt5plus, QT_API_PYSIDE2), + ] + for _setup, QT_API in _candidates: + try: + _setup() + except ImportError: + continue + break + else: + raise ImportError( + "Failed to import any of the following Qt binding modules: {}" + .format(", ".join([QT_API for _, QT_API in _candidates])) + ) +else: # We should not get there. + raise AssertionError(f"Unexpected QT_API: {QT_API}") +_version_info = tuple(QtCore.QLibraryInfo.version().segments()) + + +if _version_info < (5, 12): + raise ImportError( + f"The Qt version imported is " + f"{QtCore.QLibraryInfo.version().toString()} but Matplotlib requires " + f"Qt>=5.12") + + +# Fixes issues with Big Sur +# https://bugreports.qt.io/browse/QTBUG-87014, fixed in qt 5.15.2 +if (sys.platform == 'darwin' and + parse_version(platform.mac_ver()[0]) >= parse_version("10.16") and + _version_info < (5, 15, 2)): + os.environ.setdefault("QT_MAC_WANTS_LAYER", "1") + + +# Backports. + + +def _exec(obj): + # exec on PyQt6, exec_ elsewhere. + obj.exec() if hasattr(obj, "exec") else obj.exec_() diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/__init__.py b/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/_formlayout.py b/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/_formlayout.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf73cefbac8bc41c2f02f7895706423d3676e96 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/_formlayout.py @@ -0,0 +1,592 @@ +""" +formlayout +========== + +Module creating Qt form dialogs/layouts to edit various type of parameters + + +formlayout License Agreement (MIT License) +------------------------------------------ + +Copyright (c) 2009 Pierre Raybaut + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +""" + +# History: +# 1.0.10: added float validator +# (disable "Ok" and "Apply" button when not valid) +# 1.0.7: added support for "Apply" button +# 1.0.6: code cleaning + +__version__ = '1.0.10' +__license__ = __doc__ + +from ast import literal_eval + +import copy +import datetime +import logging +from numbers import Integral, Real + +from matplotlib import _api, colors as mcolors +from matplotlib.backends.qt_compat import _to_int, QtGui, QtWidgets, QtCore + +_log = logging.getLogger(__name__) + +BLACKLIST = {"title", "label"} + + +class ColorButton(QtWidgets.QPushButton): + """ + Color choosing push button + """ + colorChanged = QtCore.Signal(QtGui.QColor) + + def __init__(self, parent=None): + super().__init__(parent) + self.setFixedSize(20, 20) + self.setIconSize(QtCore.QSize(12, 12)) + self.clicked.connect(self.choose_color) + self._color = QtGui.QColor() + + def choose_color(self): + color = QtWidgets.QColorDialog.getColor( + self._color, self.parentWidget(), "", + QtWidgets.QColorDialog.ColorDialogOption.ShowAlphaChannel) + if color.isValid(): + self.set_color(color) + + def get_color(self): + return self._color + + @QtCore.Slot(QtGui.QColor) + def set_color(self, color): + if color != self._color: + self._color = color + self.colorChanged.emit(self._color) + pixmap = QtGui.QPixmap(self.iconSize()) + pixmap.fill(color) + self.setIcon(QtGui.QIcon(pixmap)) + + color = QtCore.Property(QtGui.QColor, get_color, set_color) + + +def to_qcolor(color): + """Create a QColor from a matplotlib color""" + qcolor = QtGui.QColor() + try: + rgba = mcolors.to_rgba(color) + except ValueError: + _api.warn_external(f'Ignoring invalid color {color!r}') + return qcolor # return invalid QColor + qcolor.setRgbF(*rgba) + return qcolor + + +class ColorLayout(QtWidgets.QHBoxLayout): + """Color-specialized QLineEdit layout""" + def __init__(self, color, parent=None): + super().__init__() + assert isinstance(color, QtGui.QColor) + self.lineedit = QtWidgets.QLineEdit( + mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent) + self.lineedit.editingFinished.connect(self.update_color) + self.addWidget(self.lineedit) + self.colorbtn = ColorButton(parent) + self.colorbtn.color = color + self.colorbtn.colorChanged.connect(self.update_text) + self.addWidget(self.colorbtn) + + def update_color(self): + color = self.text() + qcolor = to_qcolor(color) # defaults to black if not qcolor.isValid() + self.colorbtn.color = qcolor + + def update_text(self, color): + self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) + + def text(self): + return self.lineedit.text() + + +def font_is_installed(font): + """Check if font is installed""" + return [fam for fam in QtGui.QFontDatabase().families() + if str(fam) == font] + + +def tuple_to_qfont(tup): + """ + Create a QFont from tuple: + (family [string], size [int], italic [bool], bold [bool]) + """ + if not (isinstance(tup, tuple) and len(tup) == 4 + and font_is_installed(tup[0]) + and isinstance(tup[1], Integral) + and isinstance(tup[2], bool) + and isinstance(tup[3], bool)): + return None + font = QtGui.QFont() + family, size, italic, bold = tup + font.setFamily(family) + font.setPointSize(size) + font.setItalic(italic) + font.setBold(bold) + return font + + +def qfont_to_tuple(font): + return (str(font.family()), int(font.pointSize()), + font.italic(), font.bold()) + + +class FontLayout(QtWidgets.QGridLayout): + """Font selection""" + def __init__(self, value, parent=None): + super().__init__() + font = tuple_to_qfont(value) + assert font is not None + + # Font family + self.family = QtWidgets.QFontComboBox(parent) + self.family.setCurrentFont(font) + self.addWidget(self.family, 0, 0, 1, -1) + + # Font size + self.size = QtWidgets.QComboBox(parent) + self.size.setEditable(True) + sizelist = [*range(6, 12), *range(12, 30, 2), 36, 48, 72] + size = font.pointSize() + if size not in sizelist: + sizelist.append(size) + sizelist.sort() + self.size.addItems([str(s) for s in sizelist]) + self.size.setCurrentIndex(sizelist.index(size)) + self.addWidget(self.size, 1, 0) + + # Italic or not + self.italic = QtWidgets.QCheckBox(self.tr("Italic"), parent) + self.italic.setChecked(font.italic()) + self.addWidget(self.italic, 1, 1) + + # Bold or not + self.bold = QtWidgets.QCheckBox(self.tr("Bold"), parent) + self.bold.setChecked(font.bold()) + self.addWidget(self.bold, 1, 2) + + def get_font(self): + font = self.family.currentFont() + font.setItalic(self.italic.isChecked()) + font.setBold(self.bold.isChecked()) + font.setPointSize(int(self.size.currentText())) + return qfont_to_tuple(font) + + +def is_edit_valid(edit): + text = edit.text() + state = edit.validator().validate(text, 0)[0] + return state == QtGui.QDoubleValidator.State.Acceptable + + +class FormWidget(QtWidgets.QWidget): + update_buttons = QtCore.Signal() + + def __init__(self, data, comment="", with_margin=False, parent=None): + """ + Parameters + ---------- + data : list of (label, value) pairs + The data to be edited in the form. + comment : str, optional + with_margin : bool, default: False + If False, the form elements reach to the border of the widget. + This is the desired behavior if the FormWidget is used as a widget + alongside with other widgets such as a QComboBox, which also do + not have a margin around them. + However, a margin can be desired if the FormWidget is the only + widget within a container, e.g. a tab in a QTabWidget. + parent : QWidget or None + The parent widget. + """ + super().__init__(parent) + self.data = copy.deepcopy(data) + self.widgets = [] + self.formlayout = QtWidgets.QFormLayout(self) + if not with_margin: + self.formlayout.setContentsMargins(0, 0, 0, 0) + if comment: + self.formlayout.addRow(QtWidgets.QLabel(comment)) + self.formlayout.addRow(QtWidgets.QLabel(" ")) + + def get_dialog(self): + """Return FormDialog instance""" + dialog = self.parent() + while not isinstance(dialog, QtWidgets.QDialog): + dialog = dialog.parent() + return dialog + + def setup(self): + for label, value in self.data: + if label is None and value is None: + # Separator: (None, None) + self.formlayout.addRow(QtWidgets.QLabel(" "), + QtWidgets.QLabel(" ")) + self.widgets.append(None) + continue + elif label is None: + # Comment + self.formlayout.addRow(QtWidgets.QLabel(value)) + self.widgets.append(None) + continue + elif tuple_to_qfont(value) is not None: + field = FontLayout(value, self) + elif (label.lower() not in BLACKLIST + and mcolors.is_color_like(value)): + field = ColorLayout(to_qcolor(value), self) + elif isinstance(value, str): + field = QtWidgets.QLineEdit(value, self) + elif isinstance(value, (list, tuple)): + if isinstance(value, tuple): + value = list(value) + # Note: get() below checks the type of value[0] in self.data so + # it is essential that value gets modified in-place. + # This means that the code is actually broken in the case where + # value is a tuple, but fortunately we always pass a list... + selindex = value.pop(0) + field = QtWidgets.QComboBox(self) + if isinstance(value[0], (list, tuple)): + keys = [key for key, _val in value] + value = [val for _key, val in value] + else: + keys = value + field.addItems(value) + if selindex in value: + selindex = value.index(selindex) + elif selindex in keys: + selindex = keys.index(selindex) + elif not isinstance(selindex, Integral): + _log.warning( + "index '%s' is invalid (label: %s, value: %s)", + selindex, label, value) + selindex = 0 + field.setCurrentIndex(selindex) + elif isinstance(value, bool): + field = QtWidgets.QCheckBox(self) + field.setChecked(value) + elif isinstance(value, Integral): + field = QtWidgets.QSpinBox(self) + field.setRange(-10**9, 10**9) + field.setValue(value) + elif isinstance(value, Real): + field = QtWidgets.QLineEdit(repr(value), self) + field.setCursorPosition(0) + field.setValidator(QtGui.QDoubleValidator(field)) + field.validator().setLocale(QtCore.QLocale("C")) + dialog = self.get_dialog() + dialog.register_float_field(field) + field.textChanged.connect(lambda text: dialog.update_buttons()) + elif isinstance(value, datetime.datetime): + field = QtWidgets.QDateTimeEdit(self) + field.setDateTime(value) + elif isinstance(value, datetime.date): + field = QtWidgets.QDateEdit(self) + field.setDate(value) + else: + field = QtWidgets.QLineEdit(repr(value), self) + self.formlayout.addRow(label, field) + self.widgets.append(field) + + def get(self): + valuelist = [] + for index, (label, value) in enumerate(self.data): + field = self.widgets[index] + if label is None: + # Separator / Comment + continue + elif tuple_to_qfont(value) is not None: + value = field.get_font() + elif isinstance(value, str) or mcolors.is_color_like(value): + value = str(field.text()) + elif isinstance(value, (list, tuple)): + index = int(field.currentIndex()) + if isinstance(value[0], (list, tuple)): + value = value[index][0] + else: + value = value[index] + elif isinstance(value, bool): + value = field.isChecked() + elif isinstance(value, Integral): + value = int(field.value()) + elif isinstance(value, Real): + value = float(str(field.text())) + elif isinstance(value, datetime.datetime): + datetime_ = field.dateTime() + if hasattr(datetime_, "toPyDateTime"): + value = datetime_.toPyDateTime() + else: + value = datetime_.toPython() + elif isinstance(value, datetime.date): + date_ = field.date() + if hasattr(date_, "toPyDate"): + value = date_.toPyDate() + else: + value = date_.toPython() + else: + value = literal_eval(str(field.text())) + valuelist.append(value) + return valuelist + + +class FormComboWidget(QtWidgets.QWidget): + update_buttons = QtCore.Signal() + + def __init__(self, datalist, comment="", parent=None): + super().__init__(parent) + layout = QtWidgets.QVBoxLayout() + self.setLayout(layout) + self.combobox = QtWidgets.QComboBox() + layout.addWidget(self.combobox) + + self.stackwidget = QtWidgets.QStackedWidget(self) + layout.addWidget(self.stackwidget) + self.combobox.currentIndexChanged.connect( + self.stackwidget.setCurrentIndex) + + self.widgetlist = [] + for data, title, comment in datalist: + self.combobox.addItem(title) + widget = FormWidget(data, comment=comment, parent=self) + self.stackwidget.addWidget(widget) + self.widgetlist.append(widget) + + def setup(self): + for widget in self.widgetlist: + widget.setup() + + def get(self): + return [widget.get() for widget in self.widgetlist] + + +class FormTabWidget(QtWidgets.QWidget): + update_buttons = QtCore.Signal() + + def __init__(self, datalist, comment="", parent=None): + super().__init__(parent) + layout = QtWidgets.QVBoxLayout() + self.tabwidget = QtWidgets.QTabWidget() + layout.addWidget(self.tabwidget) + layout.setContentsMargins(0, 0, 0, 0) + self.setLayout(layout) + self.widgetlist = [] + for data, title, comment in datalist: + if len(data[0]) == 3: + widget = FormComboWidget(data, comment=comment, parent=self) + else: + widget = FormWidget(data, with_margin=True, comment=comment, + parent=self) + index = self.tabwidget.addTab(widget, title) + self.tabwidget.setTabToolTip(index, comment) + self.widgetlist.append(widget) + + def setup(self): + for widget in self.widgetlist: + widget.setup() + + def get(self): + return [widget.get() for widget in self.widgetlist] + + +class FormDialog(QtWidgets.QDialog): + """Form Dialog""" + def __init__(self, data, title="", comment="", + icon=None, parent=None, apply=None): + super().__init__(parent) + + self.apply_callback = apply + + # Form + if isinstance(data[0][0], (list, tuple)): + self.formwidget = FormTabWidget(data, comment=comment, + parent=self) + elif len(data[0]) == 3: + self.formwidget = FormComboWidget(data, comment=comment, + parent=self) + else: + self.formwidget = FormWidget(data, comment=comment, + parent=self) + layout = QtWidgets.QVBoxLayout() + layout.addWidget(self.formwidget) + + self.float_fields = [] + self.formwidget.setup() + + # Button box + self.bbox = bbox = QtWidgets.QDialogButtonBox( + QtWidgets.QDialogButtonBox.StandardButton( + _to_int(QtWidgets.QDialogButtonBox.StandardButton.Ok) | + _to_int(QtWidgets.QDialogButtonBox.StandardButton.Cancel) + )) + self.formwidget.update_buttons.connect(self.update_buttons) + if self.apply_callback is not None: + apply_btn = bbox.addButton( + QtWidgets.QDialogButtonBox.StandardButton.Apply) + apply_btn.clicked.connect(self.apply) + + bbox.accepted.connect(self.accept) + bbox.rejected.connect(self.reject) + layout.addWidget(bbox) + + self.setLayout(layout) + + self.setWindowTitle(title) + if not isinstance(icon, QtGui.QIcon): + icon = QtWidgets.QWidget().style().standardIcon( + QtWidgets.QStyle.SP_MessageBoxQuestion) + self.setWindowIcon(icon) + + def register_float_field(self, field): + self.float_fields.append(field) + + def update_buttons(self): + valid = True + for field in self.float_fields: + if not is_edit_valid(field): + valid = False + for btn_type in ["Ok", "Apply"]: + btn = self.bbox.button( + getattr(QtWidgets.QDialogButtonBox.StandardButton, + btn_type)) + if btn is not None: + btn.setEnabled(valid) + + def accept(self): + self.data = self.formwidget.get() + self.apply_callback(self.data) + super().accept() + + def reject(self): + self.data = None + super().reject() + + def apply(self): + self.apply_callback(self.formwidget.get()) + + def get(self): + """Return form result""" + return self.data + + +def fedit(data, title="", comment="", icon=None, parent=None, apply=None): + """ + Create form dialog + + data: datalist, datagroup + title: str + comment: str + icon: QIcon instance + parent: parent QWidget + apply: apply callback (function) + + datalist: list/tuple of (field_name, field_value) + datagroup: list/tuple of (datalist *or* datagroup, title, comment) + + -> one field for each member of a datalist + -> one tab for each member of a top-level datagroup + -> one page (of a multipage widget, each page can be selected with a combo + box) for each member of a datagroup inside a datagroup + + Supported types for field_value: + - int, float, str, bool + - colors: in Qt-compatible text form, i.e. in hex format or name + (red, ...) (automatically detected from a string) + - list/tuple: + * the first element will be the selected index (or value) + * the other elements can be couples (key, value) or only values + """ + + # Create a QApplication instance if no instance currently exists + # (e.g., if the module is used directly from the interpreter) + if QtWidgets.QApplication.startingUp(): + _app = QtWidgets.QApplication([]) + dialog = FormDialog(data, title, comment, icon, parent, apply) + + if parent is not None: + if hasattr(parent, "_fedit_dialog"): + parent._fedit_dialog.close() + parent._fedit_dialog = dialog + + dialog.show() + + +if __name__ == "__main__": + + _app = QtWidgets.QApplication([]) + + def create_datalist_example(): + return [('str', 'this is a string'), + ('list', [0, '1', '3', '4']), + ('list2', ['--', ('none', 'None'), ('--', 'Dashed'), + ('-.', 'DashDot'), ('-', 'Solid'), + ('steps', 'Steps'), (':', 'Dotted')]), + ('float', 1.2), + (None, 'Other:'), + ('int', 12), + ('font', ('Arial', 10, False, True)), + ('color', '#123409'), + ('bool', True), + ('date', datetime.date(2010, 10, 10)), + ('datetime', datetime.datetime(2010, 10, 10)), + ] + + def create_datagroup_example(): + datalist = create_datalist_example() + return ((datalist, "Category 1", "Category 1 comment"), + (datalist, "Category 2", "Category 2 comment"), + (datalist, "Category 3", "Category 3 comment")) + + # --------- datalist example + datalist = create_datalist_example() + + def apply_test(data): + print("data:", data) + fedit(datalist, title="Example", + comment="This is just an example.", + apply=apply_test) + + _app.exec() + + # --------- datagroup example + datagroup = create_datagroup_example() + fedit(datagroup, "Global title", + apply=apply_test) + _app.exec() + + # --------- datagroup inside a datagroup example + datalist = create_datalist_example() + datagroup = create_datagroup_example() + fedit(((datagroup, "Title 1", "Tab 1 comment"), + (datalist, "Title 2", "Tab 2 comment"), + (datalist, "Title 3", "Tab 3 comment")), + "Global title", + apply=apply_test) + _app.exec() diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/figureoptions.py b/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/figureoptions.py new file mode 100644 index 0000000000000000000000000000000000000000..9d31fa9ced2ca24961597eddcc5e3e0f36f8fad8 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/qt_editor/figureoptions.py @@ -0,0 +1,271 @@ +# Copyright © 2009 Pierre Raybaut +# Licensed under the terms of the MIT License +# see the Matplotlib licenses directory for a copy of the license + + +"""Module that provides a GUI-based editor for Matplotlib's figure options.""" + +from itertools import chain +from matplotlib import cbook, cm, colors as mcolors, markers, image as mimage +from matplotlib.backends.qt_compat import QtGui +from matplotlib.backends.qt_editor import _formlayout +from matplotlib.dates import DateConverter, num2date + +LINESTYLES = {'-': 'Solid', + '--': 'Dashed', + '-.': 'DashDot', + ':': 'Dotted', + 'None': 'None', + } + +DRAWSTYLES = { + 'default': 'Default', + 'steps-pre': 'Steps (Pre)', 'steps': 'Steps (Pre)', + 'steps-mid': 'Steps (Mid)', + 'steps-post': 'Steps (Post)'} + +MARKERS = markers.MarkerStyle.markers + + +def figure_edit(axes, parent=None): + """Edit matplotlib figure options""" + sep = (None, None) # separator + + # Get / General + def convert_limits(lim, converter): + """Convert axis limits for correct input editors.""" + if isinstance(converter, DateConverter): + return map(num2date, lim) + # Cast to builtin floats as they have nicer reprs. + return map(float, lim) + + axis_map = axes._axis_map + axis_limits = { + name: tuple(convert_limits( + getattr(axes, f'get_{name}lim')(), axis.get_converter() + )) + for name, axis in axis_map.items() + } + general = [ + ('Title', axes.get_title()), + sep, + *chain.from_iterable([ + ( + (None, f"{name.title()}-Axis"), + ('Min', axis_limits[name][0]), + ('Max', axis_limits[name][1]), + ('Label', axis.label.get_text()), + ('Scale', [axis.get_scale(), + 'linear', 'log', 'symlog', 'logit']), + sep, + ) + for name, axis in axis_map.items() + ]), + ('(Re-)Generate automatic legend', False), + ] + + # Save the converter and unit data + axis_converter = { + name: axis.get_converter() + for name, axis in axis_map.items() + } + axis_units = { + name: axis.get_units() + for name, axis in axis_map.items() + } + + # Get / Curves + labeled_lines = [] + for line in axes.get_lines(): + label = line.get_label() + if label == '_nolegend_': + continue + labeled_lines.append((label, line)) + curves = [] + + def prepare_data(d, init): + """ + Prepare entry for FormLayout. + + *d* is a mapping of shorthands to style names (a single style may + have multiple shorthands, in particular the shorthands `None`, + `"None"`, `"none"` and `""` are synonyms); *init* is one shorthand + of the initial style. + + This function returns an list suitable for initializing a + FormLayout combobox, namely `[initial_name, (shorthand, + style_name), (shorthand, style_name), ...]`. + """ + if init not in d: + d = {**d, init: str(init)} + # Drop duplicate shorthands from dict (by overwriting them during + # the dict comprehension). + name2short = {name: short for short, name in d.items()} + # Convert back to {shorthand: name}. + short2name = {short: name for name, short in name2short.items()} + # Find the kept shorthand for the style specified by init. + canonical_init = name2short[d[init]] + # Sort by representation and prepend the initial value. + return ([canonical_init] + + sorted(short2name.items(), + key=lambda short_and_name: short_and_name[1])) + + for label, line in labeled_lines: + color = mcolors.to_hex( + mcolors.to_rgba(line.get_color(), line.get_alpha()), + keep_alpha=True) + ec = mcolors.to_hex( + mcolors.to_rgba(line.get_markeredgecolor(), line.get_alpha()), + keep_alpha=True) + fc = mcolors.to_hex( + mcolors.to_rgba(line.get_markerfacecolor(), line.get_alpha()), + keep_alpha=True) + curvedata = [ + ('Label', label), + sep, + (None, 'Line'), + ('Line style', prepare_data(LINESTYLES, line.get_linestyle())), + ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())), + ('Width', line.get_linewidth()), + ('Color (RGBA)', color), + sep, + (None, 'Marker'), + ('Style', prepare_data(MARKERS, line.get_marker())), + ('Size', line.get_markersize()), + ('Face color (RGBA)', fc), + ('Edge color (RGBA)', ec)] + curves.append([curvedata, label, ""]) + # Is there a curve displayed? + has_curve = bool(curves) + + # Get ScalarMappables. + labeled_mappables = [] + for mappable in [*axes.images, *axes.collections]: + label = mappable.get_label() + if label == '_nolegend_' or mappable.get_array() is None: + continue + labeled_mappables.append((label, mappable)) + mappables = [] + cmaps = [(cmap, name) for name, cmap in sorted(cm._colormaps.items())] + for label, mappable in labeled_mappables: + cmap = mappable.get_cmap() + if cmap.name not in cm._colormaps: + cmaps = [(cmap, cmap.name), *cmaps] + low, high = mappable.get_clim() + mappabledata = [ + ('Label', label), + ('Colormap', [cmap.name] + cmaps), + ('Min. value', low), + ('Max. value', high), + ] + if hasattr(mappable, "get_interpolation"): # Images. + interpolations = [ + (name, name) for name in sorted(mimage.interpolations_names)] + mappabledata.append(( + 'Interpolation', + [mappable.get_interpolation(), *interpolations])) + + interpolation_stages = ['data', 'rgba', 'auto'] + mappabledata.append(( + 'Interpolation stage', + [mappable.get_interpolation_stage(), *interpolation_stages])) + + mappables.append([mappabledata, label, ""]) + # Is there a scalarmappable displayed? + has_sm = bool(mappables) + + datalist = [(general, "Axes", "")] + if curves: + datalist.append((curves, "Curves", "")) + if mappables: + datalist.append((mappables, "Images, etc.", "")) + + def apply_callback(data): + """A callback to apply changes.""" + orig_limits = { + name: getattr(axes, f"get_{name}lim")() + for name in axis_map + } + + general = data.pop(0) + curves = data.pop(0) if has_curve else [] + mappables = data.pop(0) if has_sm else [] + if data: + raise ValueError("Unexpected field") + + title = general.pop(0) + axes.set_title(title) + generate_legend = general.pop() + + for i, (name, axis) in enumerate(axis_map.items()): + axis_min = general[4*i] + axis_max = general[4*i + 1] + axis_label = general[4*i + 2] + axis_scale = general[4*i + 3] + if axis.get_scale() != axis_scale: + getattr(axes, f"set_{name}scale")(axis_scale) + + axis._set_lim(axis_min, axis_max, auto=False) + axis.set_label_text(axis_label) + + # Restore the unit data + axis._set_converter(axis_converter[name]) + axis.set_units(axis_units[name]) + + # Set / Curves + for index, curve in enumerate(curves): + line = labeled_lines[index][1] + (label, linestyle, drawstyle, linewidth, color, marker, markersize, + markerfacecolor, markeredgecolor) = curve + line.set_label(label) + line.set_linestyle(linestyle) + line.set_drawstyle(drawstyle) + line.set_linewidth(linewidth) + rgba = mcolors.to_rgba(color) + line.set_alpha(None) + line.set_color(rgba) + if marker != 'none': + line.set_marker(marker) + line.set_markersize(markersize) + line.set_markerfacecolor(markerfacecolor) + line.set_markeredgecolor(markeredgecolor) + + # Set ScalarMappables. + for index, mappable_settings in enumerate(mappables): + mappable = labeled_mappables[index][1] + if len(mappable_settings) == 6: + label, cmap, low, high, interpolation, interpolation_stage = \ + mappable_settings + mappable.set_interpolation(interpolation) + mappable.set_interpolation_stage(interpolation_stage) + elif len(mappable_settings) == 4: + label, cmap, low, high = mappable_settings + mappable.set_label(label) + mappable.set_cmap(cmap) + mappable.set_clim(*sorted([low, high])) + + # re-generate legend, if checkbox is checked + if generate_legend: + draggable = None + ncols = 1 + if axes.legend_ is not None: + old_legend = axes.get_legend() + draggable = old_legend._draggable is not None + ncols = old_legend._ncols + new_legend = axes.legend(ncols=ncols) + if new_legend: + new_legend.set_draggable(draggable) + + # Redraw + figure = axes.get_figure() + figure.canvas.draw() + for name in axis_map: + if getattr(axes, f"get_{name}lim")() != orig_limits[name]: + figure.canvas.toolbar.push_current() + break + + _formlayout.fedit( + datalist, title="Figure options", parent=parent, + icon=QtGui.QIcon( + str(cbook._get_data_path('images', 'qt4_editor_options.svg'))), + apply=apply_callback) diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/registry.py b/python_embeded/Lib/site-packages/matplotlib/backends/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a53f917a4c349a8bd12c0b38455e11b4dc638 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/registry.py @@ -0,0 +1,414 @@ +from enum import Enum +import importlib + + +class BackendFilter(Enum): + """ + Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin` + + .. versionadded:: 3.9 + """ + INTERACTIVE = 0 + NON_INTERACTIVE = 1 + + +class BackendRegistry: + """ + Registry of backends available within Matplotlib. + + This is the single source of truth for available backends. + + All use of ``BackendRegistry`` should be via the singleton instance + ``backend_registry`` which can be imported from ``matplotlib.backends``. + + Each backend has a name, a module name containing the backend code, and an + optional GUI framework that must be running if the backend is interactive. + There are three sources of backends: built-in (source code is within the + Matplotlib repository), explicit ``module://some.backend`` syntax (backend is + obtained by loading the module), or via an entry point (self-registering + backend in an external package). + + .. versionadded:: 3.9 + """ + # Mapping of built-in backend name to GUI framework, or "headless" for no + # GUI framework. Built-in backends are those which are included in the + # Matplotlib repo. A backend with name 'name' is located in the module + # f"matplotlib.backends.backend_{name.lower()}" + _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = { + "gtk3agg": "gtk3", + "gtk3cairo": "gtk3", + "gtk4agg": "gtk4", + "gtk4cairo": "gtk4", + "macosx": "macosx", + "nbagg": "nbagg", + "notebook": "nbagg", + "qtagg": "qt", + "qtcairo": "qt", + "qt5agg": "qt5", + "qt5cairo": "qt5", + "tkagg": "tk", + "tkcairo": "tk", + "webagg": "webagg", + "wx": "wx", + "wxagg": "wx", + "wxcairo": "wx", + "agg": "headless", + "cairo": "headless", + "pdf": "headless", + "pgf": "headless", + "ps": "headless", + "svg": "headless", + "template": "headless", + } + + # Reverse mapping of gui framework to preferred built-in backend. + _GUI_FRAMEWORK_TO_BACKEND = { + "gtk3": "gtk3agg", + "gtk4": "gtk4agg", + "headless": "agg", + "macosx": "macosx", + "qt": "qtagg", + "qt5": "qt5agg", + "qt6": "qtagg", + "tk": "tkagg", + "wx": "wxagg", + } + + def __init__(self): + # Only load entry points when first needed. + self._loaded_entry_points = False + + # Mapping of non-built-in backend to GUI framework, added dynamically from + # entry points and from matplotlib.use("module://some.backend") format. + # New entries have an "unknown" GUI framework that is determined when first + # needed by calling _get_gui_framework_by_loading. + self._backend_to_gui_framework = {} + + # Mapping of backend name to module name, where different from + # f"matplotlib.backends.backend_{backend_name.lower()}". These are either + # hardcoded for backward compatibility, or loaded from entry points or + # "module://some.backend" syntax. + self._name_to_module = { + "notebook": "nbagg", + } + + def _backend_module_name(self, backend): + if backend.startswith("module://"): + return backend[9:] + + # Return name of module containing the specified backend. + # Does not check if the backend is valid, use is_valid_backend for that. + backend = backend.lower() + + # Check if have specific name to module mapping. + backend = self._name_to_module.get(backend, backend) + + return (backend[9:] if backend.startswith("module://") + else f"matplotlib.backends.backend_{backend}") + + def _clear(self): + # Clear all dynamically-added data, used for testing only. + self.__init__() + + def _ensure_entry_points_loaded(self): + # Load entry points, if they have not already been loaded. + if not self._loaded_entry_points: + entries = self._read_entry_points() + self._validate_and_store_entry_points(entries) + self._loaded_entry_points = True + + def _get_gui_framework_by_loading(self, backend): + # Determine GUI framework for a backend by loading its module and reading the + # FigureCanvas.required_interactive_framework attribute. + # Returns "headless" if there is no GUI framework. + module = self.load_backend_module(backend) + canvas_class = module.FigureCanvas + return canvas_class.required_interactive_framework or "headless" + + def _read_entry_points(self): + # Read entry points of modules that self-advertise as Matplotlib backends. + # Expects entry points like this one from matplotlib-inline (in pyproject.toml + # format): + # [project.entry-points."matplotlib.backend"] + # inline = "matplotlib_inline.backend_inline" + import importlib.metadata as im + + entry_points = im.entry_points(group="matplotlib.backend") + entries = [(entry.name, entry.value) for entry in entry_points] + + # For backward compatibility, if matplotlib-inline and/or ipympl are installed + # but too old to include entry points, create them. Do not import ipympl + # directly as this calls matplotlib.use() whilst in this function. + def backward_compatible_entry_points( + entries, module_name, threshold_version, names, target): + from matplotlib import _parse_to_version_info + try: + module_version = im.version(module_name) + if _parse_to_version_info(module_version) < threshold_version: + for name in names: + entries.append((name, target)) + except im.PackageNotFoundError: + pass + + names = [entry[0] for entry in entries] + if "inline" not in names: + backward_compatible_entry_points( + entries, "matplotlib_inline", (0, 1, 7), ["inline"], + "matplotlib_inline.backend_inline") + if "ipympl" not in names: + backward_compatible_entry_points( + entries, "ipympl", (0, 9, 4), ["ipympl", "widget"], + "ipympl.backend_nbagg") + + return entries + + def _validate_and_store_entry_points(self, entries): + # Validate and store entry points so that they can be used via matplotlib.use() + # in the normal manner. Entry point names cannot be of module:// format, cannot + # shadow a built-in backend name, and there cannot be multiple entry points + # with the same name but different modules. Multiple entry points with the same + # name and value are permitted (it can sometimes happen outside of our control, + # see https://github.com/matplotlib/matplotlib/issues/28367). + for name, module in set(entries): + name = name.lower() + if name.startswith("module://"): + raise RuntimeError( + f"Entry point name '{name}' cannot start with 'module://'") + if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK: + raise RuntimeError(f"Entry point name '{name}' is a built-in backend") + if name in self._backend_to_gui_framework: + raise RuntimeError(f"Entry point name '{name}' duplicated") + + self._name_to_module[name] = "module://" + module + # Do not yet know backend GUI framework, determine it only when necessary. + self._backend_to_gui_framework[name] = "unknown" + + def backend_for_gui_framework(self, framework): + """ + Return the name of the backend corresponding to the specified GUI framework. + + Parameters + ---------- + framework : str + GUI framework such as "qt". + + Returns + ------- + str or None + Backend name or None if GUI framework not recognised. + """ + return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower()) + + def is_valid_backend(self, backend): + """ + Return True if the backend name is valid, False otherwise. + + A backend name is valid if it is one of the built-in backends or has been + dynamically added via an entry point. Those beginning with ``module://`` are + always considered valid and are added to the current list of all backends + within this function. + + Even if a name is valid, it may not be importable or usable. This can only be + determined by loading and using the backend module. + + Parameters + ---------- + backend : str + Name of backend. + + Returns + ------- + bool + True if backend is valid, False otherwise. + """ + if not backend.startswith("module://"): + backend = backend.lower() + + # For backward compatibility, convert ipympl and matplotlib-inline long + # module:// names to their shortened forms. + backwards_compat = { + "module://ipympl.backend_nbagg": "widget", + "module://matplotlib_inline.backend_inline": "inline", + } + backend = backwards_compat.get(backend, backend) + + if (backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or + backend in self._backend_to_gui_framework): + return True + + if backend.startswith("module://"): + self._backend_to_gui_framework[backend] = "unknown" + return True + + # Only load entry points if really need to and not already done so. + self._ensure_entry_points_loaded() + if backend in self._backend_to_gui_framework: + return True + + return False + + def list_all(self): + """ + Return list of all known backends. + + These include built-in backends and those obtained at runtime either from entry + points or explicit ``module://some.backend`` syntax. + + Entry points will be loaded if they haven't been already. + + Returns + ------- + list of str + Backend names. + """ + self._ensure_entry_points_loaded() + return [*self.list_builtin(), *self._backend_to_gui_framework] + + def list_builtin(self, filter_=None): + """ + Return list of backends that are built into Matplotlib. + + Parameters + ---------- + filter_ : `~.BackendFilter`, optional + Filter to apply to returned backends. For example, to return only + non-interactive backends use `.BackendFilter.NON_INTERACTIVE`. + + Returns + ------- + list of str + Backend names. + """ + if filter_ == BackendFilter.INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v != "headless"] + elif filter_ == BackendFilter.NON_INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v == "headless"] + + return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK] + + def list_gui_frameworks(self): + """ + Return list of GUI frameworks used by Matplotlib backends. + + Returns + ------- + list of str + GUI framework names. + """ + return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != "headless"] + + def load_backend_module(self, backend): + """ + Load and return the module containing the specified backend. + + Parameters + ---------- + backend : str + Name of backend to load. + + Returns + ------- + Module + Module containing backend. + """ + module_name = self._backend_module_name(backend) + return importlib.import_module(module_name) + + def resolve_backend(self, backend): + """ + Return the backend and GUI framework for the specified backend name. + + If the GUI framework is not yet known then it will be determined by loading the + backend module and checking the ``FigureCanvas.required_interactive_framework`` + attribute. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + backend : str or None + Name of backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if isinstance(backend, str): + if not backend.startswith("module://"): + backend = backend.lower() + else: # Might be _auto_backend_sentinel or None + # Use whatever is already running... + from matplotlib import get_backend + backend = get_backend() + + # Is backend already known (built-in or dynamically loaded)? + gui = (self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or + self._backend_to_gui_framework.get(backend)) + + # Is backend "module://something"? + if gui is None and isinstance(backend, str) and backend.startswith("module://"): + gui = "unknown" + + # Is backend a possible entry point? + if gui is None and not self._loaded_entry_points: + self._ensure_entry_points_loaded() + gui = self._backend_to_gui_framework.get(backend) + + # Backend known but not its gui framework. + if gui == "unknown": + gui = self._get_gui_framework_by_loading(backend) + self._backend_to_gui_framework[backend] = gui + + if gui is None: + raise RuntimeError(f"'{backend}' is not a recognised backend name") + + return backend, gui if gui != "headless" else None + + def resolve_gui_or_backend(self, gui_or_backend): + """ + Return the backend and GUI framework for the specified string that may be + either a GUI framework or a backend name, tested in that order. + + This is for use with the IPython %matplotlib magic command which may be a GUI + framework such as ``%matplotlib qt`` or a backend name such as + ``%matplotlib qtagg``. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + gui_or_backend : str or None + Name of GUI framework or backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if not gui_or_backend.startswith("module://"): + gui_or_backend = gui_or_backend.lower() + + # First check if it is a gui loop name. + backend = self.backend_for_gui_framework(gui_or_backend) + if backend is not None: + return backend, gui_or_backend if gui_or_backend != "headless" else None + + # Then check if it is a backend name. + try: + return self.resolve_backend(gui_or_backend) + except Exception: # KeyError ? + raise RuntimeError( + f"'{gui_or_backend}' is not a recognised GUI loop or backend name") + + +# Singleton +backend_registry = BackendRegistry() diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/all_figures.html b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/all_figures.html new file mode 100644 index 0000000000000000000000000000000000000000..62f04b65c9bf6b72e7b5de2c25e46a1b88109c89 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/all_figures.html @@ -0,0 +1,52 @@ + + + + + + + + + + + + + MPL | WebAgg current figures + + + +
+ +
+ + + diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/boilerplate.css b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/boilerplate.css new file mode 100644 index 0000000000000000000000000000000000000000..2b1535f4495e6f2242a09f6c822a01e34389bd98 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/boilerplate.css @@ -0,0 +1,77 @@ +/** + * HTML5 ✰ Boilerplate + * + * style.css contains a reset, font normalization and some base styles. + * + * Credit is left where credit is due. + * Much inspiration was taken from these projects: + * - yui.yahooapis.com/2.8.1/build/base/base.css + * - camendesign.com/design/ + * - praegnanz.de/weblog/htmlcssjs-kickstart + */ + + +/** + * html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline) + * v1.6.1 2010-09-17 | Authors: Eric Meyer & Richard Clark + * html5doctor.com/html-5-reset-stylesheet/ + */ + +html, body, div, span, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, +small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, figcaption, figure, +footer, header, hgroup, menu, nav, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} + +sup { vertical-align: super; } +sub { vertical-align: sub; } + +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} + +blockquote, q { quotes: none; } + +blockquote:before, blockquote:after, +q:before, q:after { content: ""; content: none; } + +ins { background-color: #ff9; color: #000; text-decoration: none; } + +mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; } + +del { text-decoration: line-through; } + +abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; } + +table { border-collapse: collapse; border-spacing: 0; } + +hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } + +input, select { vertical-align: middle; } + + +/** + * Font normalization inspired by YUI Library's fonts.css: developer.yahoo.com/yui/ + */ + +body { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */ +select, input, textarea, button { font:99% sans-serif; } + +/* Normalize monospace sizing: + en.wikipedia.org/wiki/MediaWiki_talk:Common.css/Archive_11#Teletype_style_fix_for_Chrome */ +pre, code, kbd, samp { font-family: monospace, sans-serif; } + +em,i { font-style: italic; } +b,strong { font-weight: bold; } diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/fbm.css b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/fbm.css new file mode 100644 index 0000000000000000000000000000000000000000..ce35d99a5e64c2e42a368aa61cd41ddb563d9ddd --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/fbm.css @@ -0,0 +1,97 @@ + +/* Flexible box model classes */ +/* Taken from Alex Russell https://infrequently.org/2009/08/css-3-progress/ */ + +.hbox { + display: -webkit-box; + -webkit-box-orient: horizontal; + -webkit-box-align: stretch; + + display: -moz-box; + -moz-box-orient: horizontal; + -moz-box-align: stretch; + + display: box; + box-orient: horizontal; + box-align: stretch; +} + +.hbox > * { + -webkit-box-flex: 0; + -moz-box-flex: 0; + box-flex: 0; +} + +.vbox { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-box-align: stretch; + + display: -moz-box; + -moz-box-orient: vertical; + -moz-box-align: stretch; + + display: box; + box-orient: vertical; + box-align: stretch; +} + +.vbox > * { + -webkit-box-flex: 0; + -moz-box-flex: 0; + box-flex: 0; +} + +.reverse { + -webkit-box-direction: reverse; + -moz-box-direction: reverse; + box-direction: reverse; +} + +.box-flex0 { + -webkit-box-flex: 0; + -moz-box-flex: 0; + box-flex: 0; +} + +.box-flex1, .box-flex { + -webkit-box-flex: 1; + -moz-box-flex: 1; + box-flex: 1; +} + +.box-flex2 { + -webkit-box-flex: 2; + -moz-box-flex: 2; + box-flex: 2; +} + +.box-group1 { + -webkit-box-flex-group: 1; + -moz-box-flex-group: 1; + box-flex-group: 1; +} + +.box-group2 { + -webkit-box-flex-group: 2; + -moz-box-flex-group: 2; + box-flex-group: 2; +} + +.start { + -webkit-box-pack: start; + -moz-box-pack: start; + box-pack: start; +} + +.end { + -webkit-box-pack: end; + -moz-box-pack: end; + box-pack: end; +} + +.center { + -webkit-box-pack: center; + -moz-box-pack: center; + box-pack: center; +} diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/mpl.css b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/mpl.css new file mode 100644 index 0000000000000000000000000000000000000000..e55733d25ecfc6237aa8052c1fc2b7e3f356da23 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/mpl.css @@ -0,0 +1,84 @@ +/* General styling */ +.ui-helper-clearfix:before, +.ui-helper-clearfix:after { + content: ""; + display: table; + border-collapse: collapse; +} +.ui-helper-clearfix:after { + clear: both; +} + +/* Header */ +.ui-widget-header { + border: 1px solid #dddddd; + border-top-left-radius: 6px; + border-top-right-radius: 6px; + background: #e9e9e9; + color: #333333; + font-weight: bold; +} + +/* Toolbar and items */ +.mpl-toolbar { + width: 100%; +} + +.mpl-toolbar div.mpl-button-group { + display: inline-block; +} + +.mpl-button-group + .mpl-button-group { + margin-left: 0.5em; +} + +.mpl-widget { + background-color: #fff; + border: 1px solid #ccc; + display: inline-block; + cursor: pointer; + color: #333; + padding: 6px; + vertical-align: middle; +} + +.mpl-widget:disabled, +.mpl-widget[disabled] { + background-color: #ddd; + border-color: #ddd !important; + cursor: not-allowed; +} + +.mpl-widget:disabled img, +.mpl-widget[disabled] img { + /* Convert black to grey */ + filter: contrast(0%); +} + +.mpl-widget.active img { + /* Convert black to tab:blue, approximately */ + filter: invert(34%) sepia(97%) saturate(468%) hue-rotate(162deg) brightness(96%) contrast(91%); +} + +button.mpl-widget:focus, +button.mpl-widget:hover { + background-color: #ddd; + border-color: #aaa; +} + +.mpl-button-group button.mpl-widget { + margin-left: -1px; +} +.mpl-button-group button.mpl-widget:first-child { + border-top-left-radius: 6px; + border-bottom-left-radius: 6px; + margin-left: 0px; +} +.mpl-button-group button.mpl-widget:last-child { + border-top-right-radius: 6px; + border-bottom-right-radius: 6px; +} + +select.mpl-widget { + cursor: default; +} diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/page.css b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/page.css new file mode 100644 index 0000000000000000000000000000000000000000..ded0d92203790eaaab21feea83930611acec51f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/css/page.css @@ -0,0 +1,82 @@ +/** + * Primary styles + * + * Author: IPython Development Team + */ + + +body { + background-color: white; + /* This makes sure that the body covers the entire window and needs to + be in a different element than the display: box in wrapper below */ + position: absolute; + left: 0px; + right: 0px; + top: 0px; + bottom: 0px; + overflow: visible; +} + + +div#header { + /* Initially hidden to prevent FLOUC */ + display: none; + position: relative; + height: 40px; + padding: 5px; + margin: 0px; + width: 100%; +} + +span#ipython_notebook { + position: absolute; + padding: 2px 2px 2px 5px; +} + +span#ipython_notebook img { + font-family: Verdana, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif; + height: 24px; + text-decoration:none; + display: inline; + color: black; +} + +#site { + width: 100%; + display: none; +} + +/* We set the fonts by hand here to override the values in the theme */ +.ui-widget { + font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; +} + +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { + font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; +} + +/* Smaller buttons */ +.ui-button .ui-button-text { + padding: 0.2em 0.8em; + font-size: 77%; +} + +input.ui-button { + padding: 0.3em 0.9em; +} + +span#login_widget { + float: right; +} + +.border-box-sizing { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; +} + +#figure-div { + display: inline-block; + margin: 10px; + vertical-align: top; +} diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html new file mode 100644 index 0000000000000000000000000000000000000000..b941d352a7d6ca1351b7fb9879386c2d391e9be7 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html @@ -0,0 +1,34 @@ + + diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl.js b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl.js new file mode 100644 index 0000000000000000000000000000000000000000..2d1f383e9839508df2ec05201b8d7cf8dae767ba --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl.js @@ -0,0 +1,705 @@ +/* Put everything inside the global mpl namespace */ +/* global mpl */ +window.mpl = {}; + +mpl.get_websocket_type = function () { + if (typeof WebSocket !== 'undefined') { + return WebSocket; + } else if (typeof MozWebSocket !== 'undefined') { + return MozWebSocket; + } else { + alert( + 'Your browser does not have WebSocket support. ' + + 'Please try Chrome, Safari or Firefox ≥ 6. ' + + 'Firefox 4 and 5 are also supported but you ' + + 'have to enable WebSockets in about:config.' + ); + } +}; + +mpl.figure = function (figure_id, websocket, ondownload, parent_element) { + this.id = figure_id; + + this.ws = websocket; + + this.supports_binary = this.ws.binaryType !== undefined; + + if (!this.supports_binary) { + var warnings = document.getElementById('mpl-warnings'); + if (warnings) { + warnings.style.display = 'block'; + warnings.textContent = + 'This browser does not support binary websocket messages. ' + + 'Performance may be slow.'; + } + } + + this.imageObj = new Image(); + + this.context = undefined; + this.message = undefined; + this.canvas = undefined; + this.rubberband_canvas = undefined; + this.rubberband_context = undefined; + this.format_dropdown = undefined; + + this.image_mode = 'full'; + + this.root = document.createElement('div'); + this.root.setAttribute('style', 'display: inline-block'); + this._root_extra_style(this.root); + + parent_element.appendChild(this.root); + + this._init_header(this); + this._init_canvas(this); + this._init_toolbar(this); + + var fig = this; + + this.waiting = false; + + this.ws.onopen = function () { + fig.send_message('supports_binary', { value: fig.supports_binary }); + fig.send_message('send_image_mode', {}); + if (fig.ratio !== 1) { + fig.send_message('set_device_pixel_ratio', { + device_pixel_ratio: fig.ratio, + }); + } + fig.send_message('refresh', {}); + }; + + this.imageObj.onload = function () { + if (fig.image_mode === 'full') { + // Full images could contain transparency (where diff images + // almost always do), so we need to clear the canvas so that + // there is no ghosting. + fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height); + } + fig.context.drawImage(fig.imageObj, 0, 0); + }; + + this.imageObj.onunload = function () { + fig.ws.close(); + }; + + this.ws.onmessage = this._make_on_message_function(this); + + this.ondownload = ondownload; +}; + +mpl.figure.prototype._init_header = function () { + var titlebar = document.createElement('div'); + titlebar.classList = + 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix'; + var titletext = document.createElement('div'); + titletext.classList = 'ui-dialog-title'; + titletext.setAttribute( + 'style', + 'width: 100%; text-align: center; padding: 3px;' + ); + titlebar.appendChild(titletext); + this.root.appendChild(titlebar); + this.header = titletext; +}; + +mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {}; + +mpl.figure.prototype._root_extra_style = function (_canvas_div) {}; + +mpl.figure.prototype._init_canvas = function () { + var fig = this; + + var canvas_div = (this.canvas_div = document.createElement('div')); + canvas_div.setAttribute('tabindex', '0'); + canvas_div.setAttribute( + 'style', + 'border: 1px solid #ddd;' + + 'box-sizing: content-box;' + + 'clear: both;' + + 'min-height: 1px;' + + 'min-width: 1px;' + + 'outline: 0;' + + 'overflow: hidden;' + + 'position: relative;' + + 'resize: both;' + + 'z-index: 2;' + ); + + function on_keyboard_event_closure(name) { + return function (event) { + return fig.key_event(event, name); + }; + } + + canvas_div.addEventListener( + 'keydown', + on_keyboard_event_closure('key_press') + ); + canvas_div.addEventListener( + 'keyup', + on_keyboard_event_closure('key_release') + ); + + this._canvas_extra_style(canvas_div); + this.root.appendChild(canvas_div); + + var canvas = (this.canvas = document.createElement('canvas')); + canvas.classList.add('mpl-canvas'); + canvas.setAttribute( + 'style', + 'box-sizing: content-box;' + + 'pointer-events: none;' + + 'position: relative;' + + 'z-index: 0;' + ); + + this.context = canvas.getContext('2d'); + + var backingStore = + this.context.backingStorePixelRatio || + this.context.webkitBackingStorePixelRatio || + this.context.mozBackingStorePixelRatio || + this.context.msBackingStorePixelRatio || + this.context.oBackingStorePixelRatio || + this.context.backingStorePixelRatio || + 1; + + this.ratio = (window.devicePixelRatio || 1) / backingStore; + + var rubberband_canvas = (this.rubberband_canvas = document.createElement( + 'canvas' + )); + rubberband_canvas.setAttribute( + 'style', + 'box-sizing: content-box;' + + 'left: 0;' + + 'pointer-events: none;' + + 'position: absolute;' + + 'top: 0;' + + 'z-index: 1;' + ); + + // Apply a ponyfill if ResizeObserver is not implemented by browser. + if (this.ResizeObserver === undefined) { + if (window.ResizeObserver !== undefined) { + this.ResizeObserver = window.ResizeObserver; + } else { + var obs = _JSXTOOLS_RESIZE_OBSERVER({}); + this.ResizeObserver = obs.ResizeObserver; + } + } + + this.resizeObserverInstance = new this.ResizeObserver(function (entries) { + // There's no need to resize if the WebSocket is not connected: + // - If it is still connecting, then we will get an initial resize from + // Python once it connects. + // - If it has disconnected, then resizing will clear the canvas and + // never get anything back to refill it, so better to not resize and + // keep something visible. + if (fig.ws.readyState != 1) { + return; + } + var nentries = entries.length; + for (var i = 0; i < nentries; i++) { + var entry = entries[i]; + var width, height; + if (entry.contentBoxSize) { + if (entry.contentBoxSize instanceof Array) { + // Chrome 84 implements new version of spec. + width = entry.contentBoxSize[0].inlineSize; + height = entry.contentBoxSize[0].blockSize; + } else { + // Firefox implements old version of spec. + width = entry.contentBoxSize.inlineSize; + height = entry.contentBoxSize.blockSize; + } + } else { + // Chrome <84 implements even older version of spec. + width = entry.contentRect.width; + height = entry.contentRect.height; + } + + // Keep the size of the canvas and rubber band canvas in sync with + // the canvas container. + if (entry.devicePixelContentBoxSize) { + // Chrome 84 implements new version of spec. + canvas.setAttribute( + 'width', + entry.devicePixelContentBoxSize[0].inlineSize + ); + canvas.setAttribute( + 'height', + entry.devicePixelContentBoxSize[0].blockSize + ); + } else { + canvas.setAttribute('width', width * fig.ratio); + canvas.setAttribute('height', height * fig.ratio); + } + /* This rescales the canvas back to display pixels, so that it + * appears correct on HiDPI screens. */ + canvas.style.width = width + 'px'; + canvas.style.height = height + 'px'; + + rubberband_canvas.setAttribute('width', width); + rubberband_canvas.setAttribute('height', height); + + // And update the size in Python. We ignore the initial 0/0 size + // that occurs as the element is placed into the DOM, which should + // otherwise not happen due to the minimum size styling. + if (width != 0 && height != 0) { + fig.request_resize(width, height); + } + } + }); + this.resizeObserverInstance.observe(canvas_div); + + function on_mouse_event_closure(name) { + /* User Agent sniffing is bad, but WebKit is busted: + * https://bugs.webkit.org/show_bug.cgi?id=144526 + * https://bugs.webkit.org/show_bug.cgi?id=181818 + * The worst that happens here is that they get an extra browser + * selection when dragging, if this check fails to catch them. + */ + var UA = navigator.userAgent; + var isWebKit = /AppleWebKit/.test(UA) && !/Chrome/.test(UA); + if(isWebKit) { + return function (event) { + /* This prevents the web browser from automatically changing to + * the text insertion cursor when the button is pressed. We + * want to control all of the cursor setting manually through + * the 'cursor' event from matplotlib */ + event.preventDefault() + return fig.mouse_event(event, name); + }; + } else { + return function (event) { + return fig.mouse_event(event, name); + }; + } + } + + canvas_div.addEventListener( + 'mousedown', + on_mouse_event_closure('button_press') + ); + canvas_div.addEventListener( + 'mouseup', + on_mouse_event_closure('button_release') + ); + canvas_div.addEventListener( + 'dblclick', + on_mouse_event_closure('dblclick') + ); + // Throttle sequential mouse events to 1 every 20ms. + canvas_div.addEventListener( + 'mousemove', + on_mouse_event_closure('motion_notify') + ); + + canvas_div.addEventListener( + 'mouseenter', + on_mouse_event_closure('figure_enter') + ); + canvas_div.addEventListener( + 'mouseleave', + on_mouse_event_closure('figure_leave') + ); + + canvas_div.addEventListener('wheel', function (event) { + if (event.deltaY < 0) { + event.step = 1; + } else { + event.step = -1; + } + on_mouse_event_closure('scroll')(event); + }); + + canvas_div.appendChild(canvas); + canvas_div.appendChild(rubberband_canvas); + + this.rubberband_context = rubberband_canvas.getContext('2d'); + this.rubberband_context.strokeStyle = '#000000'; + + this._resize_canvas = function (width, height, forward) { + if (forward) { + canvas_div.style.width = width + 'px'; + canvas_div.style.height = height + 'px'; + } + }; + + // Disable right mouse context menu. + canvas_div.addEventListener('contextmenu', function (_e) { + event.preventDefault(); + return false; + }); + + function set_focus() { + canvas.focus(); + canvas_div.focus(); + } + + window.setTimeout(set_focus, 100); +}; + +mpl.figure.prototype._init_toolbar = function () { + var fig = this; + + var toolbar = document.createElement('div'); + toolbar.classList = 'mpl-toolbar'; + this.root.appendChild(toolbar); + + function on_click_closure(name) { + return function (_event) { + return fig.toolbar_button_onclick(name); + }; + } + + function on_mouseover_closure(tooltip) { + return function (event) { + if (!event.currentTarget.disabled) { + return fig.toolbar_button_onmouseover(tooltip); + } + }; + } + + fig.buttons = {}; + var buttonGroup = document.createElement('div'); + buttonGroup.classList = 'mpl-button-group'; + for (var toolbar_ind in mpl.toolbar_items) { + var name = mpl.toolbar_items[toolbar_ind][0]; + var tooltip = mpl.toolbar_items[toolbar_ind][1]; + var image = mpl.toolbar_items[toolbar_ind][2]; + var method_name = mpl.toolbar_items[toolbar_ind][3]; + + if (!name) { + /* Instead of a spacer, we start a new button group. */ + if (buttonGroup.hasChildNodes()) { + toolbar.appendChild(buttonGroup); + } + buttonGroup = document.createElement('div'); + buttonGroup.classList = 'mpl-button-group'; + continue; + } + + var button = (fig.buttons[name] = document.createElement('button')); + button.classList = 'mpl-widget'; + button.setAttribute('role', 'button'); + button.setAttribute('aria-disabled', 'false'); + button.addEventListener('click', on_click_closure(method_name)); + button.addEventListener('mouseover', on_mouseover_closure(tooltip)); + + var icon_img = document.createElement('img'); + icon_img.src = '_images/' + image + '.png'; + icon_img.srcset = '_images/' + image + '_large.png 2x'; + icon_img.alt = tooltip; + button.appendChild(icon_img); + + buttonGroup.appendChild(button); + } + + if (buttonGroup.hasChildNodes()) { + toolbar.appendChild(buttonGroup); + } + + var fmt_picker = document.createElement('select'); + fmt_picker.classList = 'mpl-widget'; + toolbar.appendChild(fmt_picker); + this.format_dropdown = fmt_picker; + + for (var ind in mpl.extensions) { + var fmt = mpl.extensions[ind]; + var option = document.createElement('option'); + option.selected = fmt === mpl.default_extension; + option.innerHTML = fmt; + fmt_picker.appendChild(option); + } + + var status_bar = document.createElement('span'); + status_bar.classList = 'mpl-message'; + toolbar.appendChild(status_bar); + this.message = status_bar; +}; + +mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) { + // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client, + // which will in turn request a refresh of the image. + this.send_message('resize', { width: x_pixels, height: y_pixels }); +}; + +mpl.figure.prototype.send_message = function (type, properties) { + properties['type'] = type; + properties['figure_id'] = this.id; + this.ws.send(JSON.stringify(properties)); +}; + +mpl.figure.prototype.send_draw_message = function () { + if (!this.waiting) { + this.waiting = true; + this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id })); + } +}; + +mpl.figure.prototype.handle_save = function (fig, _msg) { + var format_dropdown = fig.format_dropdown; + var format = format_dropdown.options[format_dropdown.selectedIndex].value; + fig.ondownload(fig, format); +}; + +mpl.figure.prototype.handle_resize = function (fig, msg) { + var size = msg['size']; + if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) { + fig._resize_canvas(size[0], size[1], msg['forward']); + fig.send_message('refresh', {}); + } +}; + +mpl.figure.prototype.handle_rubberband = function (fig, msg) { + var x0 = msg['x0'] / fig.ratio; + var y0 = (fig.canvas.height - msg['y0']) / fig.ratio; + var x1 = msg['x1'] / fig.ratio; + var y1 = (fig.canvas.height - msg['y1']) / fig.ratio; + x0 = Math.floor(x0) + 0.5; + y0 = Math.floor(y0) + 0.5; + x1 = Math.floor(x1) + 0.5; + y1 = Math.floor(y1) + 0.5; + var min_x = Math.min(x0, x1); + var min_y = Math.min(y0, y1); + var width = Math.abs(x1 - x0); + var height = Math.abs(y1 - y0); + + fig.rubberband_context.clearRect( + 0, + 0, + fig.canvas.width / fig.ratio, + fig.canvas.height / fig.ratio + ); + + fig.rubberband_context.strokeRect(min_x, min_y, width, height); +}; + +mpl.figure.prototype.handle_figure_label = function (fig, msg) { + // Updates the figure title. + fig.header.textContent = msg['label']; +}; + +mpl.figure.prototype.handle_cursor = function (fig, msg) { + fig.canvas_div.style.cursor = msg['cursor']; +}; + +mpl.figure.prototype.handle_message = function (fig, msg) { + fig.message.textContent = msg['message']; +}; + +mpl.figure.prototype.handle_draw = function (fig, _msg) { + // Request the server to send over a new figure. + fig.send_draw_message(); +}; + +mpl.figure.prototype.handle_image_mode = function (fig, msg) { + fig.image_mode = msg['mode']; +}; + +mpl.figure.prototype.handle_history_buttons = function (fig, msg) { + for (var key in msg) { + if (!(key in fig.buttons)) { + continue; + } + fig.buttons[key].disabled = !msg[key]; + fig.buttons[key].setAttribute('aria-disabled', !msg[key]); + } +}; + +mpl.figure.prototype.handle_navigate_mode = function (fig, msg) { + if (msg['mode'] === 'PAN') { + fig.buttons['Pan'].classList.add('active'); + fig.buttons['Zoom'].classList.remove('active'); + } else if (msg['mode'] === 'ZOOM') { + fig.buttons['Pan'].classList.remove('active'); + fig.buttons['Zoom'].classList.add('active'); + } else { + fig.buttons['Pan'].classList.remove('active'); + fig.buttons['Zoom'].classList.remove('active'); + } +}; + +mpl.figure.prototype.updated_canvas_event = function () { + // Called whenever the canvas gets updated. + this.send_message('ack', {}); +}; + +// A function to construct a web socket function for onmessage handling. +// Called in the figure constructor. +mpl.figure.prototype._make_on_message_function = function (fig) { + return function socket_on_message(evt) { + if (evt.data instanceof Blob) { + var img = evt.data; + if (img.type !== 'image/png') { + /* FIXME: We get "Resource interpreted as Image but + * transferred with MIME type text/plain:" errors on + * Chrome. But how to set the MIME type? It doesn't seem + * to be part of the websocket stream */ + img.type = 'image/png'; + } + + /* Free the memory for the previous frames */ + if (fig.imageObj.src) { + (window.URL || window.webkitURL).revokeObjectURL( + fig.imageObj.src + ); + } + + fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL( + img + ); + fig.updated_canvas_event(); + fig.waiting = false; + return; + } else if ( + typeof evt.data === 'string' && + evt.data.slice(0, 21) === 'data:image/png;base64' + ) { + fig.imageObj.src = evt.data; + fig.updated_canvas_event(); + fig.waiting = false; + return; + } + + var msg = JSON.parse(evt.data); + var msg_type = msg['type']; + + // Call the "handle_{type}" callback, which takes + // the figure and JSON message as its only arguments. + try { + var callback = fig['handle_' + msg_type]; + } catch (e) { + console.log( + "No handler for the '" + msg_type + "' message type: ", + msg + ); + return; + } + + if (callback) { + try { + // console.log("Handling '" + msg_type + "' message: ", msg); + callback(fig, msg); + } catch (e) { + console.log( + "Exception inside the 'handler_" + msg_type + "' callback:", + e, + e.stack, + msg + ); + } + } + }; +}; + +function getModifiers(event) { + var mods = []; + if (event.ctrlKey) { + mods.push('ctrl'); + } + if (event.altKey) { + mods.push('alt'); + } + if (event.shiftKey) { + mods.push('shift'); + } + if (event.metaKey) { + mods.push('meta'); + } + return mods; +} + +/* + * return a copy of an object with only non-object keys + * we need this to avoid circular references + * https://stackoverflow.com/a/24161582/3208463 + */ +function simpleKeys(original) { + return Object.keys(original).reduce(function (obj, key) { + if (typeof original[key] !== 'object') { + obj[key] = original[key]; + } + return obj; + }, {}); +} + +mpl.figure.prototype.mouse_event = function (event, name) { + if (name === 'button_press') { + this.canvas.focus(); + this.canvas_div.focus(); + } + + // from https://stackoverflow.com/q/1114465 + var boundingRect = this.canvas.getBoundingClientRect(); + var x = (event.clientX - boundingRect.left) * this.ratio; + var y = (event.clientY - boundingRect.top) * this.ratio; + + this.send_message(name, { + x: x, + y: y, + button: event.button, + step: event.step, + buttons: event.buttons, + modifiers: getModifiers(event), + guiEvent: simpleKeys(event), + }); + + return false; +}; + +mpl.figure.prototype._key_event_extra = function (_event, _name) { + // Handle any extra behaviour associated with a key event +}; + +mpl.figure.prototype.key_event = function (event, name) { + // Prevent repeat events + if (name === 'key_press') { + if (event.key === this._key) { + return; + } else { + this._key = event.key; + } + } + if (name === 'key_release') { + this._key = null; + } + + var value = ''; + if (event.ctrlKey && event.key !== 'Control') { + value += 'ctrl+'; + } + else if (event.altKey && event.key !== 'Alt') { + value += 'alt+'; + } + else if (event.shiftKey && event.key !== 'Shift') { + value += 'shift+'; + } + + value += 'k' + event.key; + + this._key_event_extra(event, name); + + this.send_message(name, { key: value, guiEvent: simpleKeys(event) }); + return false; +}; + +mpl.figure.prototype.toolbar_button_onclick = function (name) { + if (name === 'download') { + this.handle_save(this, null); + } else { + this.send_message('toolbar_button', { name: name }); + } +}; + +mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) { + this.message.textContent = tooltip; +}; + +///////////////// REMAINING CONTENT GENERATED BY embed_js.py ///////////////// +// prettier-ignore +var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError("Constructor requires 'new' operator");i.set(this,e)}function h(){throw new TypeError("Function is not a constructor")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl_tornado.js b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl_tornado.js new file mode 100644 index 0000000000000000000000000000000000000000..b3cab8b7b906d95fcfe221bf3aaf04722004f7a6 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/mpl_tornado.js @@ -0,0 +1,8 @@ +/* This .js file contains functions for matplotlib's built-in + tornado-based server, that are not relevant when embedding WebAgg + in another web application. */ + +/* exported mpl_ondownload */ +function mpl_ondownload(figure, format) { + window.open(figure.id + '/download.' + format, '_blank'); +} diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/nbagg_mpl.js b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/nbagg_mpl.js new file mode 100644 index 0000000000000000000000000000000000000000..26d79ff4e1da11d3c362f748e75b22026cc8438a --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/js/nbagg_mpl.js @@ -0,0 +1,275 @@ +/* global mpl */ + +var comm_websocket_adapter = function (comm) { + // Create a "websocket"-like object which calls the given IPython comm + // object with the appropriate methods. Currently this is a non binary + // socket, so there is still some room for performance tuning. + var ws = {}; + + ws.binaryType = comm.kernel.ws.binaryType; + ws.readyState = comm.kernel.ws.readyState; + function updateReadyState(_event) { + if (comm.kernel.ws) { + ws.readyState = comm.kernel.ws.readyState; + } else { + ws.readyState = 3; // Closed state. + } + } + comm.kernel.ws.addEventListener('open', updateReadyState); + comm.kernel.ws.addEventListener('close', updateReadyState); + comm.kernel.ws.addEventListener('error', updateReadyState); + + ws.close = function () { + comm.close(); + }; + ws.send = function (m) { + //console.log('sending', m); + comm.send(m); + }; + // Register the callback with on_msg. + comm.on_msg(function (msg) { + //console.log('receiving', msg['content']['data'], msg); + var data = msg['content']['data']; + if (data['blob'] !== undefined) { + data = { + data: new Blob(msg['buffers'], { type: data['blob'] }), + }; + } + // Pass the mpl event to the overridden (by mpl) onmessage function. + ws.onmessage(data); + }); + return ws; +}; + +mpl.mpl_figure_comm = function (comm, msg) { + // This is the function which gets called when the mpl process + // starts-up an IPython Comm through the "matplotlib" channel. + + var id = msg.content.data.id; + // Get hold of the div created by the display call when the Comm + // socket was opened in Python. + var element = document.getElementById(id); + var ws_proxy = comm_websocket_adapter(comm); + + function ondownload(figure, _format) { + window.open(figure.canvas.toDataURL()); + } + + var fig = new mpl.figure(id, ws_proxy, ondownload, element); + + // Call onopen now - mpl needs it, as it is assuming we've passed it a real + // web socket which is closed, not our websocket->open comm proxy. + ws_proxy.onopen(); + + fig.parent_element = element; + fig.cell_info = mpl.find_output_cell("
"); + if (!fig.cell_info) { + console.error('Failed to find cell for figure', id, fig); + return; + } + fig.cell_info[0].output_area.element.on( + 'cleared', + { fig: fig }, + fig._remove_fig_handler + ); +}; + +mpl.figure.prototype.handle_close = function (fig, msg) { + var width = fig.canvas.width / fig.ratio; + fig.cell_info[0].output_area.element.off( + 'cleared', + fig._remove_fig_handler + ); + fig.resizeObserverInstance.unobserve(fig.canvas_div); + + // Update the output cell to use the data from the current canvas. + fig.push_to_output(); + var dataURL = fig.canvas.toDataURL(); + // Re-enable the keyboard manager in IPython - without this line, in FF, + // the notebook keyboard shortcuts fail. + IPython.keyboard_manager.enable(); + fig.parent_element.innerHTML = + ''; + fig.close_ws(fig, msg); +}; + +mpl.figure.prototype.close_ws = function (fig, msg) { + fig.send_message('closing', msg); + // fig.ws.close() +}; + +mpl.figure.prototype.push_to_output = function (_remove_interactive) { + // Turn the data on the canvas into data in the output cell. + var width = this.canvas.width / this.ratio; + var dataURL = this.canvas.toDataURL(); + this.cell_info[1]['text/html'] = + ''; +}; + +mpl.figure.prototype.updated_canvas_event = function () { + // Tell IPython that the notebook contents must change. + IPython.notebook.set_dirty(true); + this.send_message('ack', {}); + var fig = this; + // Wait a second, then push the new image to the DOM so + // that it is saved nicely (might be nice to debounce this). + setTimeout(function () { + fig.push_to_output(); + }, 1000); +}; + +mpl.figure.prototype._init_toolbar = function () { + var fig = this; + + var toolbar = document.createElement('div'); + toolbar.classList = 'btn-toolbar'; + this.root.appendChild(toolbar); + + function on_click_closure(name) { + return function (_event) { + return fig.toolbar_button_onclick(name); + }; + } + + function on_mouseover_closure(tooltip) { + return function (event) { + if (!event.currentTarget.disabled) { + return fig.toolbar_button_onmouseover(tooltip); + } + }; + } + + fig.buttons = {}; + var buttonGroup = document.createElement('div'); + buttonGroup.classList = 'btn-group'; + var button; + for (var toolbar_ind in mpl.toolbar_items) { + var name = mpl.toolbar_items[toolbar_ind][0]; + var tooltip = mpl.toolbar_items[toolbar_ind][1]; + var image = mpl.toolbar_items[toolbar_ind][2]; + var method_name = mpl.toolbar_items[toolbar_ind][3]; + + if (!name) { + /* Instead of a spacer, we start a new button group. */ + if (buttonGroup.hasChildNodes()) { + toolbar.appendChild(buttonGroup); + } + buttonGroup = document.createElement('div'); + buttonGroup.classList = 'btn-group'; + continue; + } + + button = fig.buttons[name] = document.createElement('button'); + button.classList = 'btn btn-default'; + button.href = '#'; + button.title = name; + button.innerHTML = ''; + button.addEventListener('click', on_click_closure(method_name)); + button.addEventListener('mouseover', on_mouseover_closure(tooltip)); + buttonGroup.appendChild(button); + } + + if (buttonGroup.hasChildNodes()) { + toolbar.appendChild(buttonGroup); + } + + // Add the status bar. + var status_bar = document.createElement('span'); + status_bar.classList = 'mpl-message pull-right'; + toolbar.appendChild(status_bar); + this.message = status_bar; + + // Add the close button to the window. + var buttongrp = document.createElement('div'); + buttongrp.classList = 'btn-group inline pull-right'; + button = document.createElement('button'); + button.classList = 'btn btn-mini btn-primary'; + button.href = '#'; + button.title = 'Stop Interaction'; + button.innerHTML = ''; + button.addEventListener('click', function (_evt) { + fig.handle_close(fig, {}); + }); + button.addEventListener( + 'mouseover', + on_mouseover_closure('Stop Interaction') + ); + buttongrp.appendChild(button); + var titlebar = this.root.querySelector('.ui-dialog-titlebar'); + titlebar.insertBefore(buttongrp, titlebar.firstChild); +}; + +mpl.figure.prototype._remove_fig_handler = function (event) { + var fig = event.data.fig; + if (event.target !== this) { + // Ignore bubbled events from children. + return; + } + fig.close_ws(fig, {}); +}; + +mpl.figure.prototype._root_extra_style = function (el) { + el.style.boxSizing = 'content-box'; // override notebook setting of border-box. +}; + +mpl.figure.prototype._canvas_extra_style = function (el) { + // this is important to make the div 'focusable + el.setAttribute('tabindex', 0); + // reach out to IPython and tell the keyboard manager to turn it's self + // off when our div gets focus + + // location in version 3 + if (IPython.notebook.keyboard_manager) { + IPython.notebook.keyboard_manager.register_events(el); + } else { + // location in version 2 + IPython.keyboard_manager.register_events(el); + } +}; + +mpl.figure.prototype._key_event_extra = function (event, _name) { + // Check for shift+enter + if (event.shiftKey && event.which === 13) { + this.canvas_div.blur(); + // select the cell after this one + var index = IPython.notebook.find_cell_index(this.cell_info[0]); + IPython.notebook.select(index + 1); + } +}; + +mpl.figure.prototype.handle_save = function (fig, _msg) { + fig.ondownload(fig, null); +}; + +mpl.find_output_cell = function (html_output) { + // Return the cell and output element which can be found *uniquely* in the notebook. + // Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook" + // IPython event is triggered only after the cells have been serialised, which for + // our purposes (turning an active figure into a static one), is too late. + var cells = IPython.notebook.get_cells(); + var ncells = cells.length; + for (var i = 0; i < ncells; i++) { + var cell = cells[i]; + if (cell.cell_type === 'code') { + for (var j = 0; j < cell.output_area.outputs.length; j++) { + var data = cell.output_area.outputs[j]; + if (data.data) { + // IPython >= 3 moved mimebundle to data attribute of output + data = data.data; + } + if (data['text/html'] === html_output) { + return [cell, data, j]; + } + } + } + } +}; + +// Register the function which deals with the matplotlib target/channel. +// The kernel may be null if the page has been refreshed. +if (IPython.notebook.kernel !== null) { + IPython.notebook.kernel.comm_manager.register_target( + 'matplotlib', + mpl.mpl_figure_comm + ); +} diff --git a/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/single_figure.html b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/single_figure.html new file mode 100644 index 0000000000000000000000000000000000000000..ceaaab00669ff62e0724eff610dcb74adcff1674 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/backends/web_backend/single_figure.html @@ -0,0 +1,39 @@ + + + + + + + + + + + + matplotlib + + + +
+
+ + diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e75e09e6c0c376e117789e9287d1a95de9acb009 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniIta.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniIta.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c27d42fb250a5881efeccbf9c9dabca18efe958b Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXNonUniIta.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f81717ec1d0c057dcf1be2b9ac4e282fdfbe7987 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..855dec982374b3f452120cbc47e5a892ef51c02b Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f955ca2ad1ba36cd36e185671843448854d517dc Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..6ffd35778fd8eebf304a4842edd92ee49398567a Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf new file mode 100644 index 0000000000000000000000000000000000000000..01ed101cd477dfb112616440bdb6a8a54a30cb67 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1ccf365e8f1635df3d0672a92c416dca0e8ef033 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bf2b66af7620441b260a339358adf5c9628a4d4e Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bd5f93f0e48d5d993b349c160cb2efac071e8599 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf new file mode 100644 index 0000000000000000000000000000000000000000..73b9930f6cf7388f3337355ffc5cc0035c053e34 Binary files /dev/null and b/python_embeded/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf differ diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/kpsewhich.lua b/python_embeded/Lib/site-packages/matplotlib/mpl-data/kpsewhich.lua new file mode 100644 index 0000000000000000000000000000000000000000..8e9172a45082567bee6802113aa40664d1bfc010 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/mpl-data/kpsewhich.lua @@ -0,0 +1,3 @@ +-- see dviread._LuatexKpsewhich +kpse.set_program_name("latex") +while true do print(kpse.lookup(io.read():gsub("\r", ""))); io.flush(); end diff --git a/python_embeded/Lib/site-packages/matplotlib/mpl-data/matplotlibrc b/python_embeded/Lib/site-packages/matplotlib/mpl-data/matplotlibrc new file mode 100644 index 0000000000000000000000000000000000000000..0f6c5694e537a654337902b45cde754fa563a5b4 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/mpl-data/matplotlibrc @@ -0,0 +1,813 @@ +#### MATPLOTLIBRC FORMAT + +## NOTE FOR END USERS: DO NOT EDIT THIS FILE! +## +## This is a sample Matplotlib configuration file - you can find a copy +## of it on your system in site-packages/matplotlib/mpl-data/matplotlibrc +## (relative to your Python installation location). +## DO NOT EDIT IT! +## +## If you wish to change your default style, copy this file to one of the +## following locations: +## Unix/Linux: +## $HOME/.config/matplotlib/matplotlibrc OR +## $XDG_CONFIG_HOME/matplotlib/matplotlibrc (if $XDG_CONFIG_HOME is set) +## Other platforms: +## $HOME/.matplotlib/matplotlibrc +## and edit that copy. +## +## See https://matplotlib.org/stable/users/explain/customizing.html#customizing-with-matplotlibrc-files +## for more details on the paths which are checked for the configuration file. +## +## Blank lines, or lines starting with a comment symbol, are ignored, as are +## trailing comments. Other lines must have the format: +## key: val # optional comment +## +## Formatting: Use PEP8-like style (as enforced in the rest of the codebase). +## All lines start with an additional '#', so that removing all leading '#'s +## yields a valid style file. +## +## Colors: for the color values below, you can either use +## - a Matplotlib color string, such as r, k, or b +## - an RGB tuple, such as (1.0, 0.5, 0.0) +## - a double-quoted hex string, such as "#ff00ff". +## The unquoted string ff00ff is also supported for backward +## compatibility, but is discouraged. +## - a scalar grayscale intensity such as 0.75 +## - a legal html color name, e.g., red, blue, darkslategray +## +## String values may optionally be enclosed in double quotes, which allows +## using the comment character # in the string. +## +## This file (and other style files) must be encoded as utf-8. +## +## Matplotlib configuration are currently divided into following parts: +## - BACKENDS +## - LINES +## - PATCHES +## - HATCHES +## - BOXPLOT +## - FONT +## - TEXT +## - LaTeX +## - AXES +## - DATES +## - TICKS +## - GRIDS +## - LEGEND +## - FIGURE +## - IMAGES +## - CONTOUR PLOTS +## - ERRORBAR PLOTS +## - HISTOGRAM PLOTS +## - SCATTER PLOTS +## - AGG RENDERING +## - PATHS +## - SAVING FIGURES +## - INTERACTIVE KEYMAPS +## - ANIMATION + +##### CONFIGURATION BEGINS HERE + + +## *************************************************************************** +## * BACKENDS * +## *************************************************************************** +## The default backend. If you omit this parameter, the first working +## backend from the following list is used: +## MacOSX QtAgg Gtk4Agg Gtk3Agg TkAgg WxAgg Agg +## Other choices include: +## QtCairo GTK4Cairo GTK3Cairo TkCairo WxCairo Cairo +## Qt5Agg Qt5Cairo Wx # deprecated. +## PS PDF SVG Template +## You can also deploy your own backend outside of Matplotlib by referring to +## the module name (which must be in the PYTHONPATH) as 'module://my_backend'. +##backend: Agg + +## The port to use for the web server in the WebAgg backend. +#webagg.port: 8988 + +## The address on which the WebAgg web server should be reachable +#webagg.address: 127.0.0.1 + +## If webagg.port is unavailable, a number of other random ports will +## be tried until one that is available is found. +#webagg.port_retries: 50 + +## When True, open the web browser to the plot that is shown +#webagg.open_in_browser: True + +## If you are running pyplot inside a GUI and your backend choice +## conflicts, we will automatically try to find a compatible one for +## you if backend_fallback is True +#backend_fallback: True + +#interactive: False +#figure.hooks: # list of dotted.module.name:dotted.callable.name +#toolbar: toolbar2 # {None, toolbar2, toolmanager} +#timezone: UTC # a pytz timezone string, e.g., US/Central or Europe/Paris + + +## *************************************************************************** +## * LINES * +## *************************************************************************** +## See https://matplotlib.org/stable/api/artist_api.html#module-matplotlib.lines +## for more information on line properties. +#lines.linewidth: 1.5 # line width in points +#lines.linestyle: - # solid line +#lines.color: C0 # has no affect on plot(); see axes.prop_cycle +#lines.marker: None # the default marker +#lines.markerfacecolor: auto # the default marker face color +#lines.markeredgecolor: auto # the default marker edge color +#lines.markeredgewidth: 1.0 # the line width around the marker symbol +#lines.markersize: 6 # marker size, in points +#lines.dash_joinstyle: round # {miter, round, bevel} +#lines.dash_capstyle: butt # {butt, round, projecting} +#lines.solid_joinstyle: round # {miter, round, bevel} +#lines.solid_capstyle: projecting # {butt, round, projecting} +#lines.antialiased: True # render lines in antialiased (no jaggies) + +## The three standard dash patterns. These are scaled by the linewidth. +#lines.dashed_pattern: 3.7, 1.6 +#lines.dashdot_pattern: 6.4, 1.6, 1, 1.6 +#lines.dotted_pattern: 1, 1.65 +#lines.scale_dashes: True + +#markers.fillstyle: full # {full, left, right, bottom, top, none} + +#pcolor.shading: auto +#pcolormesh.snap: True # Whether to snap the mesh to pixel boundaries. This is + # provided solely to allow old test images to remain + # unchanged. Set to False to obtain the previous behavior. + +## *************************************************************************** +## * PATCHES * +## *************************************************************************** +## Patches are graphical objects that fill 2D space, like polygons or circles. +## See https://matplotlib.org/stable/api/artist_api.html#module-matplotlib.patches +## for more information on patch properties. +#patch.linewidth: 1.0 # edge width in points. +#patch.facecolor: C0 +#patch.edgecolor: black # By default, Patches and Collections do not draw edges. + # This value is only used if facecolor is "none" + # (an Artist without facecolor and edgecolor would be + # invisible) or if patch.force_edgecolor is True. +#patch.force_edgecolor: False # By default, Patches and Collections do not draw edges. + # Set this to True to draw edges with patch.edgedcolor + # as the default edgecolor. + # This is mainly relevant for styles. +#patch.antialiased: True # render patches in antialiased (no jaggies) + + +## *************************************************************************** +## * HATCHES * +## *************************************************************************** +#hatch.color: black +#hatch.linewidth: 1.0 + + +## *************************************************************************** +## * BOXPLOT * +## *************************************************************************** +#boxplot.notch: False +#boxplot.vertical: True +#boxplot.whiskers: 1.5 +#boxplot.bootstrap: None +#boxplot.patchartist: False +#boxplot.showmeans: False +#boxplot.showcaps: True +#boxplot.showbox: True +#boxplot.showfliers: True +#boxplot.meanline: False + +#boxplot.flierprops.color: black +#boxplot.flierprops.marker: o +#boxplot.flierprops.markerfacecolor: none +#boxplot.flierprops.markeredgecolor: black +#boxplot.flierprops.markeredgewidth: 1.0 +#boxplot.flierprops.markersize: 6 +#boxplot.flierprops.linestyle: none +#boxplot.flierprops.linewidth: 1.0 + +#boxplot.boxprops.color: black +#boxplot.boxprops.linewidth: 1.0 +#boxplot.boxprops.linestyle: - + +#boxplot.whiskerprops.color: black +#boxplot.whiskerprops.linewidth: 1.0 +#boxplot.whiskerprops.linestyle: - + +#boxplot.capprops.color: black +#boxplot.capprops.linewidth: 1.0 +#boxplot.capprops.linestyle: - + +#boxplot.medianprops.color: C1 +#boxplot.medianprops.linewidth: 1.0 +#boxplot.medianprops.linestyle: - + +#boxplot.meanprops.color: C2 +#boxplot.meanprops.marker: ^ +#boxplot.meanprops.markerfacecolor: C2 +#boxplot.meanprops.markeredgecolor: C2 +#boxplot.meanprops.markersize: 6 +#boxplot.meanprops.linestyle: -- +#boxplot.meanprops.linewidth: 1.0 + + +## *************************************************************************** +## * FONT * +## *************************************************************************** +## The font properties used by `text.Text`. +## See https://matplotlib.org/stable/api/font_manager_api.html for more information +## on font properties. The 6 font properties used for font matching are +## given below with their default values. +## +## The font.family property can take either a single or multiple entries of any +## combination of concrete font names (not supported when rendering text with +## usetex) or the following five generic values: +## - 'serif' (e.g., Times), +## - 'sans-serif' (e.g., Helvetica), +## - 'cursive' (e.g., Zapf-Chancery), +## - 'fantasy' (e.g., Western), and +## - 'monospace' (e.g., Courier). +## Each of these values has a corresponding default list of font names +## (font.serif, etc.); the first available font in the list is used. Note that +## for font.serif, font.sans-serif, and font.monospace, the first element of +## the list (a DejaVu font) will always be used because DejaVu is shipped with +## Matplotlib and is thus guaranteed to be available; the other entries are +## left as examples of other possible values. +## +## The font.style property has three values: normal (or roman), italic +## or oblique. The oblique style will be used for italic, if it is not +## present. +## +## The font.variant property has two values: normal or small-caps. For +## TrueType fonts, which are scalable fonts, small-caps is equivalent +## to using a font size of 'smaller', or about 83 % of the current font +## size. +## +## The font.weight property has effectively 13 values: normal, bold, +## bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as +## 400, and bold is 700. bolder and lighter are relative values with +## respect to the current weight. +## +## The font.stretch property has 11 values: ultra-condensed, +## extra-condensed, condensed, semi-condensed, normal, semi-expanded, +## expanded, extra-expanded, ultra-expanded, wider, and narrower. This +## property is not currently implemented. +## +## The font.size property is the default font size for text, given in points. +## 10 pt is the standard value. +## +## Note that font.size controls default text sizes. To configure +## special text sizes tick labels, axes, labels, title, etc., see the rc +## settings for axes and ticks. Special text sizes can be defined +## relative to font.size, using the following values: xx-small, x-small, +## small, medium, large, x-large, xx-large, larger, or smaller + +#font.family: sans-serif +#font.style: normal +#font.variant: normal +#font.weight: normal +#font.stretch: normal +#font.size: 10.0 + +#font.serif: DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif +#font.sans-serif: DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif +#font.cursive: Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive +#font.fantasy: Chicago, Charcoal, Impact, Western, xkcd script, fantasy +#font.monospace: DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace + + +## *************************************************************************** +## * TEXT * +## *************************************************************************** +## The text properties used by `text.Text`. +## See https://matplotlib.org/stable/api/artist_api.html#module-matplotlib.text +## for more information on text properties +#text.color: black + +## FreeType hinting flag ("foo" corresponds to FT_LOAD_FOO); may be one of the +## following (Proprietary Matplotlib-specific synonyms are given in parentheses, +## but their use is discouraged): +## - default: Use the font's native hinter if possible, else FreeType's auto-hinter. +## ("either" is a synonym). +## - no_autohint: Use the font's native hinter if possible, else don't hint. +## ("native" is a synonym.) +## - force_autohint: Use FreeType's auto-hinter. ("auto" is a synonym.) +## - no_hinting: Disable hinting. ("none" is a synonym.) +#text.hinting: force_autohint + +#text.hinting_factor: 8 # Specifies the amount of softness for hinting in the + # horizontal direction. A value of 1 will hint to full + # pixels. A value of 2 will hint to half pixels etc. +#text.kerning_factor: 0 # Specifies the scaling factor for kerning values. This + # is provided solely to allow old test images to remain + # unchanged. Set to 6 to obtain previous behavior. + # Values other than 0 or 6 have no defined meaning. +#text.antialiased: True # If True (default), the text will be antialiased. + # This only affects raster outputs. +#text.parse_math: True # Use mathtext if there is an even number of unescaped + # dollar signs. + + +## *************************************************************************** +## * LaTeX * +## *************************************************************************** +## For more information on LaTeX properties, see +## https://matplotlib.org/stable/users/explain/text/usetex.html +#text.usetex: False # use latex for all text handling. The following fonts + # are supported through the usual rc parameter settings: + # new century schoolbook, bookman, times, palatino, + # zapf chancery, charter, serif, sans-serif, helvetica, + # avant garde, courier, monospace, computer modern roman, + # computer modern sans serif, computer modern typewriter +#text.latex.preamble: # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES + # AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP + # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO. + # text.latex.preamble is a single line of LaTeX code that + # will be passed on to the LaTeX system. It may contain + # any code that is valid for the LaTeX "preamble", i.e. + # between the "\documentclass" and "\begin{document}" + # statements. + # Note that it has to be put on a single line, which may + # become quite long. + # The following packages are always loaded with usetex, + # so beware of package collisions: + # geometry, inputenc, type1cm. + # PostScript (PSNFSS) font packages may also be + # loaded, depending on your font settings. + +## The following settings allow you to select the fonts in math mode. +#mathtext.fontset: dejavusans # Should be 'dejavusans' (default), + # 'dejavuserif', 'cm' (Computer Modern), 'stix', + # 'stixsans' or 'custom' +## "mathtext.fontset: custom" is defined by the mathtext.bf, .cal, .it, ... +## settings which map a TeX font name to a fontconfig font pattern. (These +## settings are not used for other font sets.) +#mathtext.bf: sans:bold +#mathtext.bfit: sans:italic:bold +#mathtext.cal: cursive +#mathtext.it: sans:italic +#mathtext.rm: sans +#mathtext.sf: sans +#mathtext.tt: monospace +#mathtext.fallback: cm # Select fallback font from ['cm' (Computer Modern), 'stix' + # 'stixsans'] when a symbol cannot be found in one of the + # custom math fonts. Select 'None' to not perform fallback + # and replace the missing character by a dummy symbol. +#mathtext.default: it # The default font to use for math. + # Can be any of the LaTeX font names, including + # the special name "regular" for the same font + # used in regular text. + + +## *************************************************************************** +## * AXES * +## *************************************************************************** +## Following are default face and edge colors, default tick sizes, +## default font sizes for tick labels, and so on. See +## https://matplotlib.org/stable/api/axes_api.html#module-matplotlib.axes +#axes.facecolor: white # axes background color +#axes.edgecolor: black # axes edge color +#axes.linewidth: 0.8 # edge line width +#axes.grid: False # display grid or not +#axes.grid.axis: both # which axis the grid should apply to +#axes.grid.which: major # grid lines at {major, minor, both} ticks +#axes.titlelocation: center # alignment of the title: {left, right, center} +#axes.titlesize: large # font size of the axes title +#axes.titleweight: normal # font weight of title +#axes.titlecolor: auto # color of the axes title, auto falls back to + # text.color as default value +#axes.titley: None # position title (axes relative units). None implies auto +#axes.titlepad: 6.0 # pad between axes and title in points +#axes.labelsize: medium # font size of the x and y labels +#axes.labelpad: 4.0 # space between label and axis +#axes.labelweight: normal # weight of the x and y labels +#axes.labelcolor: black +#axes.axisbelow: line # draw axis gridlines and ticks: + # - below patches (True) + # - above patches but below lines ('line') + # - above all (False) + +#axes.formatter.limits: -5, 6 # use scientific notation if log10 + # of the axis range is smaller than the + # first or larger than the second +#axes.formatter.use_locale: False # When True, format tick labels + # according to the user's locale. + # For example, use ',' as a decimal + # separator in the fr_FR locale. +#axes.formatter.use_mathtext: False # When True, use mathtext for scientific + # notation. +#axes.formatter.min_exponent: 0 # minimum exponent to format in scientific notation +#axes.formatter.useoffset: True # If True, the tick label formatter + # will default to labeling ticks relative + # to an offset when the data range is + # small compared to the minimum absolute + # value of the data. +#axes.formatter.offset_threshold: 4 # When useoffset is True, the offset + # will be used when it can remove + # at least this number of significant + # digits from tick labels. + +#axes.spines.left: True # display axis spines +#axes.spines.bottom: True +#axes.spines.top: True +#axes.spines.right: True + +#axes.unicode_minus: True # use Unicode for the minus symbol rather than hyphen. See + # https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes +#axes.prop_cycle: cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf']) + # color cycle for plot lines as list of string color specs: + # single letter, long name, or web-style hex + # As opposed to all other parameters in this file, the color + # values must be enclosed in quotes for this parameter, + # e.g. '1f77b4', instead of 1f77b4. + # See also https://matplotlib.org/stable/users/explain/artists/color_cycle.html + # for more details on prop_cycle usage. +#axes.xmargin: .05 # x margin. See `axes.Axes.margins` +#axes.ymargin: .05 # y margin. See `axes.Axes.margins` +#axes.zmargin: .05 # z margin. See `axes.Axes.margins` +#axes.autolimit_mode: data # If "data", use axes.xmargin and axes.ymargin as is. + # If "round_numbers", after application of margins, axis + # limits are further expanded to the nearest "round" number. +#polaraxes.grid: True # display grid on polar axes +#axes3d.grid: True # display grid on 3D axes +#axes3d.automargin: False # automatically add margin when manually setting 3D axis limits + +#axes3d.xaxis.panecolor: (0.95, 0.95, 0.95, 0.5) # background pane on 3D axes +#axes3d.yaxis.panecolor: (0.90, 0.90, 0.90, 0.5) # background pane on 3D axes +#axes3d.zaxis.panecolor: (0.925, 0.925, 0.925, 0.5) # background pane on 3D axes + +#axes3d.mouserotationstyle: arcball # {azel, trackball, sphere, arcball} + # See also https://matplotlib.org/stable/api/toolkits/mplot3d/view_angles.html#rotation-with-mouse +#axes3d.trackballsize: 0.667 # trackball diameter, in units of the Axes bbox +#axes3d.trackballborder: 0.2 # trackball border width, in units of the Axes bbox (only for 'sphere' and 'arcball' style) + +## *************************************************************************** +## * AXIS * +## *************************************************************************** +#xaxis.labellocation: center # alignment of the xaxis label: {left, right, center} +#yaxis.labellocation: center # alignment of the yaxis label: {bottom, top, center} + + +## *************************************************************************** +## * DATES * +## *************************************************************************** +## These control the default format strings used in AutoDateFormatter. +## Any valid format datetime format string can be used (see the python +## `datetime` for details). For example, by using: +## - '%x' will use the locale date representation +## - '%X' will use the locale time representation +## - '%c' will use the full locale datetime representation +## These values map to the scales: +## {'year': 365, 'month': 30, 'day': 1, 'hour': 1/24, 'minute': 1 / (24 * 60)} + +#date.autoformatter.year: %Y +#date.autoformatter.month: %Y-%m +#date.autoformatter.day: %Y-%m-%d +#date.autoformatter.hour: %m-%d %H +#date.autoformatter.minute: %d %H:%M +#date.autoformatter.second: %H:%M:%S +#date.autoformatter.microsecond: %M:%S.%f +## The reference date for Matplotlib's internal date representation +## See https://matplotlib.org/stable/gallery/ticks/date_precision_and_epochs.html +#date.epoch: 1970-01-01T00:00:00 +## 'auto', 'concise': +#date.converter: auto +## For auto converter whether to use interval_multiples: +#date.interval_multiples: True + +## *************************************************************************** +## * TICKS * +## *************************************************************************** +## See https://matplotlib.org/stable/api/axis_api.html#matplotlib.axis.Tick +#xtick.top: False # draw ticks on the top side +#xtick.bottom: True # draw ticks on the bottom side +#xtick.labeltop: False # draw label on the top +#xtick.labelbottom: True # draw label on the bottom +#xtick.major.size: 3.5 # major tick size in points +#xtick.minor.size: 2 # minor tick size in points +#xtick.major.width: 0.8 # major tick width in points +#xtick.minor.width: 0.6 # minor tick width in points +#xtick.major.pad: 3.5 # distance to major tick label in points +#xtick.minor.pad: 3.4 # distance to the minor tick label in points +#xtick.color: black # color of the ticks +#xtick.labelcolor: inherit # color of the tick labels or inherit from xtick.color +#xtick.labelsize: medium # font size of the tick labels +#xtick.direction: out # direction: {in, out, inout} +#xtick.minor.visible: False # visibility of minor ticks on x-axis +#xtick.major.top: True # draw x axis top major ticks +#xtick.major.bottom: True # draw x axis bottom major ticks +#xtick.minor.top: True # draw x axis top minor ticks +#xtick.minor.bottom: True # draw x axis bottom minor ticks +#xtick.minor.ndivs: auto # number of minor ticks between the major ticks on x-axis +#xtick.alignment: center # alignment of xticks + +#ytick.left: True # draw ticks on the left side +#ytick.right: False # draw ticks on the right side +#ytick.labelleft: True # draw tick labels on the left side +#ytick.labelright: False # draw tick labels on the right side +#ytick.major.size: 3.5 # major tick size in points +#ytick.minor.size: 2 # minor tick size in points +#ytick.major.width: 0.8 # major tick width in points +#ytick.minor.width: 0.6 # minor tick width in points +#ytick.major.pad: 3.5 # distance to major tick label in points +#ytick.minor.pad: 3.4 # distance to the minor tick label in points +#ytick.color: black # color of the ticks +#ytick.labelcolor: inherit # color of the tick labels or inherit from ytick.color +#ytick.labelsize: medium # font size of the tick labels +#ytick.direction: out # direction: {in, out, inout} +#ytick.minor.visible: False # visibility of minor ticks on y-axis +#ytick.major.left: True # draw y axis left major ticks +#ytick.major.right: True # draw y axis right major ticks +#ytick.minor.left: True # draw y axis left minor ticks +#ytick.minor.right: True # draw y axis right minor ticks +#ytick.minor.ndivs: auto # number of minor ticks between the major ticks on y-axis +#ytick.alignment: center_baseline # alignment of yticks + + +## *************************************************************************** +## * GRIDS * +## *************************************************************************** +#grid.color: "#b0b0b0" # grid color +#grid.linestyle: - # solid +#grid.linewidth: 0.8 # in points +#grid.alpha: 1.0 # transparency, between 0.0 and 1.0 + + +## *************************************************************************** +## * LEGEND * +## *************************************************************************** +#legend.loc: best +#legend.frameon: True # if True, draw the legend on a background patch +#legend.framealpha: 0.8 # legend patch transparency +#legend.facecolor: inherit # inherit from axes.facecolor; or color spec +#legend.edgecolor: 0.8 # background patch boundary color +#legend.fancybox: True # if True, use a rounded box for the + # legend background, else a rectangle +#legend.shadow: False # if True, give background a shadow effect +#legend.numpoints: 1 # the number of marker points in the legend line +#legend.scatterpoints: 1 # number of scatter points +#legend.markerscale: 1.0 # the relative size of legend markers vs. original +#legend.fontsize: medium +#legend.labelcolor: None +#legend.title_fontsize: None # None sets to the same as the default axes. + +## Dimensions as fraction of font size: +#legend.borderpad: 0.4 # border whitespace +#legend.labelspacing: 0.5 # the vertical space between the legend entries +#legend.handlelength: 2.0 # the length of the legend lines +#legend.handleheight: 0.7 # the height of the legend handle +#legend.handletextpad: 0.8 # the space between the legend line and legend text +#legend.borderaxespad: 0.5 # the border between the axes and legend edge +#legend.columnspacing: 2.0 # column separation + + +## *************************************************************************** +## * FIGURE * +## *************************************************************************** +## See https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure +#figure.titlesize: large # size of the figure title (``Figure.suptitle()``) +#figure.titleweight: normal # weight of the figure title +#figure.labelsize: large # size of the figure label (``Figure.sup[x|y]label()``) +#figure.labelweight: normal # weight of the figure label +#figure.figsize: 6.4, 4.8 # figure size in inches +#figure.dpi: 100 # figure dots per inch +#figure.facecolor: white # figure face color +#figure.edgecolor: white # figure edge color +#figure.frameon: True # enable figure frame +#figure.max_open_warning: 20 # The maximum number of figures to open through + # the pyplot interface before emitting a warning. + # If less than one this feature is disabled. +#figure.raise_window : True # Raise the GUI window to front when show() is called. + +## The figure subplot parameters. All dimensions are a fraction of the figure width and height. +#figure.subplot.left: 0.125 # the left side of the subplots of the figure +#figure.subplot.right: 0.9 # the right side of the subplots of the figure +#figure.subplot.bottom: 0.11 # the bottom of the subplots of the figure +#figure.subplot.top: 0.88 # the top of the subplots of the figure +#figure.subplot.wspace: 0.2 # the amount of width reserved for space between subplots, + # expressed as a fraction of the average axis width +#figure.subplot.hspace: 0.2 # the amount of height reserved for space between subplots, + # expressed as a fraction of the average axis height + +## Figure layout +#figure.autolayout: False # When True, automatically adjust subplot + # parameters to make the plot fit the figure + # using `tight_layout` +#figure.constrained_layout.use: False # When True, automatically make plot + # elements fit on the figure. (Not + # compatible with `autolayout`, above). +## Padding (in inches) around axes; defaults to 3/72 inches, i.e. 3 points. +#figure.constrained_layout.h_pad: 0.04167 +#figure.constrained_layout.w_pad: 0.04167 +## Spacing between subplots, relative to the subplot sizes. Much smaller than for +## tight_layout (figure.subplot.hspace, figure.subplot.wspace) as constrained_layout +## already takes surrounding texts (titles, labels, # ticklabels) into account. +#figure.constrained_layout.hspace: 0.02 +#figure.constrained_layout.wspace: 0.02 + + +## *************************************************************************** +## * IMAGES * +## *************************************************************************** +#image.aspect: equal # {equal, auto} or a number +#image.interpolation: auto # see help(imshow) for options +#image.interpolation_stage: auto # see help(imshow) for options +#image.cmap: viridis # A colormap name (plasma, magma, etc.) +#image.lut: 256 # the size of the colormap lookup table +#image.origin: upper # {lower, upper} +#image.resample: True +#image.composite_image: True # When True, all the images on a set of axes are + # combined into a single composite image before + # saving a figure as a vector graphics file, + # such as a PDF. + + +## *************************************************************************** +## * CONTOUR PLOTS * +## *************************************************************************** +#contour.negative_linestyle: dashed # string or on-off ink sequence +#contour.corner_mask: True # {True, False} +#contour.linewidth: None # {float, None} Size of the contour line + # widths. If set to None, it falls back to + # `line.linewidth`. +#contour.algorithm: mpl2014 # {mpl2005, mpl2014, serial, threaded} + + +## *************************************************************************** +## * ERRORBAR PLOTS * +## *************************************************************************** +#errorbar.capsize: 0 # length of end cap on error bars in pixels + + +## *************************************************************************** +## * HISTOGRAM PLOTS * +## *************************************************************************** +#hist.bins: 10 # The default number of histogram bins or 'auto'. + + +## *************************************************************************** +## * SCATTER PLOTS * +## *************************************************************************** +#scatter.marker: o # The default marker type for scatter plots. +#scatter.edgecolors: face # The default edge colors for scatter plots. + + +## *************************************************************************** +## * AGG RENDERING * +## *************************************************************************** +## Warning: experimental, 2008/10/10 +#agg.path.chunksize: 0 # 0 to disable; values in the range + # 10000 to 100000 can improve speed slightly + # and prevent an Agg rendering failure + # when plotting very large data sets, + # especially if they are very gappy. + # It may cause minor artifacts, though. + # A value of 20000 is probably a good + # starting point. + + +## *************************************************************************** +## * PATHS * +## *************************************************************************** +#path.simplify: True # When True, simplify paths by removing "invisible" + # points to reduce file size and increase rendering + # speed +#path.simplify_threshold: 0.111111111111 # The threshold of similarity below + # which vertices will be removed in + # the simplification process. +#path.snap: True # When True, rectilinear axis-aligned paths will be snapped + # to the nearest pixel when certain criteria are met. + # When False, paths will never be snapped. +#path.sketch: None # May be None, or a tuple of the form: + # path.sketch: (scale, length, randomness) + # - *scale* is the amplitude of the wiggle + # perpendicular to the line (in pixels). + # - *length* is the length of the wiggle along the + # line (in pixels). + # - *randomness* is the factor by which the length is + # randomly scaled. +#path.effects: + + +## *************************************************************************** +## * SAVING FIGURES * +## *************************************************************************** +## The default savefig parameters can be different from the display parameters +## e.g., you may want a higher resolution, or to make the figure +## background white +#savefig.dpi: figure # figure dots per inch or 'figure' +#savefig.facecolor: auto # figure face color when saving +#savefig.edgecolor: auto # figure edge color when saving +#savefig.format: png # {png, ps, pdf, svg} +#savefig.bbox: standard # {tight, standard} + # 'tight' is incompatible with generating frames + # for animation +#savefig.pad_inches: 0.1 # padding to be used, when bbox is set to 'tight' +#savefig.directory: ~ # default directory in savefig dialog, gets updated after + # interactive saves, unless set to the empty string (i.e. + # the current directory); use '.' to start at the current + # directory but update after interactive saves +#savefig.transparent: False # whether figures are saved with a transparent + # background by default +#savefig.orientation: portrait # orientation of saved figure, for PostScript output only + +### macosx backend params +#macosx.window_mode : system # How to open new figures (system, tab, window) + # system uses the MacOS system preferences + +### tk backend params +#tk.window_focus: False # Maintain shell focus for TkAgg + +### ps backend params +#ps.papersize: letter # {figure, letter, legal, ledger, A0-A10, B0-B10} +#ps.useafm: False # use AFM fonts, results in small files +#ps.usedistiller: False # {ghostscript, xpdf, None} + # Experimental: may produce smaller files. + # xpdf intended for production of publication quality files, + # but requires ghostscript, xpdf and ps2eps +#ps.distiller.res: 6000 # dpi +#ps.fonttype: 3 # Output Type 3 (Type3) or Type 42 (TrueType) + +### PDF backend params +#pdf.compression: 6 # integer from 0 to 9 + # 0 disables compression (good for debugging) +#pdf.fonttype: 3 # Output Type 3 (Type3) or Type 42 (TrueType) +#pdf.use14corefonts: False +#pdf.inheritcolor: False + +### SVG backend params +#svg.image_inline: True # Write raster image data directly into the SVG file +#svg.fonttype: path # How to handle SVG fonts: + # path: Embed characters as paths -- supported + # by most SVG renderers + # None: Assume fonts are installed on the + # machine where the SVG will be viewed. +#svg.hashsalt: None # If not None, use this string as hash salt instead of uuid4 +#svg.id: None # If not None, use this string as the value for the `id` + # attribute in the top tag + +### pgf parameter +## See https://matplotlib.org/stable/tutorials/text/pgf.html for more information. +#pgf.rcfonts: True +#pgf.preamble: # See text.latex.preamble for documentation +#pgf.texsystem: xelatex + +### docstring params +#docstring.hardcopy: False # set this when you want to generate hardcopy docstring + + +## *************************************************************************** +## * INTERACTIVE KEYMAPS * +## *************************************************************************** +## Event keys to interact with figures/plots via keyboard. +## See https://matplotlib.org/stable/users/explain/interactive.html for more +## details on interactive navigation. Customize these settings according to +## your needs. Leave the field(s) empty if you don't need a key-map. (i.e., +## fullscreen : '') +#keymap.fullscreen: f, ctrl+f # toggling +#keymap.home: h, r, home # home or reset mnemonic +#keymap.back: left, c, backspace, MouseButton.BACK # forward / backward keys +#keymap.forward: right, v, MouseButton.FORWARD # for quick navigation +#keymap.pan: p # pan mnemonic +#keymap.zoom: o # zoom mnemonic +#keymap.save: s, ctrl+s # saving current figure +#keymap.help: f1 # display help about active tools +#keymap.quit: ctrl+w, cmd+w, q # close the current figure +#keymap.quit_all: # close all figures +#keymap.grid: g # switching on/off major grids in current axes +#keymap.grid_minor: G # switching on/off minor grids in current axes +#keymap.yscale: l # toggle scaling of y-axes ('log'/'linear') +#keymap.xscale: k, L # toggle scaling of x-axes ('log'/'linear') +#keymap.copy: ctrl+c, cmd+c # copy figure to clipboard + + +## *************************************************************************** +## * ANIMATION * +## *************************************************************************** +#animation.html: none # How to display the animation as HTML in + # the IPython notebook: + # - 'html5' uses HTML5 video tag + # - 'jshtml' creates a JavaScript animation +#animation.writer: ffmpeg # MovieWriter 'backend' to use +#animation.codec: h264 # Codec to use for writing movie +#animation.bitrate: -1 # Controls size/quality trade-off for movie. + # -1 implies let utility auto-determine +#animation.frame_format: png # Controls frame format used by temp files + +## Path to ffmpeg binary. Unqualified paths are resolved by subprocess.Popen. +#animation.ffmpeg_path: ffmpeg +## Additional arguments to pass to ffmpeg. +#animation.ffmpeg_args: + +## Path to ImageMagick's convert binary. Unqualified paths are resolved by +## subprocess.Popen, except that on Windows, we look up an install of +## ImageMagick in the registry (as convert is also the name of a system tool). +#animation.convert_path: convert +## Additional arguments to pass to convert. +#animation.convert_args: -layers, OptimizePlus +# +#animation.embed_limit: 20.0 # Limit, in MB, of size of base64 encoded + # animation in HTML (i.e. IPython notebook) diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/__init__.py b/python_embeded/Lib/site-packages/matplotlib/projections/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b46192a84ea047959f71183c1aa1627514fac4 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/__init__.py @@ -0,0 +1,126 @@ +""" +Non-separable transforms that map from data space to screen space. + +Projections are defined as `~.axes.Axes` subclasses. They include the +following elements: + +- A transformation from data coordinates into display coordinates. + +- An inverse of that transformation. This is used, for example, to convert + mouse positions from screen space back into data space. + +- Transformations for the gridlines, ticks and ticklabels. Custom projections + will often need to place these elements in special locations, and Matplotlib + has a facility to help with doing so. + +- Setting up default values (overriding `~.axes.Axes.cla`), since the defaults + for a rectilinear Axes may not be appropriate. + +- Defining the shape of the Axes, for example, an elliptical Axes, that will be + used to draw the background of the plot and for clipping any data elements. + +- Defining custom locators and formatters for the projection. For example, in + a geographic projection, it may be more convenient to display the grid in + degrees, even if the data is in radians. + +- Set up interactive panning and zooming. This is left as an "advanced" + feature left to the reader, but there is an example of this for polar plots + in `matplotlib.projections.polar`. + +- Any additional methods for additional convenience or features. + +Once the projection Axes is defined, it can be used in one of two ways: + +- By defining the class attribute ``name``, the projection Axes can be + registered with `matplotlib.projections.register_projection` and subsequently + simply invoked by name:: + + fig.add_subplot(projection="my_proj_name") + +- For more complex, parameterisable projections, a generic "projection" object + may be defined which includes the method ``_as_mpl_axes``. ``_as_mpl_axes`` + should take no arguments and return the projection's Axes subclass and a + dictionary of additional arguments to pass to the subclass' ``__init__`` + method. Subsequently a parameterised projection can be initialised with:: + + fig.add_subplot(projection=MyProjection(param1=param1_value)) + + where MyProjection is an object which implements a ``_as_mpl_axes`` method. + +A full-fledged and heavily annotated example is in +:doc:`/gallery/misc/custom_projection`. The polar plot functionality in +`matplotlib.projections.polar` may also be of interest. +""" + +from .. import axes, _docstring +from .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes +from .polar import PolarAxes + +try: + from mpl_toolkits.mplot3d import Axes3D +except Exception: + import warnings + warnings.warn("Unable to import Axes3D. This may be due to multiple versions of " + "Matplotlib being installed (e.g. as a system package and as a pip " + "package). As a result, the 3D projection is not available.") + Axes3D = None + + +class ProjectionRegistry: + """A mapping of registered projection names to projection classes.""" + + def __init__(self): + self._all_projection_types = {} + + def register(self, *projections): + """Register a new set of projections.""" + for projection in projections: + name = projection.name + self._all_projection_types[name] = projection + + def get_projection_class(self, name): + """Get a projection class from its *name*.""" + return self._all_projection_types[name] + + def get_projection_names(self): + """Return the names of all projections currently registered.""" + return sorted(self._all_projection_types) + + +projection_registry = ProjectionRegistry() +projection_registry.register( + axes.Axes, + PolarAxes, + AitoffAxes, + HammerAxes, + LambertAxes, + MollweideAxes, +) +if Axes3D is not None: + projection_registry.register(Axes3D) +else: + # remove from namespace if not importable + del Axes3D + + +def register_projection(cls): + projection_registry.register(cls) + + +def get_projection_class(projection=None): + """ + Get a projection class from its name. + + If *projection* is None, a standard rectilinear projection is returned. + """ + if projection is None: + projection = 'rectilinear' + + try: + return projection_registry.get_projection_class(projection) + except KeyError as err: + raise ValueError("Unknown projection %r" % projection) from err + + +get_projection_names = projection_registry.get_projection_names +_docstring.interpd.register(projection_names=get_projection_names()) diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/__init__.pyi b/python_embeded/Lib/site-packages/matplotlib/projections/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e0d210f1c9e9d71160c32646850c4ef57494238 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/__init__.pyi @@ -0,0 +1,20 @@ +from .geo import ( + AitoffAxes as AitoffAxes, + HammerAxes as HammerAxes, + LambertAxes as LambertAxes, + MollweideAxes as MollweideAxes, +) +from .polar import PolarAxes as PolarAxes +from ..axes import Axes + +class ProjectionRegistry: + def __init__(self) -> None: ... + def register(self, *projections: type[Axes]) -> None: ... + def get_projection_class(self, name: str) -> type[Axes]: ... + def get_projection_names(self) -> list[str]: ... + +projection_registry: ProjectionRegistry + +def register_projection(cls: type[Axes]) -> None: ... +def get_projection_class(projection: str | None = ...) -> type[Axes]: ... +def get_projection_names() -> list[str]: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/geo.py b/python_embeded/Lib/site-packages/matplotlib/projections/geo.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ab3c746deab63e8fec0fe7053fd02eaade8cc5 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/geo.py @@ -0,0 +1,511 @@ +import numpy as np + +import matplotlib as mpl +from matplotlib import _api +from matplotlib.axes import Axes +import matplotlib.axis as maxis +from matplotlib.patches import Circle +from matplotlib.path import Path +import matplotlib.spines as mspines +from matplotlib.ticker import ( + Formatter, NullLocator, FixedLocator, NullFormatter) +from matplotlib.transforms import Affine2D, BboxTransformTo, Transform + + +class GeoAxes(Axes): + """An abstract base class for geographic projections.""" + + class ThetaFormatter(Formatter): + """ + Used to format the theta tick labels. Converts the native + unit of radians into degrees and adds a degree symbol. + """ + def __init__(self, round_to=1.0): + self._round_to = round_to + + def __call__(self, x, pos=None): + degrees = round(np.rad2deg(x) / self._round_to) * self._round_to + return f"{degrees:0.0f}\N{DEGREE SIGN}" + + RESOLUTION = 75 + + def _init_axis(self): + self.xaxis = maxis.XAxis(self, clear=False) + self.yaxis = maxis.YAxis(self, clear=False) + self.spines['geo'].register_axis(self.yaxis) + + def clear(self): + # docstring inherited + super().clear() + + self.set_longitude_grid(30) + self.set_latitude_grid(15) + self.set_longitude_grid_ends(75) + self.xaxis.set_minor_locator(NullLocator()) + self.yaxis.set_minor_locator(NullLocator()) + self.xaxis.set_ticks_position('none') + self.yaxis.set_ticks_position('none') + self.yaxis.set_tick_params(label1On=True) + # Why do we need to turn on yaxis tick labels, but + # xaxis tick labels are already on? + + self.grid(mpl.rcParams['axes.grid']) + + Axes.set_xlim(self, -np.pi, np.pi) + Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) + + def _set_lim_and_transforms(self): + # A (possibly non-linear) projection on the (already scaled) data + self.transProjection = self._get_core_transform(self.RESOLUTION) + + self.transAffine = self._get_affine_transform() + + self.transAxes = BboxTransformTo(self.bbox) + + # The complete data transformation stack -- from data all the + # way to display coordinates + self.transData = \ + self.transProjection + \ + self.transAffine + \ + self.transAxes + + # This is the transform for longitude ticks. + self._xaxis_pretransform = \ + Affine2D() \ + .scale(1, self._longitude_cap * 2) \ + .translate(0, -self._longitude_cap) + self._xaxis_transform = \ + self._xaxis_pretransform + \ + self.transData + self._xaxis_text1_transform = \ + Affine2D().scale(1, 0) + \ + self.transData + \ + Affine2D().translate(0, 4) + self._xaxis_text2_transform = \ + Affine2D().scale(1, 0) + \ + self.transData + \ + Affine2D().translate(0, -4) + + # This is the transform for latitude ticks. + yaxis_stretch = Affine2D().scale(np.pi * 2, 1).translate(-np.pi, 0) + yaxis_space = Affine2D().scale(1, 1.1) + self._yaxis_transform = \ + yaxis_stretch + \ + self.transData + yaxis_text_base = \ + yaxis_stretch + \ + self.transProjection + \ + (yaxis_space + + self.transAffine + + self.transAxes) + self._yaxis_text1_transform = \ + yaxis_text_base + \ + Affine2D().translate(-8, 0) + self._yaxis_text2_transform = \ + yaxis_text_base + \ + Affine2D().translate(8, 0) + + def _get_affine_transform(self): + transform = self._get_core_transform(1) + xscale, _ = transform.transform((np.pi, 0)) + _, yscale = transform.transform((0, np.pi/2)) + return Affine2D() \ + .scale(0.5 / xscale, 0.5 / yscale) \ + .translate(0.5, 0.5) + + def get_xaxis_transform(self, which='grid'): + _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) + return self._xaxis_transform + + def get_xaxis_text1_transform(self, pad): + return self._xaxis_text1_transform, 'bottom', 'center' + + def get_xaxis_text2_transform(self, pad): + return self._xaxis_text2_transform, 'top', 'center' + + def get_yaxis_transform(self, which='grid'): + _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) + return self._yaxis_transform + + def get_yaxis_text1_transform(self, pad): + return self._yaxis_text1_transform, 'center', 'right' + + def get_yaxis_text2_transform(self, pad): + return self._yaxis_text2_transform, 'center', 'left' + + def _gen_axes_patch(self): + return Circle((0.5, 0.5), 0.5) + + def _gen_axes_spines(self): + return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} + + def set_yscale(self, *args, **kwargs): + if args[0] != 'linear': + raise NotImplementedError + + set_xscale = set_yscale + + def set_xlim(self, *args, **kwargs): + """Not supported. Please consider using Cartopy.""" + raise TypeError("Changing axes limits of a geographic projection is " + "not supported. Please consider using Cartopy.") + + set_ylim = set_xlim + set_xbound = set_xlim + set_ybound = set_ylim + + def invert_xaxis(self): + """Not supported. Please consider using Cartopy.""" + raise TypeError("Changing axes limits of a geographic projection is " + "not supported. Please consider using Cartopy.") + + invert_yaxis = invert_xaxis + + def format_coord(self, lon, lat): + """Return a format string formatting the coordinate.""" + lon, lat = np.rad2deg([lon, lat]) + ns = 'N' if lat >= 0.0 else 'S' + ew = 'E' if lon >= 0.0 else 'W' + return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s' + % (abs(lat), ns, abs(lon), ew)) + + def set_longitude_grid(self, degrees): + """ + Set the number of degrees between each longitude grid. + """ + # Skip -180 and 180, which are the fixed limits. + grid = np.arange(-180 + degrees, 180, degrees) + self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) + self.xaxis.set_major_formatter(self.ThetaFormatter(degrees)) + + def set_latitude_grid(self, degrees): + """ + Set the number of degrees between each latitude grid. + """ + # Skip -90 and 90, which are the fixed limits. + grid = np.arange(-90 + degrees, 90, degrees) + self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) + self.yaxis.set_major_formatter(self.ThetaFormatter(degrees)) + + def set_longitude_grid_ends(self, degrees): + """ + Set the latitude(s) at which to stop drawing the longitude grids. + """ + self._longitude_cap = np.deg2rad(degrees) + self._xaxis_pretransform \ + .clear() \ + .scale(1.0, self._longitude_cap * 2.0) \ + .translate(0.0, -self._longitude_cap) + + def get_data_ratio(self): + """Return the aspect ratio of the data itself.""" + return 1.0 + + ### Interactive panning + + def can_zoom(self): + """ + Return whether this Axes supports the zoom box button functionality. + + This Axes object does not support interactive zoom box. + """ + return False + + def can_pan(self): + """ + Return whether this Axes supports the pan/zoom button functionality. + + This Axes object does not support interactive pan/zoom. + """ + return False + + def start_pan(self, x, y, button): + pass + + def end_pan(self): + pass + + def drag_pan(self, button, key, x, y): + pass + + +class _GeoTransform(Transform): + # Factoring out some common functionality. + input_dims = output_dims = 2 + + def __init__(self, resolution): + """ + Create a new geographical transform. + + Resolution is the number of steps to interpolate between each input + line segment to approximate its path in curved space. + """ + super().__init__() + self._resolution = resolution + + def __str__(self): + return f"{type(self).__name__}({self._resolution})" + + def transform_path_non_affine(self, path): + # docstring inherited + ipath = path.interpolated(self._resolution) + return Path(self.transform(ipath.vertices), ipath.codes) + + +class AitoffAxes(GeoAxes): + name = 'aitoff' + + class AitoffTransform(_GeoTransform): + """The base Aitoff transform.""" + + def transform_non_affine(self, values): + # docstring inherited + longitude, latitude = values.T + + # Pre-compute some values + half_long = longitude / 2.0 + cos_latitude = np.cos(latitude) + + alpha = np.arccos(cos_latitude * np.cos(half_long)) + sinc_alpha = np.sinc(alpha / np.pi) # np.sinc is sin(pi*x)/(pi*x). + + x = (cos_latitude * np.sin(half_long)) / sinc_alpha + y = np.sin(latitude) / sinc_alpha + return np.column_stack([x, y]) + + def inverted(self): + # docstring inherited + return AitoffAxes.InvertedAitoffTransform(self._resolution) + + class InvertedAitoffTransform(_GeoTransform): + + def transform_non_affine(self, values): + # docstring inherited + # MGDTODO: Math is hard ;( + return np.full_like(values, np.nan) + + def inverted(self): + # docstring inherited + return AitoffAxes.AitoffTransform(self._resolution) + + def __init__(self, *args, **kwargs): + self._longitude_cap = np.pi / 2.0 + super().__init__(*args, **kwargs) + self.set_aspect(0.5, adjustable='box', anchor='C') + self.clear() + + def _get_core_transform(self, resolution): + return self.AitoffTransform(resolution) + + +class HammerAxes(GeoAxes): + name = 'hammer' + + class HammerTransform(_GeoTransform): + """The base Hammer transform.""" + + def transform_non_affine(self, values): + # docstring inherited + longitude, latitude = values.T + half_long = longitude / 2.0 + cos_latitude = np.cos(latitude) + sqrt2 = np.sqrt(2.0) + alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long)) + x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha + y = (sqrt2 * np.sin(latitude)) / alpha + return np.column_stack([x, y]) + + def inverted(self): + # docstring inherited + return HammerAxes.InvertedHammerTransform(self._resolution) + + class InvertedHammerTransform(_GeoTransform): + + def transform_non_affine(self, values): + # docstring inherited + x, y = values.T + z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2) + longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1))) + latitude = np.arcsin(y*z) + return np.column_stack([longitude, latitude]) + + def inverted(self): + # docstring inherited + return HammerAxes.HammerTransform(self._resolution) + + def __init__(self, *args, **kwargs): + self._longitude_cap = np.pi / 2.0 + super().__init__(*args, **kwargs) + self.set_aspect(0.5, adjustable='box', anchor='C') + self.clear() + + def _get_core_transform(self, resolution): + return self.HammerTransform(resolution) + + +class MollweideAxes(GeoAxes): + name = 'mollweide' + + class MollweideTransform(_GeoTransform): + """The base Mollweide transform.""" + + def transform_non_affine(self, values): + # docstring inherited + def d(theta): + delta = (-(theta + np.sin(theta) - pi_sin_l) + / (1 + np.cos(theta))) + return delta, np.abs(delta) > 0.001 + + longitude, latitude = values.T + + clat = np.pi/2 - np.abs(latitude) + ihigh = clat < 0.087 # within 5 degrees of the poles + ilow = ~ihigh + aux = np.empty(latitude.shape, dtype=float) + + if ilow.any(): # Newton-Raphson iteration + pi_sin_l = np.pi * np.sin(latitude[ilow]) + theta = 2.0 * latitude[ilow] + delta, large_delta = d(theta) + while np.any(large_delta): + theta[large_delta] += delta[large_delta] + delta, large_delta = d(theta) + aux[ilow] = theta / 2 + + if ihigh.any(): # Taylor series-based approx. solution + e = clat[ihigh] + d = 0.5 * (3 * np.pi * e**2) ** (1.0/3) + aux[ihigh] = (np.pi/2 - d) * np.sign(latitude[ihigh]) + + xy = np.empty(values.shape, dtype=float) + xy[:, 0] = (2.0 * np.sqrt(2.0) / np.pi) * longitude * np.cos(aux) + xy[:, 1] = np.sqrt(2.0) * np.sin(aux) + + return xy + + def inverted(self): + # docstring inherited + return MollweideAxes.InvertedMollweideTransform(self._resolution) + + class InvertedMollweideTransform(_GeoTransform): + + def transform_non_affine(self, values): + # docstring inherited + x, y = values.T + # from Equations (7, 8) of + # https://mathworld.wolfram.com/MollweideProjection.html + theta = np.arcsin(y / np.sqrt(2)) + longitude = (np.pi / (2 * np.sqrt(2))) * x / np.cos(theta) + latitude = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi) + return np.column_stack([longitude, latitude]) + + def inverted(self): + # docstring inherited + return MollweideAxes.MollweideTransform(self._resolution) + + def __init__(self, *args, **kwargs): + self._longitude_cap = np.pi / 2.0 + super().__init__(*args, **kwargs) + self.set_aspect(0.5, adjustable='box', anchor='C') + self.clear() + + def _get_core_transform(self, resolution): + return self.MollweideTransform(resolution) + + +class LambertAxes(GeoAxes): + name = 'lambert' + + class LambertTransform(_GeoTransform): + """The base Lambert transform.""" + + def __init__(self, center_longitude, center_latitude, resolution): + """ + Create a new Lambert transform. Resolution is the number of steps + to interpolate between each input line segment to approximate its + path in curved Lambert space. + """ + _GeoTransform.__init__(self, resolution) + self._center_longitude = center_longitude + self._center_latitude = center_latitude + + def transform_non_affine(self, values): + # docstring inherited + longitude, latitude = values.T + clong = self._center_longitude + clat = self._center_latitude + cos_lat = np.cos(latitude) + sin_lat = np.sin(latitude) + diff_long = longitude - clong + cos_diff_long = np.cos(diff_long) + + inner_k = np.maximum( # Prevent divide-by-zero problems + 1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long, + 1e-15) + k = np.sqrt(2 / inner_k) + x = k * cos_lat*np.sin(diff_long) + y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long) + + return np.column_stack([x, y]) + + def inverted(self): + # docstring inherited + return LambertAxes.InvertedLambertTransform( + self._center_longitude, + self._center_latitude, + self._resolution) + + class InvertedLambertTransform(_GeoTransform): + + def __init__(self, center_longitude, center_latitude, resolution): + _GeoTransform.__init__(self, resolution) + self._center_longitude = center_longitude + self._center_latitude = center_latitude + + def transform_non_affine(self, values): + # docstring inherited + x, y = values.T + clong = self._center_longitude + clat = self._center_latitude + p = np.maximum(np.hypot(x, y), 1e-9) + c = 2 * np.arcsin(0.5 * p) + sin_c = np.sin(c) + cos_c = np.cos(c) + + latitude = np.arcsin(cos_c*np.sin(clat) + + ((y*sin_c*np.cos(clat)) / p)) + longitude = clong + np.arctan( + (x*sin_c) / (p*np.cos(clat)*cos_c - y*np.sin(clat)*sin_c)) + + return np.column_stack([longitude, latitude]) + + def inverted(self): + # docstring inherited + return LambertAxes.LambertTransform( + self._center_longitude, + self._center_latitude, + self._resolution) + + def __init__(self, *args, center_longitude=0, center_latitude=0, **kwargs): + self._longitude_cap = np.pi / 2 + self._center_longitude = center_longitude + self._center_latitude = center_latitude + super().__init__(*args, **kwargs) + self.set_aspect('equal', adjustable='box', anchor='C') + self.clear() + + def clear(self): + # docstring inherited + super().clear() + self.yaxis.set_major_formatter(NullFormatter()) + + def _get_core_transform(self, resolution): + return self.LambertTransform( + self._center_longitude, + self._center_latitude, + resolution) + + def _get_affine_transform(self): + return Affine2D() \ + .scale(0.25) \ + .translate(0.5, 0.5) diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/geo.pyi b/python_embeded/Lib/site-packages/matplotlib/projections/geo.pyi new file mode 100644 index 0000000000000000000000000000000000000000..93220f8cbcd58278b90bd18bbc58d5ef92d45d4f --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/geo.pyi @@ -0,0 +1,112 @@ +from matplotlib.axes import Axes +from matplotlib.ticker import Formatter +from matplotlib.transforms import Transform + +from typing import Any, Literal + +class GeoAxes(Axes): + class ThetaFormatter(Formatter): + def __init__(self, round_to: float = ...) -> None: ... + def __call__(self, x: float, pos: Any | None = ...): ... + RESOLUTION: float + def get_xaxis_transform( + self, which: Literal["tick1", "tick2", "grid"] = ... + ) -> Transform: ... + def get_xaxis_text1_transform( + self, pad: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_xaxis_text2_transform( + self, pad: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_transform( + self, which: Literal["tick1", "tick2", "grid"] = ... + ) -> Transform: ... + def get_yaxis_text1_transform( + self, pad: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_text2_transform( + self, pad: float + ) -> tuple[ + Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def set_xlim(self, *args, **kwargs) -> tuple[float, float]: ... + def set_ylim(self, *args, **kwargs) -> tuple[float, float]: ... + def format_coord(self, lon: float, lat: float) -> str: ... + def set_longitude_grid(self, degrees: float) -> None: ... + def set_latitude_grid(self, degrees: float) -> None: ... + def set_longitude_grid_ends(self, degrees: float) -> None: ... + def get_data_ratio(self) -> float: ... + def can_zoom(self) -> bool: ... + def can_pan(self) -> bool: ... + def start_pan(self, x, y, button) -> None: ... + def end_pan(self) -> None: ... + def drag_pan(self, button, key, x, y) -> None: ... + +class _GeoTransform(Transform): + input_dims: int + output_dims: int + def __init__(self, resolution: int) -> None: ... + +class AitoffAxes(GeoAxes): + name: str + + class AitoffTransform(_GeoTransform): + def inverted(self) -> AitoffAxes.InvertedAitoffTransform: ... + + class InvertedAitoffTransform(_GeoTransform): + def inverted(self) -> AitoffAxes.AitoffTransform: ... + +class HammerAxes(GeoAxes): + name: str + + class HammerTransform(_GeoTransform): + def inverted(self) -> HammerAxes.InvertedHammerTransform: ... + + class InvertedHammerTransform(_GeoTransform): + def inverted(self) -> HammerAxes.HammerTransform: ... + +class MollweideAxes(GeoAxes): + name: str + + class MollweideTransform(_GeoTransform): + def inverted(self) -> MollweideAxes.InvertedMollweideTransform: ... + + class InvertedMollweideTransform(_GeoTransform): + def inverted(self) -> MollweideAxes.MollweideTransform: ... + +class LambertAxes(GeoAxes): + name: str + + class LambertTransform(_GeoTransform): + def __init__( + self, center_longitude: float, center_latitude: float, resolution: int + ) -> None: ... + def inverted(self) -> LambertAxes.InvertedLambertTransform: ... + + class InvertedLambertTransform(_GeoTransform): + def __init__( + self, center_longitude: float, center_latitude: float, resolution: int + ) -> None: ... + def inverted(self) -> LambertAxes.LambertTransform: ... + + def __init__( + self, + *args, + center_longitude: float = ..., + center_latitude: float = ..., + **kwargs + ) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/polar.py b/python_embeded/Lib/site-packages/matplotlib/projections/polar.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe6045039b152801c35933e8432ccd59ab8615b --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/polar.py @@ -0,0 +1,1557 @@ +import math +import types + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +from matplotlib.axes import Axes +import matplotlib.axis as maxis +import matplotlib.markers as mmarkers +import matplotlib.patches as mpatches +from matplotlib.path import Path +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +from matplotlib.spines import Spine + + +def _apply_theta_transforms_warn(): + _api.warn_deprecated( + "3.9", + message=( + "Passing `apply_theta_transforms=True` (the default) " + "is deprecated since Matplotlib %(since)s. " + "Support for this will be removed in Matplotlib in %(removal)s. " + "To prevent this warning, set `apply_theta_transforms=False`, " + "and make sure to shift theta values before being passed to " + "this transform." + ) + ) + + +class PolarTransform(mtransforms.Transform): + r""" + The base polar transform. + + This transform maps polar coordinates :math:`\theta, r` into Cartesian + coordinates :math:`x, y = r \cos(\theta), r \sin(\theta)` + (but does not fully transform into Axes coordinates or + handle positioning in screen space). + + This transformation is designed to be applied to data after any scaling + along the radial axis (e.g. log-scaling) has been applied to the input + data. + + Path segments at a fixed radius are automatically transformed to circular + arcs as long as ``path._interpolation_steps > 1``. + """ + + input_dims = output_dims = 2 + + def __init__(self, axis=None, use_rmin=True, *, + apply_theta_transforms=True, scale_transform=None): + """ + Parameters + ---------- + axis : `~matplotlib.axis.Axis`, optional + Axis associated with this transform. This is used to get the + minimum radial limit. + use_rmin : `bool`, optional + If ``True``, subtract the minimum radial axis limit before + transforming to Cartesian coordinates. *axis* must also be + specified for this to take effect. + """ + super().__init__() + self._axis = axis + self._use_rmin = use_rmin + self._apply_theta_transforms = apply_theta_transforms + self._scale_transform = scale_transform + if apply_theta_transforms: + _apply_theta_transforms_warn() + + __str__ = mtransforms._make_str_method( + "_axis", + use_rmin="_use_rmin", + apply_theta_transforms="_apply_theta_transforms") + + def _get_rorigin(self): + # Get lower r limit after being scaled by the radial scale transform + return self._scale_transform.transform( + (0, self._axis.get_rorigin()))[1] + + def transform_non_affine(self, values): + # docstring inherited + theta, r = np.transpose(values) + # PolarAxes does not use the theta transforms here, but apply them for + # backwards-compatibility if not being used by it. + if self._apply_theta_transforms and self._axis is not None: + theta *= self._axis.get_theta_direction() + theta += self._axis.get_theta_offset() + if self._use_rmin and self._axis is not None: + r = (r - self._get_rorigin()) * self._axis.get_rsign() + r = np.where(r >= 0, r, np.nan) + return np.column_stack([r * np.cos(theta), r * np.sin(theta)]) + + def transform_path_non_affine(self, path): + # docstring inherited + if not len(path) or path._interpolation_steps == 1: + return Path(self.transform_non_affine(path.vertices), path.codes) + xys = [] + codes = [] + last_t = last_r = None + for trs, c in path.iter_segments(): + trs = trs.reshape((-1, 2)) + if c == Path.LINETO: + (t, r), = trs + if t == last_t: # Same angle: draw a straight line. + xys.extend(self.transform_non_affine(trs)) + codes.append(Path.LINETO) + elif r == last_r: # Same radius: draw an arc. + # The following is complicated by Path.arc() being + # "helpful" and unwrapping the angles, but we don't want + # that behavior here. + last_td, td = np.rad2deg([last_t, t]) + if self._use_rmin and self._axis is not None: + r = ((r - self._get_rorigin()) + * self._axis.get_rsign()) + if last_td <= td: + while td - last_td > 360: + arc = Path.arc(last_td, last_td + 360) + xys.extend(arc.vertices[1:] * r) + codes.extend(arc.codes[1:]) + last_td += 360 + arc = Path.arc(last_td, td) + xys.extend(arc.vertices[1:] * r) + codes.extend(arc.codes[1:]) + else: + # The reverse version also relies on the fact that all + # codes but the first one are the same. + while last_td - td > 360: + arc = Path.arc(last_td - 360, last_td) + xys.extend(arc.vertices[::-1][1:] * r) + codes.extend(arc.codes[1:]) + last_td -= 360 + arc = Path.arc(td, last_td) + xys.extend(arc.vertices[::-1][1:] * r) + codes.extend(arc.codes[1:]) + else: # Interpolate. + trs = cbook.simple_linear_interpolation( + np.vstack([(last_t, last_r), trs]), + path._interpolation_steps)[1:] + xys.extend(self.transform_non_affine(trs)) + codes.extend([Path.LINETO] * len(trs)) + else: # Not a straight line. + xys.extend(self.transform_non_affine(trs)) + codes.extend([c] * len(trs)) + last_t, last_r = trs[-1] + return Path(xys, codes) + + def inverted(self): + # docstring inherited + return PolarAxes.InvertedPolarTransform( + self._axis, self._use_rmin, + apply_theta_transforms=self._apply_theta_transforms + ) + + +class PolarAffine(mtransforms.Affine2DBase): + r""" + The affine part of the polar projection. + + Scales the output so that maximum radius rests on the edge of the Axes + circle and the origin is mapped to (0.5, 0.5). The transform applied is + the same to x and y components and given by: + + .. math:: + + x_{1} = 0.5 \left [ \frac{x_{0}}{(r_{\max} - r_{\min})} + 1 \right ] + + :math:`r_{\min}, r_{\max}` are the minimum and maximum radial limits after + any scaling (e.g. log scaling) has been removed. + """ + def __init__(self, scale_transform, limits): + """ + Parameters + ---------- + scale_transform : `~matplotlib.transforms.Transform` + Scaling transform for the data. This is used to remove any scaling + from the radial view limits. + limits : `~matplotlib.transforms.BboxBase` + View limits of the data. The only part of its bounds that is used + is the y limits (for the radius limits). + """ + super().__init__() + self._scale_transform = scale_transform + self._limits = limits + self.set_children(scale_transform, limits) + self._mtx = None + + __str__ = mtransforms._make_str_method("_scale_transform", "_limits") + + def get_matrix(self): + # docstring inherited + if self._invalid: + limits_scaled = self._limits.transformed(self._scale_transform) + yscale = limits_scaled.ymax - limits_scaled.ymin + affine = mtransforms.Affine2D() \ + .scale(0.5 / yscale) \ + .translate(0.5, 0.5) + self._mtx = affine.get_matrix() + self._inverted = None + self._invalid = 0 + return self._mtx + + +class InvertedPolarTransform(mtransforms.Transform): + """ + The inverse of the polar transform, mapping Cartesian + coordinate space *x* and *y* back to *theta* and *r*. + """ + input_dims = output_dims = 2 + + def __init__(self, axis=None, use_rmin=True, + *, apply_theta_transforms=True): + """ + Parameters + ---------- + axis : `~matplotlib.axis.Axis`, optional + Axis associated with this transform. This is used to get the + minimum radial limit. + use_rmin : `bool`, optional + If ``True``, add the minimum radial axis limit after + transforming from Cartesian coordinates. *axis* must also be + specified for this to take effect. + """ + super().__init__() + self._axis = axis + self._use_rmin = use_rmin + self._apply_theta_transforms = apply_theta_transforms + if apply_theta_transforms: + _apply_theta_transforms_warn() + + __str__ = mtransforms._make_str_method( + "_axis", + use_rmin="_use_rmin", + apply_theta_transforms="_apply_theta_transforms") + + def transform_non_affine(self, values): + # docstring inherited + x, y = values.T + r = np.hypot(x, y) + theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi) + # PolarAxes does not use the theta transforms here, but apply them for + # backwards-compatibility if not being used by it. + if self._apply_theta_transforms and self._axis is not None: + theta -= self._axis.get_theta_offset() + theta *= self._axis.get_theta_direction() + theta %= 2 * np.pi + if self._use_rmin and self._axis is not None: + r += self._axis.get_rorigin() + r *= self._axis.get_rsign() + return np.column_stack([theta, r]) + + def inverted(self): + # docstring inherited + return PolarAxes.PolarTransform( + self._axis, self._use_rmin, + apply_theta_transforms=self._apply_theta_transforms + ) + + +class ThetaFormatter(mticker.Formatter): + """ + Used to format the *theta* tick labels. Converts the native + unit of radians into degrees and adds a degree symbol. + """ + + def __call__(self, x, pos=None): + vmin, vmax = self.axis.get_view_interval() + d = np.rad2deg(abs(vmax - vmin)) + digits = max(-int(np.log10(d) - 1.5), 0) + return f"{np.rad2deg(x):0.{digits}f}\N{DEGREE SIGN}" + + +class _AxisWrapper: + def __init__(self, axis): + self._axis = axis + + def get_view_interval(self): + return np.rad2deg(self._axis.get_view_interval()) + + def set_view_interval(self, vmin, vmax): + self._axis.set_view_interval(*np.deg2rad((vmin, vmax))) + + def get_minpos(self): + return np.rad2deg(self._axis.get_minpos()) + + def get_data_interval(self): + return np.rad2deg(self._axis.get_data_interval()) + + def set_data_interval(self, vmin, vmax): + self._axis.set_data_interval(*np.deg2rad((vmin, vmax))) + + def get_tick_space(self): + return self._axis.get_tick_space() + + +class ThetaLocator(mticker.Locator): + """ + Used to locate theta ticks. + + This will work the same as the base locator except in the case that the + view spans the entire circle. In such cases, the previously used default + locations of every 45 degrees are returned. + """ + + def __init__(self, base): + self.base = base + self.axis = self.base.axis = _AxisWrapper(self.base.axis) + + def set_axis(self, axis): + self.axis = _AxisWrapper(axis) + self.base.set_axis(self.axis) + + def __call__(self): + lim = self.axis.get_view_interval() + if _is_full_circle_deg(lim[0], lim[1]): + return np.deg2rad(min(lim)) + np.arange(8) * 2 * np.pi / 8 + else: + return np.deg2rad(self.base()) + + def view_limits(self, vmin, vmax): + vmin, vmax = np.rad2deg((vmin, vmax)) + return np.deg2rad(self.base.view_limits(vmin, vmax)) + + +class ThetaTick(maxis.XTick): + """ + A theta-axis tick. + + This subclass of `.XTick` provides angular ticks with some small + modification to their re-positioning such that ticks are rotated based on + tick location. This results in ticks that are correctly perpendicular to + the arc spine. + + When 'auto' rotation is enabled, labels are also rotated to be parallel to + the spine. The label padding is also applied here since it's not possible + to use a generic axes transform to produce tick-specific padding. + """ + + def __init__(self, axes, *args, **kwargs): + self._text1_translate = mtransforms.ScaledTranslation( + 0, 0, axes.get_figure(root=False).dpi_scale_trans) + self._text2_translate = mtransforms.ScaledTranslation( + 0, 0, axes.get_figure(root=False).dpi_scale_trans) + super().__init__(axes, *args, **kwargs) + self.label1.set( + rotation_mode='anchor', + transform=self.label1.get_transform() + self._text1_translate) + self.label2.set( + rotation_mode='anchor', + transform=self.label2.get_transform() + self._text2_translate) + + def _apply_params(self, **kwargs): + super()._apply_params(**kwargs) + # Ensure transform is correct; sometimes this gets reset. + trans = self.label1.get_transform() + if not trans.contains_branch(self._text1_translate): + self.label1.set_transform(trans + self._text1_translate) + trans = self.label2.get_transform() + if not trans.contains_branch(self._text2_translate): + self.label2.set_transform(trans + self._text2_translate) + + def _update_padding(self, pad, angle): + padx = pad * np.cos(angle) / 72 + pady = pad * np.sin(angle) / 72 + self._text1_translate._t = (padx, pady) + self._text1_translate.invalidate() + self._text2_translate._t = (-padx, -pady) + self._text2_translate.invalidate() + + def update_position(self, loc): + super().update_position(loc) + axes = self.axes + angle = loc * axes.get_theta_direction() + axes.get_theta_offset() + text_angle = np.rad2deg(angle) % 360 - 90 + angle -= np.pi / 2 + + marker = self.tick1line.get_marker() + if marker in (mmarkers.TICKUP, '|'): + trans = mtransforms.Affine2D().scale(1, 1).rotate(angle) + elif marker == mmarkers.TICKDOWN: + trans = mtransforms.Affine2D().scale(1, -1).rotate(angle) + else: + # Don't modify custom tick line markers. + trans = self.tick1line._marker._transform + self.tick1line._marker._transform = trans + + marker = self.tick2line.get_marker() + if marker in (mmarkers.TICKUP, '|'): + trans = mtransforms.Affine2D().scale(1, 1).rotate(angle) + elif marker == mmarkers.TICKDOWN: + trans = mtransforms.Affine2D().scale(1, -1).rotate(angle) + else: + # Don't modify custom tick line markers. + trans = self.tick2line._marker._transform + self.tick2line._marker._transform = trans + + mode, user_angle = self._labelrotation + if mode == 'default': + text_angle = user_angle + else: + if text_angle > 90: + text_angle -= 180 + elif text_angle < -90: + text_angle += 180 + text_angle += user_angle + self.label1.set_rotation(text_angle) + self.label2.set_rotation(text_angle) + + # This extra padding helps preserve the look from previous releases but + # is also needed because labels are anchored to their center. + pad = self._pad + 7 + self._update_padding(pad, + self._loc * axes.get_theta_direction() + + axes.get_theta_offset()) + + +class ThetaAxis(maxis.XAxis): + """ + A theta Axis. + + This overrides certain properties of an `.XAxis` to provide special-casing + for an angular axis. + """ + __name__ = 'thetaaxis' + axis_name = 'theta' #: Read-only name identifying the axis. + _tick_class = ThetaTick + + def _wrap_locator_formatter(self): + self.set_major_locator(ThetaLocator(self.get_major_locator())) + self.set_major_formatter(ThetaFormatter()) + self.isDefault_majloc = True + self.isDefault_majfmt = True + + def clear(self): + # docstring inherited + super().clear() + self.set_ticks_position('none') + self._wrap_locator_formatter() + + def _set_scale(self, value, **kwargs): + if value != 'linear': + raise NotImplementedError( + "The xscale cannot be set on a polar plot") + super()._set_scale(value, **kwargs) + # LinearScale.set_default_locators_and_formatters just set the major + # locator to be an AutoLocator, so we customize it here to have ticks + # at sensible degree multiples. + self.get_major_locator().set_params(steps=[1, 1.5, 3, 4.5, 9, 10]) + self._wrap_locator_formatter() + + def _copy_tick_props(self, src, dest): + """Copy the props from src tick to dest tick.""" + if src is None or dest is None: + return + super()._copy_tick_props(src, dest) + + # Ensure that tick transforms are independent so that padding works. + trans = dest._get_text1_transform()[0] + dest.label1.set_transform(trans + dest._text1_translate) + trans = dest._get_text2_transform()[0] + dest.label2.set_transform(trans + dest._text2_translate) + + +class RadialLocator(mticker.Locator): + """ + Used to locate radius ticks. + + Ensures that all ticks are strictly positive. For all other tasks, it + delegates to the base `.Locator` (which may be different depending on the + scale of the *r*-axis). + """ + + def __init__(self, base, axes=None): + self.base = base + self._axes = axes + + def set_axis(self, axis): + self.base.set_axis(axis) + + def __call__(self): + # Ensure previous behaviour with full circle non-annular views. + if self._axes: + if _is_full_circle_rad(*self._axes.viewLim.intervalx): + rorigin = self._axes.get_rorigin() * self._axes.get_rsign() + if self._axes.get_rmin() <= rorigin: + return [tick for tick in self.base() if tick > rorigin] + return self.base() + + def _zero_in_bounds(self): + """ + Return True if zero is within the valid values for the + scale of the radial axis. + """ + vmin, vmax = self._axes.yaxis._scale.limit_range_for_scale(0, 1, 1e-5) + return vmin == 0 + + def nonsingular(self, vmin, vmax): + # docstring inherited + if self._zero_in_bounds() and (vmin, vmax) == (-np.inf, np.inf): + # Initial view limits + return (0, 1) + else: + return self.base.nonsingular(vmin, vmax) + + def view_limits(self, vmin, vmax): + vmin, vmax = self.base.view_limits(vmin, vmax) + if self._zero_in_bounds() and vmax > vmin: + # this allows inverted r/y-lims + vmin = min(0, vmin) + return mtransforms.nonsingular(vmin, vmax) + + +class _ThetaShift(mtransforms.ScaledTranslation): + """ + Apply a padding shift based on axes theta limits. + + This is used to create padding for radial ticks. + + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The owning Axes; used to determine limits. + pad : float + The padding to apply, in points. + mode : {'min', 'max', 'rlabel'} + Whether to shift away from the start (``'min'``) or the end (``'max'``) + of the axes, or using the rlabel position (``'rlabel'``). + """ + def __init__(self, axes, pad, mode): + super().__init__(pad, pad, axes.get_figure(root=False).dpi_scale_trans) + self.set_children(axes._realViewLim) + self.axes = axes + self.mode = mode + self.pad = pad + + __str__ = mtransforms._make_str_method("axes", "pad", "mode") + + def get_matrix(self): + if self._invalid: + if self.mode == 'rlabel': + angle = ( + np.deg2rad(self.axes.get_rlabel_position() + * self.axes.get_theta_direction()) + + self.axes.get_theta_offset() + - np.pi / 2 + ) + elif self.mode == 'min': + angle = self.axes._realViewLim.xmin - np.pi / 2 + elif self.mode == 'max': + angle = self.axes._realViewLim.xmax + np.pi / 2 + self._t = (self.pad * np.cos(angle) / 72, self.pad * np.sin(angle) / 72) + return super().get_matrix() + + +class RadialTick(maxis.YTick): + """ + A radial-axis tick. + + This subclass of `.YTick` provides radial ticks with some small + modification to their re-positioning such that ticks are rotated based on + axes limits. This results in ticks that are correctly perpendicular to + the spine. Labels are also rotated to be perpendicular to the spine, when + 'auto' rotation is enabled. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.label1.set_rotation_mode('anchor') + self.label2.set_rotation_mode('anchor') + + def _determine_anchor(self, mode, angle, start): + # Note: angle is the (spine angle - 90) because it's used for the tick + # & text setup, so all numbers below are -90 from (normed) spine angle. + if mode == 'auto': + if start: + if -90 <= angle <= 90: + return 'left', 'center' + else: + return 'right', 'center' + else: + if -90 <= angle <= 90: + return 'right', 'center' + else: + return 'left', 'center' + else: + if start: + if angle < -68.5: + return 'center', 'top' + elif angle < -23.5: + return 'left', 'top' + elif angle < 22.5: + return 'left', 'center' + elif angle < 67.5: + return 'left', 'bottom' + elif angle < 112.5: + return 'center', 'bottom' + elif angle < 157.5: + return 'right', 'bottom' + elif angle < 202.5: + return 'right', 'center' + elif angle < 247.5: + return 'right', 'top' + else: + return 'center', 'top' + else: + if angle < -68.5: + return 'center', 'bottom' + elif angle < -23.5: + return 'right', 'bottom' + elif angle < 22.5: + return 'right', 'center' + elif angle < 67.5: + return 'right', 'top' + elif angle < 112.5: + return 'center', 'top' + elif angle < 157.5: + return 'left', 'top' + elif angle < 202.5: + return 'left', 'center' + elif angle < 247.5: + return 'left', 'bottom' + else: + return 'center', 'bottom' + + def update_position(self, loc): + super().update_position(loc) + axes = self.axes + thetamin = axes.get_thetamin() + thetamax = axes.get_thetamax() + direction = axes.get_theta_direction() + offset_rad = axes.get_theta_offset() + offset = np.rad2deg(offset_rad) + full = _is_full_circle_deg(thetamin, thetamax) + + if full: + angle = (axes.get_rlabel_position() * direction + + offset) % 360 - 90 + tick_angle = 0 + else: + angle = (thetamin * direction + offset) % 360 - 90 + if direction > 0: + tick_angle = np.deg2rad(angle) + else: + tick_angle = np.deg2rad(angle + 180) + text_angle = (angle + 90) % 180 - 90 # between -90 and +90. + mode, user_angle = self._labelrotation + if mode == 'auto': + text_angle += user_angle + else: + text_angle = user_angle + + if full: + ha = self.label1.get_horizontalalignment() + va = self.label1.get_verticalalignment() + else: + ha, va = self._determine_anchor(mode, angle, direction > 0) + self.label1.set_horizontalalignment(ha) + self.label1.set_verticalalignment(va) + self.label1.set_rotation(text_angle) + + marker = self.tick1line.get_marker() + if marker == mmarkers.TICKLEFT: + trans = mtransforms.Affine2D().rotate(tick_angle) + elif marker == '_': + trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) + elif marker == mmarkers.TICKRIGHT: + trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) + else: + # Don't modify custom tick line markers. + trans = self.tick1line._marker._transform + self.tick1line._marker._transform = trans + + if full: + self.label2.set_visible(False) + self.tick2line.set_visible(False) + angle = (thetamax * direction + offset) % 360 - 90 + if direction > 0: + tick_angle = np.deg2rad(angle) + else: + tick_angle = np.deg2rad(angle + 180) + text_angle = (angle + 90) % 180 - 90 # between -90 and +90. + mode, user_angle = self._labelrotation + if mode == 'auto': + text_angle += user_angle + else: + text_angle = user_angle + + ha, va = self._determine_anchor(mode, angle, direction < 0) + self.label2.set_ha(ha) + self.label2.set_va(va) + self.label2.set_rotation(text_angle) + + marker = self.tick2line.get_marker() + if marker == mmarkers.TICKLEFT: + trans = mtransforms.Affine2D().rotate(tick_angle) + elif marker == '_': + trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) + elif marker == mmarkers.TICKRIGHT: + trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) + else: + # Don't modify custom tick line markers. + trans = self.tick2line._marker._transform + self.tick2line._marker._transform = trans + + +class RadialAxis(maxis.YAxis): + """ + A radial Axis. + + This overrides certain properties of a `.YAxis` to provide special-casing + for a radial axis. + """ + __name__ = 'radialaxis' + axis_name = 'radius' #: Read-only name identifying the axis. + _tick_class = RadialTick + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.sticky_edges.y.append(0) + + def _wrap_locator_formatter(self): + self.set_major_locator(RadialLocator(self.get_major_locator(), + self.axes)) + self.isDefault_majloc = True + + def clear(self): + # docstring inherited + super().clear() + self.set_ticks_position('none') + self._wrap_locator_formatter() + + def _set_scale(self, value, **kwargs): + super()._set_scale(value, **kwargs) + self._wrap_locator_formatter() + + +def _is_full_circle_deg(thetamin, thetamax): + """ + Determine if a wedge (in degrees) spans the full circle. + + The condition is derived from :class:`~matplotlib.patches.Wedge`. + """ + return abs(abs(thetamax - thetamin) - 360.0) < 1e-12 + + +def _is_full_circle_rad(thetamin, thetamax): + """ + Determine if a wedge (in radians) spans the full circle. + + The condition is derived from :class:`~matplotlib.patches.Wedge`. + """ + return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14 + + +class _WedgeBbox(mtransforms.Bbox): + """ + Transform (theta, r) wedge Bbox into Axes bounding box. + + Parameters + ---------- + center : (float, float) + Center of the wedge + viewLim : `~matplotlib.transforms.Bbox` + Bbox determining the boundaries of the wedge + originLim : `~matplotlib.transforms.Bbox` + Bbox determining the origin for the wedge, if different from *viewLim* + """ + def __init__(self, center, viewLim, originLim, **kwargs): + super().__init__([[0, 0], [1, 1]], **kwargs) + self._center = center + self._viewLim = viewLim + self._originLim = originLim + self.set_children(viewLim, originLim) + + __str__ = mtransforms._make_str_method("_center", "_viewLim", "_originLim") + + def get_points(self): + # docstring inherited + if self._invalid: + points = self._viewLim.get_points().copy() + # Scale angular limits to work with Wedge. + points[:, 0] *= 180 / np.pi + if points[0, 0] > points[1, 0]: + points[:, 0] = points[::-1, 0] + + # Scale radial limits based on origin radius. + points[:, 1] -= self._originLim.y0 + + # Scale radial limits to match axes limits. + rscale = 0.5 / points[1, 1] + points[:, 1] *= rscale + width = min(points[1, 1] - points[0, 1], 0.5) + + # Generate bounding box for wedge. + wedge = mpatches.Wedge(self._center, points[1, 1], + points[0, 0], points[1, 0], + width=width) + self.update_from_path(wedge.get_path()) + + # Ensure equal aspect ratio. + w, h = self._points[1] - self._points[0] + deltah = max(w - h, 0) / 2 + deltaw = max(h - w, 0) / 2 + self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]]) + + self._invalid = 0 + + return self._points + + +class PolarAxes(Axes): + """ + A polar graph projection, where the input dimensions are *theta*, *r*. + + Theta starts pointing east and goes anti-clockwise. + """ + name = 'polar' + + def __init__(self, *args, + theta_offset=0, theta_direction=1, rlabel_position=22.5, + **kwargs): + # docstring inherited + self._default_theta_offset = theta_offset + self._default_theta_direction = theta_direction + self._default_rlabel_position = np.deg2rad(rlabel_position) + super().__init__(*args, **kwargs) + self.use_sticky_edges = True + self.set_aspect('equal', adjustable='box', anchor='C') + self.clear() + + def clear(self): + # docstring inherited + super().clear() + + self.title.set_y(1.05) + + start = self.spines.get('start', None) + if start: + start.set_visible(False) + end = self.spines.get('end', None) + if end: + end.set_visible(False) + self.set_xlim(0.0, 2 * np.pi) + + self.grid(mpl.rcParams['polaraxes.grid']) + inner = self.spines.get('inner', None) + if inner: + inner.set_visible(False) + + self.set_rorigin(None) + self.set_theta_offset(self._default_theta_offset) + self.set_theta_direction(self._default_theta_direction) + + def _init_axis(self): + # This is moved out of __init__ because non-separable axes don't use it + self.xaxis = ThetaAxis(self, clear=False) + self.yaxis = RadialAxis(self, clear=False) + self.spines['polar'].register_axis(self.yaxis) + + def _set_lim_and_transforms(self): + # A view limit where the minimum radius can be locked if the user + # specifies an alternate origin. + self._originViewLim = mtransforms.LockableBbox(self.viewLim) + + # Handle angular offset and direction. + self._direction = mtransforms.Affine2D() \ + .scale(self._default_theta_direction, 1.0) + self._theta_offset = mtransforms.Affine2D() \ + .translate(self._default_theta_offset, 0.0) + self.transShift = self._direction + self._theta_offset + # A view limit shifted to the correct location after accounting for + # orientation and offset. + self._realViewLim = mtransforms.TransformedBbox(self.viewLim, + self.transShift) + + # Transforms the x and y axis separately by a scale factor + # It is assumed that this part will have non-linear components + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + # Scale view limit into a bbox around the selected wedge. This may be + # smaller than the usual unit axes rectangle if not plotting the full + # circle. + self.axesLim = _WedgeBbox((0.5, 0.5), + self._realViewLim, self._originViewLim) + + # Scale the wedge to fill the axes. + self.transWedge = mtransforms.BboxTransformFrom(self.axesLim) + + # Scale the axes to fill the figure. + self.transAxes = mtransforms.BboxTransformTo(self.bbox) + + # A (possibly non-linear) projection on the (already scaled) + # data. This one is aware of rmin + self.transProjection = self.PolarTransform( + self, + apply_theta_transforms=False, + scale_transform=self.transScale + ) + # Add dependency on rorigin. + self.transProjection.set_children(self._originViewLim) + + # An affine transformation on the data, generally to limit the + # range of the axes + self.transProjectionAffine = self.PolarAffine(self.transScale, + self._originViewLim) + + # The complete data transformation stack -- from data all the + # way to display coordinates + # + # 1. Remove any radial axis scaling (e.g. log scaling) + # 2. Shift data in the theta direction + # 3. Project the data from polar to cartesian values + # (with the origin in the same place) + # 4. Scale and translate the cartesian values to Axes coordinates + # (here the origin is moved to the lower left of the Axes) + # 5. Move and scale to fill the Axes + # 6. Convert from Axes coordinates to Figure coordinates + self.transData = ( + self.transScale + + self.transShift + + self.transProjection + + ( + self.transProjectionAffine + + self.transWedge + + self.transAxes + ) + ) + + # This is the transform for theta-axis ticks. It is + # equivalent to transData, except it always puts r == 0.0 and r == 1.0 + # at the edge of the axis circles. + self._xaxis_transform = ( + mtransforms.blended_transform_factory( + mtransforms.IdentityTransform(), + mtransforms.BboxTransformTo(self.viewLim)) + + self.transData) + # The theta labels are flipped along the radius, so that text 1 is on + # the outside by default. This should work the same as before. + flipr_transform = mtransforms.Affine2D() \ + .translate(0.0, -0.5) \ + .scale(1.0, -1.0) \ + .translate(0.0, 0.5) + self._xaxis_text_transform = flipr_transform + self._xaxis_transform + + # This is the transform for r-axis ticks. It scales the theta + # axis so the gridlines from 0.0 to 1.0, now go from thetamin to + # thetamax. + self._yaxis_transform = ( + mtransforms.blended_transform_factory( + mtransforms.BboxTransformTo(self.viewLim), + mtransforms.IdentityTransform()) + + self.transData) + # The r-axis labels are put at an angle and padded in the r-direction + self._r_label_position = mtransforms.Affine2D() \ + .translate(self._default_rlabel_position, 0.0) + self._yaxis_text_transform = mtransforms.TransformWrapper( + self._r_label_position + self.transData) + + def get_xaxis_transform(self, which='grid'): + _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) + return self._xaxis_transform + + def get_xaxis_text1_transform(self, pad): + return self._xaxis_text_transform, 'center', 'center' + + def get_xaxis_text2_transform(self, pad): + return self._xaxis_text_transform, 'center', 'center' + + def get_yaxis_transform(self, which='grid'): + if which in ('tick1', 'tick2'): + return self._yaxis_text_transform + elif which == 'grid': + return self._yaxis_transform + else: + _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) + + def get_yaxis_text1_transform(self, pad): + thetamin, thetamax = self._realViewLim.intervalx + if _is_full_circle_rad(thetamin, thetamax): + return self._yaxis_text_transform, 'bottom', 'left' + elif self.get_theta_direction() > 0: + halign = 'left' + pad_shift = _ThetaShift(self, pad, 'min') + else: + halign = 'right' + pad_shift = _ThetaShift(self, pad, 'max') + return self._yaxis_text_transform + pad_shift, 'center', halign + + def get_yaxis_text2_transform(self, pad): + if self.get_theta_direction() > 0: + halign = 'right' + pad_shift = _ThetaShift(self, pad, 'max') + else: + halign = 'left' + pad_shift = _ThetaShift(self, pad, 'min') + return self._yaxis_text_transform + pad_shift, 'center', halign + + def draw(self, renderer): + self._unstale_viewLim() + thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx) + if thetamin > thetamax: + thetamin, thetamax = thetamax, thetamin + rmin, rmax = ((self._realViewLim.intervaly - self.get_rorigin()) * + self.get_rsign()) + if isinstance(self.patch, mpatches.Wedge): + # Backwards-compatibility: Any subclassed Axes might override the + # patch to not be the Wedge that PolarAxes uses. + center = self.transWedge.transform((0.5, 0.5)) + self.patch.set_center(center) + self.patch.set_theta1(thetamin) + self.patch.set_theta2(thetamax) + + edge, _ = self.transWedge.transform((1, 0)) + radius = edge - center[0] + width = min(radius * (rmax - rmin) / rmax, radius) + self.patch.set_radius(radius) + self.patch.set_width(width) + + inner_width = radius - width + inner = self.spines.get('inner', None) + if inner: + inner.set_visible(inner_width != 0.0) + + visible = not _is_full_circle_deg(thetamin, thetamax) + # For backwards compatibility, any subclassed Axes might override the + # spines to not include start/end that PolarAxes uses. + start = self.spines.get('start', None) + end = self.spines.get('end', None) + if start: + start.set_visible(visible) + if end: + end.set_visible(visible) + if visible: + yaxis_text_transform = self._yaxis_transform + else: + yaxis_text_transform = self._r_label_position + self.transData + if self._yaxis_text_transform != yaxis_text_transform: + self._yaxis_text_transform.set(yaxis_text_transform) + self.yaxis.reset_ticks() + self.yaxis.set_clip_path(self.patch) + + super().draw(renderer) + + def _gen_axes_patch(self): + return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0) + + def _gen_axes_spines(self): + spines = { + 'polar': Spine.arc_spine(self, 'top', (0.5, 0.5), 0.5, 0, 360), + 'start': Spine.linear_spine(self, 'left'), + 'end': Spine.linear_spine(self, 'right'), + 'inner': Spine.arc_spine(self, 'bottom', (0.5, 0.5), 0.0, 0, 360), + } + spines['polar'].set_transform(self.transWedge + self.transAxes) + spines['inner'].set_transform(self.transWedge + self.transAxes) + spines['start'].set_transform(self._yaxis_transform) + spines['end'].set_transform(self._yaxis_transform) + return spines + + def set_thetamax(self, thetamax): + """Set the maximum theta limit in degrees.""" + self.viewLim.x1 = np.deg2rad(thetamax) + + def get_thetamax(self): + """Return the maximum theta limit in degrees.""" + return np.rad2deg(self.viewLim.xmax) + + def set_thetamin(self, thetamin): + """Set the minimum theta limit in degrees.""" + self.viewLim.x0 = np.deg2rad(thetamin) + + def get_thetamin(self): + """Get the minimum theta limit in degrees.""" + return np.rad2deg(self.viewLim.xmin) + + def set_thetalim(self, *args, **kwargs): + r""" + Set the minimum and maximum theta values. + + Can take the following signatures: + + - ``set_thetalim(minval, maxval)``: Set the limits in radians. + - ``set_thetalim(thetamin=minval, thetamax=maxval)``: Set the limits + in degrees. + + where minval and maxval are the minimum and maximum limits. Values are + wrapped in to the range :math:`[0, 2\pi]` (in radians), so for example + it is possible to do ``set_thetalim(-np.pi / 2, np.pi / 2)`` to have + an axis symmetric around 0. A ValueError is raised if the absolute + angle difference is larger than a full circle. + """ + orig_lim = self.get_xlim() # in radians + if 'thetamin' in kwargs: + kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin')) + if 'thetamax' in kwargs: + kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax')) + new_min, new_max = self.set_xlim(*args, **kwargs) + # Parsing all permutations of *args, **kwargs is tricky; it is simpler + # to let set_xlim() do it and then validate the limits. + if abs(new_max - new_min) > 2 * np.pi: + self.set_xlim(orig_lim) # un-accept the change + raise ValueError("The angle range must be less than a full circle") + return tuple(np.rad2deg((new_min, new_max))) + + def set_theta_offset(self, offset): + """ + Set the offset for the location of 0 in radians. + """ + mtx = self._theta_offset.get_matrix() + mtx[0, 2] = offset + self._theta_offset.invalidate() + + def get_theta_offset(self): + """ + Get the offset for the location of 0 in radians. + """ + return self._theta_offset.get_matrix()[0, 2] + + def set_theta_zero_location(self, loc, offset=0.0): + """ + Set the location of theta's zero. + + This simply calls `set_theta_offset` with the correct value in radians. + + Parameters + ---------- + loc : str + May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE". + offset : float, default: 0 + An offset in degrees to apply from the specified *loc*. **Note:** + this offset is *always* applied counter-clockwise regardless of + the direction setting. + """ + mapping = { + 'N': np.pi * 0.5, + 'NW': np.pi * 0.75, + 'W': np.pi, + 'SW': np.pi * 1.25, + 'S': np.pi * 1.5, + 'SE': np.pi * 1.75, + 'E': 0, + 'NE': np.pi * 0.25} + return self.set_theta_offset(mapping[loc] + np.deg2rad(offset)) + + def set_theta_direction(self, direction): + """ + Set the direction in which theta increases. + + clockwise, -1: + Theta increases in the clockwise direction + + counterclockwise, anticlockwise, 1: + Theta increases in the counterclockwise direction + """ + mtx = self._direction.get_matrix() + if direction in ('clockwise', -1): + mtx[0, 0] = -1 + elif direction in ('counterclockwise', 'anticlockwise', 1): + mtx[0, 0] = 1 + else: + _api.check_in_list( + [-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'], + direction=direction) + self._direction.invalidate() + + def get_theta_direction(self): + """ + Get the direction in which theta increases. + + -1: + Theta increases in the clockwise direction + + 1: + Theta increases in the counterclockwise direction + """ + return self._direction.get_matrix()[0, 0] + + def set_rmax(self, rmax): + """ + Set the outer radial limit. + + Parameters + ---------- + rmax : float + """ + self.viewLim.y1 = rmax + + def get_rmax(self): + """ + Returns + ------- + float + Outer radial limit. + """ + return self.viewLim.ymax + + def set_rmin(self, rmin): + """ + Set the inner radial limit. + + Parameters + ---------- + rmin : float + """ + self.viewLim.y0 = rmin + + def get_rmin(self): + """ + Returns + ------- + float + The inner radial limit. + """ + return self.viewLim.ymin + + def set_rorigin(self, rorigin): + """ + Update the radial origin. + + Parameters + ---------- + rorigin : float + """ + self._originViewLim.locked_y0 = rorigin + + def get_rorigin(self): + """ + Returns + ------- + float + """ + return self._originViewLim.y0 + + def get_rsign(self): + return np.sign(self._originViewLim.y1 - self._originViewLim.y0) + + def set_rlim(self, bottom=None, top=None, *, + emit=True, auto=False, **kwargs): + """ + Set the radial axis view limits. + + This function behaves like `.Axes.set_ylim`, but additionally supports + *rmin* and *rmax* as aliases for *bottom* and *top*. + + See Also + -------- + .Axes.set_ylim + """ + if 'rmin' in kwargs: + if bottom is None: + bottom = kwargs.pop('rmin') + else: + raise ValueError('Cannot supply both positional "bottom"' + 'argument and kwarg "rmin"') + if 'rmax' in kwargs: + if top is None: + top = kwargs.pop('rmax') + else: + raise ValueError('Cannot supply both positional "top"' + 'argument and kwarg "rmax"') + return self.set_ylim(bottom=bottom, top=top, emit=emit, auto=auto, + **kwargs) + + def get_rlabel_position(self): + """ + Returns + ------- + float + The theta position of the radius labels in degrees. + """ + return np.rad2deg(self._r_label_position.get_matrix()[0, 2]) + + def set_rlabel_position(self, value): + """ + Update the theta position of the radius labels. + + Parameters + ---------- + value : number + The angular position of the radius labels in degrees. + """ + self._r_label_position.clear().translate(np.deg2rad(value), 0.0) + + def set_yscale(self, *args, **kwargs): + super().set_yscale(*args, **kwargs) + self.yaxis.set_major_locator( + self.RadialLocator(self.yaxis.get_major_locator(), self)) + + def set_rscale(self, *args, **kwargs): + return Axes.set_yscale(self, *args, **kwargs) + + def set_rticks(self, *args, **kwargs): + return Axes.set_yticks(self, *args, **kwargs) + + def set_thetagrids(self, angles, labels=None, fmt=None, **kwargs): + """ + Set the theta gridlines in a polar plot. + + Parameters + ---------- + angles : tuple with floats, degrees + The angles of the theta gridlines. + + labels : tuple with strings or None + The labels to use at each theta gridline. The + `.projections.polar.ThetaFormatter` will be used if None. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. Note that the angle that is used is in + radians. + + Returns + ------- + lines : list of `.lines.Line2D` + The theta gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + .. warning:: + + This only sets the properties of the current ticks. + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `.set_tick_params` instead if possible. + + See Also + -------- + .PolarAxes.set_rgrids + .Axis.get_gridlines + .Axis.get_ticklabels + """ + + # Make sure we take into account unitized data + angles = self.convert_yunits(angles) + angles = np.deg2rad(angles) + self.set_xticks(angles) + if labels is not None: + self.set_xticklabels(labels) + elif fmt is not None: + self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) + for t in self.xaxis.get_ticklabels(): + t._internal_update(kwargs) + return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() + + def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): + """ + Set the radial gridlines on a polar plot. + + Parameters + ---------- + radii : tuple with floats + The radii for the radial gridlines + + labels : tuple with strings or None + The labels to use at each radial gridline. The + `matplotlib.ticker.ScalarFormatter` will be used if None. + + angle : float + The angular position of the radius labels in degrees. + + fmt : str or None + Format string used in `matplotlib.ticker.FormatStrFormatter`. + For example '%f'. + + Returns + ------- + lines : list of `.lines.Line2D` + The radial gridlines. + + labels : list of `.text.Text` + The tick labels. + + Other Parameters + ---------------- + **kwargs + *kwargs* are optional `.Text` properties for the labels. + + .. warning:: + + This only sets the properties of the current ticks. + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `.set_tick_params` instead if possible. + + See Also + -------- + .PolarAxes.set_thetagrids + .Axis.get_gridlines + .Axis.get_ticklabels + """ + # Make sure we take into account unitized data + radii = self.convert_xunits(radii) + radii = np.asarray(radii) + + self.set_yticks(radii) + if labels is not None: + self.set_yticklabels(labels) + elif fmt is not None: + self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) + if angle is None: + angle = self.get_rlabel_position() + self.set_rlabel_position(angle) + for t in self.yaxis.get_ticklabels(): + t._internal_update(kwargs) + return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() + + def format_coord(self, theta, r): + # docstring inherited + screen_xy = self.transData.transform((theta, r)) + screen_xys = screen_xy + np.stack( + np.meshgrid([-1, 0, 1], [-1, 0, 1])).reshape((2, -1)).T + ts, rs = self.transData.inverted().transform(screen_xys).T + delta_t = abs((ts - theta + np.pi) % (2 * np.pi) - np.pi).max() + delta_t_halfturns = delta_t / np.pi + delta_t_degrees = delta_t_halfturns * 180 + delta_r = abs(rs - r).max() + if theta < 0: + theta += 2 * np.pi + theta_halfturns = theta / np.pi + theta_degrees = theta_halfturns * 180 + + # See ScalarFormatter.format_data_short. For r, use #g-formatting + # (as for linear axes), but for theta, use f-formatting as scientific + # notation doesn't make sense and the trailing dot is ugly. + def format_sig(value, delta, opt, fmt): + # For "f", only count digits after decimal point. + prec = (max(0, -math.floor(math.log10(delta))) if fmt == "f" else + cbook._g_sig_digits(value, delta)) + return f"{value:-{opt}.{prec}{fmt}}" + + # In case fmt_xdata was not specified, resort to default + + if self.fmt_ydata is None: + r_label = format_sig(r, delta_r, "#", "g") + else: + r_label = self.format_ydata(r) + + if self.fmt_xdata is None: + return ('\N{GREEK SMALL LETTER THETA}={}\N{GREEK SMALL LETTER PI} ' + '({}\N{DEGREE SIGN}), r={}').format( + format_sig(theta_halfturns, delta_t_halfturns, "", "f"), + format_sig(theta_degrees, delta_t_degrees, "", "f"), + r_label + ) + else: + return '\N{GREEK SMALL LETTER THETA}={}, r={}'.format( + self.format_xdata(theta), + r_label + ) + + def get_data_ratio(self): + """ + Return the aspect ratio of the data itself. For a polar plot, + this should always be 1.0 + """ + return 1.0 + + # # # Interactive panning + + def can_zoom(self): + """ + Return whether this Axes supports the zoom box button functionality. + + A polar Axes does not support zoom boxes. + """ + return False + + def can_pan(self): + """ + Return whether this Axes supports the pan/zoom button functionality. + + For a polar Axes, this is slightly misleading. Both panning and + zooming are performed by the same button. Panning is performed + in azimuth while zooming is done along the radial. + """ + return True + + def start_pan(self, x, y, button): + angle = np.deg2rad(self.get_rlabel_position()) + mode = '' + if button == 1: + epsilon = np.pi / 45.0 + t, r = self.transData.inverted().transform((x, y)) + if angle - epsilon <= t <= angle + epsilon: + mode = 'drag_r_labels' + elif button == 3: + mode = 'zoom' + + self._pan_start = types.SimpleNamespace( + rmax=self.get_rmax(), + trans=self.transData.frozen(), + trans_inverse=self.transData.inverted().frozen(), + r_label_angle=self.get_rlabel_position(), + x=x, + y=y, + mode=mode) + + def end_pan(self): + del self._pan_start + + def drag_pan(self, button, key, x, y): + p = self._pan_start + + if p.mode == 'drag_r_labels': + (startt, startr), (t, r) = p.trans_inverse.transform( + [(p.x, p.y), (x, y)]) + + # Deal with theta + dt = np.rad2deg(startt - t) + self.set_rlabel_position(p.r_label_angle - dt) + + trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0) + trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0) + for t in self.yaxis.majorTicks + self.yaxis.minorTicks: + t.label1.set_va(vert1) + t.label1.set_ha(horiz1) + t.label2.set_va(vert2) + t.label2.set_ha(horiz2) + + elif p.mode == 'zoom': + (startt, startr), (t, r) = p.trans_inverse.transform( + [(p.x, p.y), (x, y)]) + + # Deal with r + scale = r / startr + self.set_rmax(p.rmax / scale) + + +# To keep things all self-contained, we can put aliases to the Polar classes +# defined above. This isn't strictly necessary, but it makes some of the +# code more readable, and provides a backwards compatible Polar API. In +# particular, this is used by the :doc:`/gallery/specialty_plots/radar_chart` +# example to override PolarTransform on a PolarAxes subclass, so make sure that +# that example is unaffected before changing this. +PolarAxes.PolarTransform = PolarTransform +PolarAxes.PolarAffine = PolarAffine +PolarAxes.InvertedPolarTransform = InvertedPolarTransform +PolarAxes.ThetaFormatter = ThetaFormatter +PolarAxes.RadialLocator = RadialLocator +PolarAxes.ThetaLocator = ThetaLocator diff --git a/python_embeded/Lib/site-packages/matplotlib/projections/polar.pyi b/python_embeded/Lib/site-packages/matplotlib/projections/polar.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de1cbc293900382e25e6ebfb6e94a3409ad16462 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/projections/polar.pyi @@ -0,0 +1,197 @@ +import matplotlib.axis as maxis +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +from matplotlib.axes import Axes +from matplotlib.lines import Line2D +from matplotlib.text import Text + +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Sequence +from typing import Any, ClassVar, Literal, overload + +class PolarTransform(mtransforms.Transform): + input_dims: int + output_dims: int + def __init__( + self, + axis: PolarAxes | None = ..., + use_rmin: bool = ..., + *, + apply_theta_transforms: bool = ..., + scale_transform: mtransforms.Transform | None = ..., + ) -> None: ... + def inverted(self) -> InvertedPolarTransform: ... + +class PolarAffine(mtransforms.Affine2DBase): + def __init__( + self, scale_transform: mtransforms.Transform, limits: mtransforms.BboxBase + ) -> None: ... + +class InvertedPolarTransform(mtransforms.Transform): + input_dims: int + output_dims: int + def __init__( + self, + axis: PolarAxes | None = ..., + use_rmin: bool = ..., + *, + apply_theta_transforms: bool = ..., + ) -> None: ... + def inverted(self) -> PolarTransform: ... + +class ThetaFormatter(mticker.Formatter): ... + +class _AxisWrapper: + def __init__(self, axis: maxis.Axis) -> None: ... + def get_view_interval(self) -> np.ndarray: ... + def set_view_interval(self, vmin: float, vmax: float) -> None: ... + def get_minpos(self) -> float: ... + def get_data_interval(self) -> np.ndarray: ... + def set_data_interval(self, vmin: float, vmax: float) -> None: ... + def get_tick_space(self) -> int: ... + +class ThetaLocator(mticker.Locator): + base: mticker.Locator + axis: _AxisWrapper | None + def __init__(self, base: mticker.Locator) -> None: ... + +class ThetaTick(maxis.XTick): + def __init__(self, axes: PolarAxes, *args, **kwargs) -> None: ... + +class ThetaAxis(maxis.XAxis): + axis_name: str + +class RadialLocator(mticker.Locator): + base: mticker.Locator + def __init__(self, base, axes: PolarAxes | None = ...) -> None: ... + +class RadialTick(maxis.YTick): ... + +class RadialAxis(maxis.YAxis): + axis_name: str + +class _WedgeBbox(mtransforms.Bbox): + def __init__( + self, + center: tuple[float, float], + viewLim: mtransforms.Bbox, + originLim: mtransforms.Bbox, + **kwargs, + ) -> None: ... + +class PolarAxes(Axes): + + PolarTransform: ClassVar[type] = PolarTransform + PolarAffine: ClassVar[type] = PolarAffine + InvertedPolarTransform: ClassVar[type] = InvertedPolarTransform + ThetaFormatter: ClassVar[type] = ThetaFormatter + RadialLocator: ClassVar[type] = RadialLocator + ThetaLocator: ClassVar[type] = ThetaLocator + + name: str + use_sticky_edges: bool + def __init__( + self, + *args, + theta_offset: float = ..., + theta_direction: float = ..., + rlabel_position: float = ..., + **kwargs, + ) -> None: ... + def get_xaxis_transform( + self, which: Literal["tick1", "tick2", "grid"] = ... + ) -> mtransforms.Transform: ... + def get_xaxis_text1_transform( + self, pad: float + ) -> tuple[ + mtransforms.Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_xaxis_text2_transform( + self, pad: float + ) -> tuple[ + mtransforms.Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_transform( + self, which: Literal["tick1", "tick2", "grid"] = ... + ) -> mtransforms.Transform: ... + def get_yaxis_text1_transform( + self, pad: float + ) -> tuple[ + mtransforms.Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def get_yaxis_text2_transform( + self, pad: float + ) -> tuple[ + mtransforms.Transform, + Literal["center", "top", "bottom", "baseline", "center_baseline"], + Literal["center", "left", "right"], + ]: ... + def set_thetamax(self, thetamax: float) -> None: ... + def get_thetamax(self) -> float: ... + def set_thetamin(self, thetamin: float) -> None: ... + def get_thetamin(self) -> float: ... + @overload + def set_thetalim(self, minval: float, maxval: float, /) -> tuple[float, float]: ... + @overload + def set_thetalim(self, *, thetamin: float, thetamax: float) -> tuple[float, float]: ... + def set_theta_offset(self, offset: float) -> None: ... + def get_theta_offset(self) -> float: ... + def set_theta_zero_location( + self, + loc: Literal["N", "NW", "W", "SW", "S", "SE", "E", "NE"], + offset: float = ..., + ) -> None: ... + def set_theta_direction( + self, + direction: Literal[-1, 1, "clockwise", "counterclockwise", "anticlockwise"], + ) -> None: ... + def get_theta_direction(self) -> Literal[-1, 1]: ... + def set_rmax(self, rmax: float) -> None: ... + def get_rmax(self) -> float: ... + def set_rmin(self, rmin: float) -> None: ... + def get_rmin(self) -> float: ... + def set_rorigin(self, rorigin: float | None) -> None: ... + def get_rorigin(self) -> float: ... + def get_rsign(self) -> float: ... + def set_rlim( + self, + bottom: float | tuple[float, float] | None = ..., + top: float | None = ..., + *, + emit: bool = ..., + auto: bool = ..., + **kwargs, + ) -> tuple[float, float]: ... + def get_rlabel_position(self) -> float: ... + def set_rlabel_position(self, value: float) -> None: ... + def set_rscale(self, *args, **kwargs) -> None: ... + def set_rticks(self, *args, **kwargs) -> None: ... + def set_thetagrids( + self, + angles: ArrayLike, + labels: Sequence[str | Text] | None = ..., + fmt: str | None = ..., + **kwargs, + ) -> tuple[list[Line2D], list[Text]]: ... + def set_rgrids( + self, + radii: ArrayLike, + labels: Sequence[str | Text] | None = ..., + angle: float | None = ..., + fmt: str | None = ..., + **kwargs, + ) -> tuple[list[Line2D], list[Text]]: ... + def format_coord(self, theta: float, r: float) -> str: ... + def get_data_ratio(self) -> float: ... + def can_zoom(self) -> bool: ... + def can_pan(self) -> bool: ... + def start_pan(self, x: float, y: float, button: int) -> None: ... + def end_pan(self) -> None: ... + def drag_pan(self, button: Any, key: Any, x: float, y: float) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/sphinxext/__init__.py b/python_embeded/Lib/site-packages/matplotlib/sphinxext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/matplotlib/sphinxext/figmpl_directive.py b/python_embeded/Lib/site-packages/matplotlib/sphinxext/figmpl_directive.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb9c6c04e8a130fe9d61c3a4c66f0ba4d80b1ad --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/sphinxext/figmpl_directive.py @@ -0,0 +1,286 @@ +""" +Add a ``figure-mpl`` directive that is a responsive version of ``figure``. + +This implementation is very similar to ``.. figure::``, except it also allows a +``srcset=`` argument to be passed to the image tag, hence allowing responsive +resolution images. + +There is no particular reason this could not be used standalone, but is meant +to be used with :doc:`/api/sphinxext_plot_directive_api`. + +Note that the directory organization is a bit different than ``.. figure::``. +See the *FigureMpl* documentation below. + +""" +import os +from os.path import relpath +from pathlib import PurePath, Path +import shutil + +from docutils import nodes +from docutils.parsers.rst import directives +from docutils.parsers.rst.directives.images import Figure, Image +from sphinx.errors import ExtensionError + +import matplotlib + + +class figmplnode(nodes.General, nodes.Element): + pass + + +class FigureMpl(Figure): + """ + Implements a directive to allow an optional hidpi image. + + Meant to be used with the *plot_srcset* configuration option in conf.py, + and gets set in the TEMPLATE of plot_directive.py + + e.g.:: + + .. figure-mpl:: plot_directive/some_plots-1.png + :alt: bar + :srcset: plot_directive/some_plots-1.png, + plot_directive/some_plots-1.2x.png 2.00x + :class: plot-directive + + The resulting html (at ``some_plots.html``) is:: + + bar + + Note that the handling of subdirectories is different than that used by the sphinx + figure directive:: + + .. figure-mpl:: plot_directive/nestedpage/index-1.png + :alt: bar + :srcset: plot_directive/nestedpage/index-1.png + plot_directive/nestedpage/index-1.2x.png 2.00x + :class: plot_directive + + The resulting html (at ``nestedpage/index.html``):: + + bar + + where the subdirectory is included in the image name for uniqueness. + """ + + has_content = False + required_arguments = 1 + optional_arguments = 2 + final_argument_whitespace = False + option_spec = { + 'alt': directives.unchanged, + 'height': directives.length_or_unitless, + 'width': directives.length_or_percentage_or_unitless, + 'scale': directives.nonnegative_int, + 'align': Image.align, + 'class': directives.class_option, + 'caption': directives.unchanged, + 'srcset': directives.unchanged, + } + + def run(self): + + image_node = figmplnode() + + imagenm = self.arguments[0] + image_node['alt'] = self.options.get('alt', '') + image_node['align'] = self.options.get('align', None) + image_node['class'] = self.options.get('class', None) + image_node['width'] = self.options.get('width', None) + image_node['height'] = self.options.get('height', None) + image_node['scale'] = self.options.get('scale', None) + image_node['caption'] = self.options.get('caption', None) + + # we would like uri to be the highest dpi version so that + # latex etc will use that. But for now, lets just make + # imagenm... maybe pdf one day? + + image_node['uri'] = imagenm + image_node['srcset'] = self.options.get('srcset', None) + + return [image_node] + + +def _parse_srcsetNodes(st): + """ + parse srcset... + """ + entries = st.split(',') + srcset = {} + for entry in entries: + spl = entry.strip().split(' ') + if len(spl) == 1: + srcset[0] = spl[0] + elif len(spl) == 2: + mult = spl[1][:-1] + srcset[float(mult)] = spl[0] + else: + raise ExtensionError(f'srcset argument "{entry}" is invalid.') + return srcset + + +def _copy_images_figmpl(self, node): + + # these will be the temporary place the plot-directive put the images eg: + # ../../../build/html/plot_directive/users/explain/artists/index-1.png + if node['srcset']: + srcset = _parse_srcsetNodes(node['srcset']) + else: + srcset = None + + # the rst file's location: eg /Users/username/matplotlib/doc/users/explain/artists + docsource = PurePath(self.document['source']).parent + + # get the relpath relative to root: + srctop = self.builder.srcdir + rel = relpath(docsource, srctop).replace('.', '').replace(os.sep, '-') + if len(rel): + rel += '-' + # eg: users/explain/artists + + imagedir = PurePath(self.builder.outdir, self.builder.imagedir) + # eg: /Users/username/matplotlib/doc/build/html/_images/users/explain/artists + + Path(imagedir).mkdir(parents=True, exist_ok=True) + + # copy all the sources to the imagedir: + if srcset: + for src in srcset.values(): + # the entries in srcset are relative to docsource's directory + abspath = PurePath(docsource, src) + name = rel + abspath.name + shutil.copyfile(abspath, imagedir / name) + else: + abspath = PurePath(docsource, node['uri']) + name = rel + abspath.name + shutil.copyfile(abspath, imagedir / name) + + return imagedir, srcset, rel + + +def visit_figmpl_html(self, node): + + imagedir, srcset, rel = _copy_images_figmpl(self, node) + + # /doc/examples/subd/plot_1.rst + docsource = PurePath(self.document['source']) + # /doc/ + # make sure to add the trailing slash: + srctop = PurePath(self.builder.srcdir, '') + # examples/subd/plot_1.rst + relsource = relpath(docsource, srctop) + # /doc/build/html + desttop = PurePath(self.builder.outdir, '') + # /doc/build/html/examples/subd + dest = desttop / relsource + + # ../../_images/ for dirhtml and ../_images/ for html + imagerel = PurePath(relpath(imagedir, dest.parent)).as_posix() + if self.builder.name == "dirhtml": + imagerel = f'..{imagerel}' + + # make uri also be relative... + nm = PurePath(node['uri'][1:]).name + uri = f'{imagerel}/{rel}{nm}' + img_attrs = {'src': uri, 'alt': node['alt']} + + # make srcset str. Need to change all the prefixes! + maxsrc = uri + if srcset: + maxmult = -1 + srcsetst = '' + for mult, src in srcset.items(): + nm = PurePath(src[1:]).name + # ../../_images/plot_1_2_0x.png + path = f'{imagerel}/{rel}{nm}' + srcsetst += path + if mult == 0: + srcsetst += ', ' + else: + srcsetst += f' {mult:1.2f}x, ' + + if mult > maxmult: + maxmult = mult + maxsrc = path + + # trim trailing comma and space... + img_attrs['srcset'] = srcsetst[:-2] + + if node['class'] is not None: + img_attrs['class'] = ' '.join(node['class']) + for style in ['width', 'height', 'scale']: + if node[style]: + if 'style' not in img_attrs: + img_attrs['style'] = f'{style}: {node[style]};' + else: + img_attrs['style'] += f'{style}: {node[style]};' + + #
+ # + # _images/index-1.2x.png + # + #
+ #

Figure caption is here.... + # #

+ #
+ #
+ self.body.append( + self.starttag( + node, 'figure', + CLASS=f'align-{node["align"]}' if node['align'] else 'align-center')) + self.body.append( + self.starttag(node, 'a', CLASS='reference internal image-reference', + href=maxsrc) + + self.emptytag(node, 'img', **img_attrs) + + '\n') + if node['caption']: + self.body.append(self.starttag(node, 'figcaption')) + self.body.append(self.starttag(node, 'p')) + self.body.append(self.starttag(node, 'span', CLASS='caption-text')) + self.body.append(node['caption']) + self.body.append('

\n') + self.body.append('\n') + + +def visit_figmpl_latex(self, node): + + if node['srcset'] is not None: + imagedir, srcset = _copy_images_figmpl(self, node) + maxmult = -1 + # choose the highest res version for latex: + maxmult = max(srcset, default=-1) + node['uri'] = PurePath(srcset[maxmult]).name + + self.visit_figure(node) + + +def depart_figmpl_html(self, node): + pass + + +def depart_figmpl_latex(self, node): + self.depart_figure(node) + + +def figurempl_addnode(app): + app.add_node(figmplnode, + html=(visit_figmpl_html, depart_figmpl_html), + latex=(visit_figmpl_latex, depart_figmpl_latex)) + + +def setup(app): + app.add_directive("figure-mpl", FigureMpl) + figurempl_addnode(app) + metadata = {'parallel_read_safe': True, 'parallel_write_safe': True, + 'version': matplotlib.__version__} + return metadata diff --git a/python_embeded/Lib/site-packages/matplotlib/sphinxext/mathmpl.py b/python_embeded/Lib/site-packages/matplotlib/sphinxext/mathmpl.py new file mode 100644 index 0000000000000000000000000000000000000000..30f0245242583c5ea162de9e5443da67d7111465 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/sphinxext/mathmpl.py @@ -0,0 +1,242 @@ +r""" +A role and directive to display mathtext in Sphinx +================================================== + +The ``mathmpl`` Sphinx extension creates a mathtext image in Matplotlib and +shows it in html output. Thus, it is a true and faithful representation of what +you will see if you pass a given LaTeX string to Matplotlib (see +:ref:`mathtext`). + +.. warning:: + In most cases, you will likely want to use one of `Sphinx's builtin Math + extensions + `__ + instead of this one. The builtin Sphinx math directive uses MathJax to + render mathematical expressions, and addresses accessibility concerns that + ``mathmpl`` doesn't address. + +Mathtext may be included in two ways: + +1. Inline, using the role:: + + This text uses inline math: :mathmpl:`\alpha > \beta`. + + which produces: + + This text uses inline math: :mathmpl:`\alpha > \beta`. + +2. Standalone, using the directive:: + + Here is some standalone math: + + .. mathmpl:: + + \alpha > \beta + + which produces: + + Here is some standalone math: + + .. mathmpl:: + + \alpha > \beta + +Options +------- + +The ``mathmpl`` role and directive both support the following options: + +fontset : str, default: 'cm' + The font set to use when displaying math. See :rc:`mathtext.fontset`. + +fontsize : float + The font size, in points. Defaults to the value from the extension + configuration option defined below. + +Configuration options +--------------------- + +The mathtext extension has the following configuration options: + +mathmpl_fontsize : float, default: 10.0 + Default font size, in points. + +mathmpl_srcset : list of str, default: [] + Additional image sizes to generate when embedding in HTML, to support + `responsive resolution images + `__. + The list should contain additional x-descriptors (``'1.5x'``, ``'2x'``, + etc.) to generate (1x is the default and always included.) + +""" + +import hashlib +from pathlib import Path + +from docutils import nodes +from docutils.parsers.rst import Directive, directives +import sphinx +from sphinx.errors import ConfigError, ExtensionError + +import matplotlib as mpl +from matplotlib import _api, mathtext +from matplotlib.rcsetup import validate_float_or_None + + +# Define LaTeX math node: +class latex_math(nodes.General, nodes.Element): + pass + + +def fontset_choice(arg): + return directives.choice(arg, mathtext.MathTextParser._font_type_mapping) + + +def math_role(role, rawtext, text, lineno, inliner, + options={}, content=[]): + i = rawtext.find('`') + latex = rawtext[i+1:-1] + node = latex_math(rawtext) + node['latex'] = latex + node['fontset'] = options.get('fontset', 'cm') + node['fontsize'] = options.get('fontsize', + setup.app.config.mathmpl_fontsize) + return [node], [] +math_role.options = {'fontset': fontset_choice, + 'fontsize': validate_float_or_None} + + +class MathDirective(Directive): + """ + The ``.. mathmpl::`` directive, as documented in the module's docstring. + """ + has_content = True + required_arguments = 0 + optional_arguments = 0 + final_argument_whitespace = False + option_spec = {'fontset': fontset_choice, + 'fontsize': validate_float_or_None} + + def run(self): + latex = ''.join(self.content) + node = latex_math(self.block_text) + node['latex'] = latex + node['fontset'] = self.options.get('fontset', 'cm') + node['fontsize'] = self.options.get('fontsize', + setup.app.config.mathmpl_fontsize) + return [node] + + +# This uses mathtext to render the expression +def latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100): + with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}): + try: + depth = mathtext.math_to_image( + f"${latex}$", filename, dpi=dpi, format="png") + except Exception: + _api.warn_external(f"Could not render math expression {latex}") + depth = 0 + return depth + + +# LaTeX to HTML translation stuff: +def latex2html(node, source): + inline = isinstance(node.parent, nodes.TextElement) + latex = node['latex'] + fontset = node['fontset'] + fontsize = node['fontsize'] + name = 'math-{}'.format( + hashlib.sha256( + f'{latex}{fontset}{fontsize}'.encode(), + usedforsecurity=False, + ).hexdigest()[-10:]) + + destdir = Path(setup.app.builder.outdir, '_images', 'mathmpl') + destdir.mkdir(parents=True, exist_ok=True) + + dest = destdir / f'{name}.png' + depth = latex2png(latex, dest, fontset, fontsize=fontsize) + + srcset = [] + for size in setup.app.config.mathmpl_srcset: + filename = f'{name}-{size.replace(".", "_")}.png' + latex2png(latex, destdir / filename, fontset, fontsize=fontsize, + dpi=100 * float(size[:-1])) + srcset.append( + f'{setup.app.builder.imgpath}/mathmpl/{filename} {size}') + if srcset: + srcset = (f'srcset="{setup.app.builder.imgpath}/mathmpl/{name}.png, ' + + ', '.join(srcset) + '" ') + + if inline: + cls = '' + else: + cls = 'class="center" ' + if inline and depth != 0: + style = 'style="position: relative; bottom: -%dpx"' % (depth + 1) + else: + style = '' + + return (f'') + + +def _config_inited(app, config): + # Check for srcset hidpi images + for i, size in enumerate(app.config.mathmpl_srcset): + if size[-1] == 'x': # "2x" = "2.0" + try: + float(size[:-1]) + except ValueError: + raise ConfigError( + f'Invalid value for mathmpl_srcset parameter: {size!r}. ' + 'Must be a list of strings with the multiplicative ' + 'factor followed by an "x". e.g. ["2.0x", "1.5x"]') + else: + raise ConfigError( + f'Invalid value for mathmpl_srcset parameter: {size!r}. ' + 'Must be a list of strings with the multiplicative ' + 'factor followed by an "x". e.g. ["2.0x", "1.5x"]') + + +def setup(app): + setup.app = app + app.add_config_value('mathmpl_fontsize', 10.0, True) + app.add_config_value('mathmpl_srcset', [], True) + try: + app.connect('config-inited', _config_inited) # Sphinx 1.8+ + except ExtensionError: + app.connect('env-updated', lambda app, env: _config_inited(app, None)) + + # Add visit/depart methods to HTML-Translator: + def visit_latex_math_html(self, node): + source = self.document.attributes['source'] + self.body.append(latex2html(node, source)) + + def depart_latex_math_html(self, node): + pass + + # Add visit/depart methods to LaTeX-Translator: + def visit_latex_math_latex(self, node): + inline = isinstance(node.parent, nodes.TextElement) + if inline: + self.body.append('$%s$' % node['latex']) + else: + self.body.extend(['\\begin{equation}', + node['latex'], + '\\end{equation}']) + + def depart_latex_math_latex(self, node): + pass + + app.add_node(latex_math, + html=(visit_latex_math_html, depart_latex_math_html), + latex=(visit_latex_math_latex, depart_latex_math_latex)) + app.add_role('mathmpl', math_role) + app.add_directive('mathmpl', MathDirective) + if sphinx.version_info < (1, 8): + app.add_role('math', math_role) + app.add_directive('math', MathDirective) + + metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} + return metadata diff --git a/python_embeded/Lib/site-packages/matplotlib/sphinxext/plot_directive.py b/python_embeded/Lib/site-packages/matplotlib/sphinxext/plot_directive.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9b7d76955015186d148e1a04fa32f3ab245a3e --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/sphinxext/plot_directive.py @@ -0,0 +1,936 @@ +""" +A directive for including a Matplotlib plot in a Sphinx document +================================================================ + +This is a Sphinx extension providing a reStructuredText directive +``.. plot::`` for including a plot in a Sphinx document. + +In HTML output, ``.. plot::`` will include a .png file with a link +to a high-res .png and .pdf. In LaTeX output, it will include a .pdf. + +The plot content may be defined in one of three ways: + +1. **A path to a source file** as the argument to the directive:: + + .. plot:: path/to/plot.py + + When a path to a source file is given, the content of the + directive may optionally contain a caption for the plot:: + + .. plot:: path/to/plot.py + + The plot caption. + + Additionally, one may specify the name of a function to call (with + no arguments) immediately after importing the module:: + + .. plot:: path/to/plot.py plot_function1 + +2. Included as **inline content** to the directive:: + + .. plot:: + + import matplotlib.pyplot as plt + plt.plot([1, 2, 3], [4, 5, 6]) + plt.title("A plotting exammple") + +3. Using **doctest** syntax:: + + .. plot:: + + A plotting example: + >>> import matplotlib.pyplot as plt + >>> plt.plot([1, 2, 3], [4, 5, 6]) + +Options +------- + +The ``.. plot::`` directive supports the following options: + +``:format:`` : {'python', 'doctest'} + The format of the input. If unset, the format is auto-detected. + +``:include-source:`` : bool + Whether to display the source code. The default can be changed using + the ``plot_include_source`` variable in :file:`conf.py` (which itself + defaults to False). + +``:show-source-link:`` : bool + Whether to show a link to the source in HTML. The default can be + changed using the ``plot_html_show_source_link`` variable in + :file:`conf.py` (which itself defaults to True). + +``:context:`` : bool or str + If provided, the code will be run in the context of all previous plot + directives for which the ``:context:`` option was specified. This only + applies to inline code plot directives, not those run from files. If + the ``:context: reset`` option is specified, the context is reset + for this and future plots, and previous figures are closed prior to + running the code. ``:context: close-figs`` keeps the context but closes + previous figures before running the code. + +``:nofigs:`` : bool + If specified, the code block will be run, but no figures will be + inserted. This is usually useful with the ``:context:`` option. + +``:caption:`` : str + If specified, the option's argument will be used as a caption for the + figure. This overwrites the caption given in the content, when the plot + is generated from a file. + +Additionally, this directive supports all the options of the `image directive +`_, +except for ``:target:`` (since plot will add its own target). These include +``:alt:``, ``:height:``, ``:width:``, ``:scale:``, ``:align:`` and ``:class:``. + +Configuration options +--------------------- + +The plot directive has the following configuration options: + +plot_include_source + Default value for the include-source option (default: False). + +plot_html_show_source_link + Whether to show a link to the source in HTML (default: True). + +plot_pre_code + Code that should be executed before each plot. If None (the default), + it will default to a string containing:: + + import numpy as np + from matplotlib import pyplot as plt + +plot_basedir + Base directory, to which ``plot::`` file names are relative to. + If None or empty (the default), file names are relative to the + directory where the file containing the directive is. + +plot_formats + File formats to generate (default: ['png', 'hires.png', 'pdf']). + List of tuples or strings:: + + [(suffix, dpi), suffix, ...] + + that determine the file format and the DPI. For entries whose + DPI was omitted, sensible defaults are chosen. When passing from + the command line through sphinx_build the list should be passed as + suffix:dpi,suffix:dpi, ... + +plot_html_show_formats + Whether to show links to the files in HTML (default: True). + +plot_rcparams + A dictionary containing any non-standard rcParams that should + be applied before each plot (default: {}). + +plot_apply_rcparams + By default, rcParams are applied when ``:context:`` option is not used + in a plot directive. If set, this configuration option overrides this + behavior and applies rcParams before each plot. + +plot_working_directory + By default, the working directory will be changed to the directory of + the example, so the code can get at its data files, if any. Also its + path will be added to `sys.path` so it can import any helper modules + sitting beside it. This configuration option can be used to specify + a central directory (also added to `sys.path`) where data files and + helper modules for all code are located. + +plot_template + Provide a customized template for preparing restructured text. + +plot_srcset + Allow the srcset image option for responsive image resolutions. List of + strings with the multiplicative factors followed by an "x". + e.g. ["2.0x", "1.5x"]. "2.0x" will create a png with the default "png" + resolution from plot_formats, multiplied by 2. If plot_srcset is + specified, the plot directive uses the + :doc:`/api/sphinxext_figmpl_directive_api` (instead of the usual figure + directive) in the intermediary rst file that is generated. + The plot_srcset option is incompatible with *singlehtml* builds, and an + error will be raised. + +Notes on how it works +--------------------- + +The plot directive runs the code it is given, either in the source file or the +code under the directive. The figure created (if any) is saved in the sphinx +build directory under a subdirectory named ``plot_directive``. It then creates +an intermediate rst file that calls a ``.. figure:`` directive (or +``.. figmpl::`` directive if ``plot_srcset`` is being used) and has links to +the ``*.png`` files in the ``plot_directive`` directory. These translations can +be customized by changing the *plot_template*. See the source of +:doc:`/api/sphinxext_plot_directive_api` for the templates defined in *TEMPLATE* +and *TEMPLATE_SRCSET*. +""" + +import contextlib +import doctest +from io import StringIO +import itertools +import os +from os.path import relpath +from pathlib import Path +import re +import shutil +import sys +import textwrap +import traceback + +from docutils.parsers.rst import directives, Directive +from docutils.parsers.rst.directives.images import Image +import jinja2 # Sphinx dependency. + +from sphinx.errors import ExtensionError + +import matplotlib +from matplotlib.backend_bases import FigureManagerBase +import matplotlib.pyplot as plt +from matplotlib import _pylab_helpers, cbook + +matplotlib.use("agg") + +__version__ = 2 + + +# ----------------------------------------------------------------------------- +# Registration hook +# ----------------------------------------------------------------------------- + + +def _option_boolean(arg): + if not arg or not arg.strip(): + # no argument given, assume used as a flag + return True + elif arg.strip().lower() in ('no', '0', 'false'): + return False + elif arg.strip().lower() in ('yes', '1', 'true'): + return True + else: + raise ValueError(f'{arg!r} unknown boolean') + + +def _option_context(arg): + if arg in [None, 'reset', 'close-figs']: + return arg + raise ValueError("Argument should be None or 'reset' or 'close-figs'") + + +def _option_format(arg): + return directives.choice(arg, ('python', 'doctest')) + + +def mark_plot_labels(app, document): + """ + To make plots referenceable, we need to move the reference from the + "htmlonly" (or "latexonly") node to the actual figure node itself. + """ + for name, explicit in document.nametypes.items(): + if not explicit: + continue + labelid = document.nameids[name] + if labelid is None: + continue + node = document.ids[labelid] + if node.tagname in ('html_only', 'latex_only'): + for n in node: + if n.tagname == 'figure': + sectname = name + for c in n: + if c.tagname == 'caption': + sectname = c.astext() + break + + node['ids'].remove(labelid) + node['names'].remove(name) + n['ids'].append(labelid) + n['names'].append(name) + document.settings.env.labels[name] = \ + document.settings.env.docname, labelid, sectname + break + + +class PlotDirective(Directive): + """The ``.. plot::`` directive, as documented in the module's docstring.""" + + has_content = True + required_arguments = 0 + optional_arguments = 2 + final_argument_whitespace = False + option_spec = { + 'alt': directives.unchanged, + 'height': directives.length_or_unitless, + 'width': directives.length_or_percentage_or_unitless, + 'scale': directives.nonnegative_int, + 'align': Image.align, + 'class': directives.class_option, + 'include-source': _option_boolean, + 'show-source-link': _option_boolean, + 'format': _option_format, + 'context': _option_context, + 'nofigs': directives.flag, + 'caption': directives.unchanged, + } + + def run(self): + """Run the plot directive.""" + try: + return run(self.arguments, self.content, self.options, + self.state_machine, self.state, self.lineno) + except Exception as e: + raise self.error(str(e)) + + +def _copy_css_file(app, exc): + if exc is None and app.builder.format == 'html': + src = cbook._get_data_path('plot_directive/plot_directive.css') + dst = app.outdir / Path('_static') + dst.mkdir(exist_ok=True) + # Use copyfile because we do not want to copy src's permissions. + shutil.copyfile(src, dst / Path('plot_directive.css')) + + +def setup(app): + setup.app = app + setup.config = app.config + setup.confdir = app.confdir + app.add_directive('plot', PlotDirective) + app.add_config_value('plot_pre_code', None, True) + app.add_config_value('plot_include_source', False, True) + app.add_config_value('plot_html_show_source_link', True, True) + app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) + app.add_config_value('plot_basedir', None, True) + app.add_config_value('plot_html_show_formats', True, True) + app.add_config_value('plot_rcparams', {}, True) + app.add_config_value('plot_apply_rcparams', False, True) + app.add_config_value('plot_working_directory', None, True) + app.add_config_value('plot_template', None, True) + app.add_config_value('plot_srcset', [], True) + app.connect('doctree-read', mark_plot_labels) + app.add_css_file('plot_directive.css') + app.connect('build-finished', _copy_css_file) + metadata = {'parallel_read_safe': True, 'parallel_write_safe': True, + 'version': matplotlib.__version__} + return metadata + + +# ----------------------------------------------------------------------------- +# Doctest handling +# ----------------------------------------------------------------------------- + + +def contains_doctest(text): + try: + # check if it's valid Python as-is + compile(text, '', 'exec') + return False + except SyntaxError: + pass + r = re.compile(r'^\s*>>>', re.M) + m = r.search(text) + return bool(m) + + +def _split_code_at_show(text, function_name): + """Split code at plt.show().""" + + is_doctest = contains_doctest(text) + if function_name is None: + parts = [] + part = [] + for line in text.split("\n"): + if ((not is_doctest and line.startswith('plt.show(')) or + (is_doctest and line.strip() == '>>> plt.show()')): + part.append(line) + parts.append("\n".join(part)) + part = [] + else: + part.append(line) + if "\n".join(part).strip(): + parts.append("\n".join(part)) + else: + parts = [text] + return is_doctest, parts + + +# ----------------------------------------------------------------------------- +# Template +# ----------------------------------------------------------------------------- + +_SOURCECODE = """ +{{ source_code }} + +.. only:: html + + {% if src_name or (html_show_formats and not multi_image) %} + ( + {%- if src_name -%} + :download:`Source code <{{ build_dir }}/{{ src_name }}>` + {%- endif -%} + {%- if html_show_formats and not multi_image -%} + {%- for img in images -%} + {%- for fmt in img.formats -%} + {%- if src_name or not loop.first -%}, {% endif -%} + :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>` + {%- endfor -%} + {%- endfor -%} + {%- endif -%} + ) + {% endif %} +""" + +TEMPLATE_SRCSET = _SOURCECODE + """ + {% for img in images %} + .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }} + {% for option in options -%} + {{ option }} + {% endfor %} + {%- if caption -%} + {{ caption }} {# appropriate leading whitespace added beforehand #} + {% endif -%} + {%- if srcset -%} + :srcset: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }} + {%- for sr in srcset -%} + , {{ build_dir }}/{{ img.basename }}.{{ sr }}.{{ default_fmt }} {{sr}} + {%- endfor -%} + {% endif %} + + {% if html_show_formats and multi_image %} + ( + {%- for fmt in img.formats -%} + {%- if not loop.first -%}, {% endif -%} + :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>` + {%- endfor -%} + ) + {% endif %} + + + {% endfor %} + +.. only:: not html + + {% for img in images %} + .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.* + {% for option in options -%} + {{ option }} + {% endfor -%} + + {{ caption }} {# appropriate leading whitespace added beforehand #} + {% endfor %} + +""" + +TEMPLATE = _SOURCECODE + """ + + {% for img in images %} + .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }} + {% for option in options -%} + {{ option }} + {% endfor %} + + {% if html_show_formats and multi_image -%} + ( + {%- for fmt in img.formats -%} + {%- if not loop.first -%}, {% endif -%} + :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>` + {%- endfor -%} + ) + {%- endif -%} + + {{ caption }} {# appropriate leading whitespace added beforehand #} + {% endfor %} + +.. only:: not html + + {% for img in images %} + .. figure:: {{ build_dir }}/{{ img.basename }}.* + {% for option in options -%} + {{ option }} + {% endfor -%} + + {{ caption }} {# appropriate leading whitespace added beforehand #} + {% endfor %} + +""" + +exception_template = """ +.. only:: html + + [`source code <%(linkdir)s/%(basename)s.py>`__] + +Exception occurred rendering plot. + +""" + +# the context of the plot for all directives specified with the +# :context: option +plot_context = dict() + + +class ImageFile: + def __init__(self, basename, dirname): + self.basename = basename + self.dirname = dirname + self.formats = [] + + def filename(self, format): + return os.path.join(self.dirname, f"{self.basename}.{format}") + + def filenames(self): + return [self.filename(fmt) for fmt in self.formats] + + +def out_of_date(original, derived, includes=None): + """ + Return whether *derived* is out-of-date relative to *original* or any of + the RST files included in it using the RST include directive (*includes*). + *derived* and *original* are full paths, and *includes* is optionally a + list of full paths which may have been included in the *original*. + """ + if not os.path.exists(derived): + return True + + if includes is None: + includes = [] + files_to_check = [original, *includes] + + def out_of_date_one(original, derived_mtime): + return (os.path.exists(original) and + derived_mtime < os.stat(original).st_mtime) + + derived_mtime = os.stat(derived).st_mtime + return any(out_of_date_one(f, derived_mtime) for f in files_to_check) + + +class PlotError(RuntimeError): + pass + + +def _run_code(code, code_path, ns=None, function_name=None): + """ + Import a Python module from a path, and run the function given by + name, if function_name is not None. + """ + + # Change the working directory to the directory of the example, so + # it can get at its data files, if any. Add its path to sys.path + # so it can import any helper modules sitting beside it. + pwd = os.getcwd() + if setup.config.plot_working_directory is not None: + try: + os.chdir(setup.config.plot_working_directory) + except OSError as err: + raise OSError(f'{err}\n`plot_working_directory` option in ' + f'Sphinx configuration file must be a valid ' + f'directory path') from err + except TypeError as err: + raise TypeError(f'{err}\n`plot_working_directory` option in ' + f'Sphinx configuration file must be a string or ' + f'None') from err + elif code_path is not None: + dirname = os.path.abspath(os.path.dirname(code_path)) + os.chdir(dirname) + + with cbook._setattr_cm( + sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \ + contextlib.redirect_stdout(StringIO()): + try: + if ns is None: + ns = {} + if not ns: + if setup.config.plot_pre_code is None: + exec('import numpy as np\n' + 'from matplotlib import pyplot as plt\n', ns) + else: + exec(str(setup.config.plot_pre_code), ns) + if "__main__" in code: + ns['__name__'] = '__main__' + + # Patch out non-interactive show() to avoid triggering a warning. + with cbook._setattr_cm(FigureManagerBase, show=lambda self: None): + exec(code, ns) + if function_name is not None: + exec(function_name + "()", ns) + + except (Exception, SystemExit) as err: + raise PlotError(traceback.format_exc()) from err + finally: + os.chdir(pwd) + return ns + + +def clear_state(plot_rcparams, close=True): + if close: + plt.close('all') + matplotlib.rc_file_defaults() + matplotlib.rcParams.update(plot_rcparams) + + +def get_plot_formats(config): + default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} + formats = [] + plot_formats = config.plot_formats + for fmt in plot_formats: + if isinstance(fmt, str): + if ':' in fmt: + suffix, dpi = fmt.split(':') + formats.append((str(suffix), int(dpi))) + else: + formats.append((fmt, default_dpi.get(fmt, 80))) + elif isinstance(fmt, (tuple, list)) and len(fmt) == 2: + formats.append((str(fmt[0]), int(fmt[1]))) + else: + raise PlotError('invalid image format "%r" in plot_formats' % fmt) + return formats + + +def _parse_srcset(entries): + """ + Parse srcset for multiples... + """ + srcset = {} + for entry in entries: + entry = entry.strip() + if len(entry) >= 2: + mult = entry[:-1] + srcset[float(mult)] = entry + else: + raise ExtensionError(f'srcset argument {entry!r} is invalid.') + return srcset + + +def render_figures(code, code_path, output_dir, output_base, context, + function_name, config, context_reset=False, + close_figs=False, + code_includes=None): + """ + Run a pyplot script and save the images in *output_dir*. + + Save the images under *output_dir* with file names derived from + *output_base* + """ + + if function_name is not None: + output_base = f'{output_base}_{function_name}' + formats = get_plot_formats(config) + + # Try to determine if all images already exist + + is_doctest, code_pieces = _split_code_at_show(code, function_name) + # Look for single-figure output files first + img = ImageFile(output_base, output_dir) + for format, dpi in formats: + if context or out_of_date(code_path, img.filename(format), + includes=code_includes): + all_exists = False + break + img.formats.append(format) + else: + all_exists = True + + if all_exists: + return [(code, [img])] + + # Then look for multi-figure output files + results = [] + for i, code_piece in enumerate(code_pieces): + images = [] + for j in itertools.count(): + if len(code_pieces) > 1: + img = ImageFile('%s_%02d_%02d' % (output_base, i, j), + output_dir) + else: + img = ImageFile('%s_%02d' % (output_base, j), output_dir) + for fmt, dpi in formats: + if context or out_of_date(code_path, img.filename(fmt), + includes=code_includes): + all_exists = False + break + img.formats.append(fmt) + + # assume that if we have one, we have them all + if not all_exists: + all_exists = (j > 0) + break + images.append(img) + if not all_exists: + break + results.append((code_piece, images)) + else: + all_exists = True + + if all_exists: + return results + + # We didn't find the files, so build them + + results = [] + ns = plot_context if context else {} + + if context_reset: + clear_state(config.plot_rcparams) + plot_context.clear() + + close_figs = not context or close_figs + + for i, code_piece in enumerate(code_pieces): + + if not context or config.plot_apply_rcparams: + clear_state(config.plot_rcparams, close_figs) + elif close_figs: + plt.close('all') + + _run_code(doctest.script_from_examples(code_piece) if is_doctest + else code_piece, + code_path, ns, function_name) + + images = [] + fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() + for j, figman in enumerate(fig_managers): + if len(fig_managers) == 1 and len(code_pieces) == 1: + img = ImageFile(output_base, output_dir) + elif len(code_pieces) == 1: + img = ImageFile("%s_%02d" % (output_base, j), output_dir) + else: + img = ImageFile("%s_%02d_%02d" % (output_base, i, j), + output_dir) + images.append(img) + + for fmt, dpi in formats: + try: + figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi) + if fmt == formats[0][0] and config.plot_srcset: + # save a 2x, 3x etc version of the default... + srcset = _parse_srcset(config.plot_srcset) + for mult, suffix in srcset.items(): + fm = f'{suffix}.{fmt}' + img.formats.append(fm) + figman.canvas.figure.savefig(img.filename(fm), + dpi=int(dpi * mult)) + except Exception as err: + raise PlotError(traceback.format_exc()) from err + img.formats.append(fmt) + + results.append((code_piece, images)) + + if not context or config.plot_apply_rcparams: + clear_state(config.plot_rcparams, close=not context) + + return results + + +def run(arguments, content, options, state_machine, state, lineno): + document = state_machine.document + config = document.settings.env.config + nofigs = 'nofigs' in options + + if config.plot_srcset and setup.app.builder.name == 'singlehtml': + raise ExtensionError( + 'plot_srcset option not compatible with single HTML writer') + + formats = get_plot_formats(config) + default_fmt = formats[0][0] + + options.setdefault('include-source', config.plot_include_source) + options.setdefault('show-source-link', config.plot_html_show_source_link) + + if 'class' in options: + # classes are parsed into a list of string, and output by simply + # printing the list, abusing the fact that RST guarantees to strip + # non-conforming characters + options['class'] = ['plot-directive'] + options['class'] + else: + options.setdefault('class', ['plot-directive']) + keep_context = 'context' in options + context_opt = None if not keep_context else options['context'] + + rst_file = document.attributes['source'] + rst_dir = os.path.dirname(rst_file) + + if len(arguments): + if not config.plot_basedir: + source_file_name = os.path.join(setup.app.builder.srcdir, + directives.uri(arguments[0])) + else: + source_file_name = os.path.join(setup.confdir, config.plot_basedir, + directives.uri(arguments[0])) + # If there is content, it will be passed as a caption. + caption = '\n'.join(content) + + # Enforce unambiguous use of captions. + if "caption" in options: + if caption: + raise ValueError( + 'Caption specified in both content and options.' + ' Please remove ambiguity.' + ) + # Use caption option + caption = options["caption"] + + # If the optional function name is provided, use it + if len(arguments) == 2: + function_name = arguments[1] + else: + function_name = None + + code = Path(source_file_name).read_text(encoding='utf-8') + output_base = os.path.basename(source_file_name) + else: + source_file_name = rst_file + code = textwrap.dedent("\n".join(map(str, content))) + counter = document.attributes.get('_plot_counter', 0) + 1 + document.attributes['_plot_counter'] = counter + base, ext = os.path.splitext(os.path.basename(source_file_name)) + output_base = '%s-%d.py' % (base, counter) + function_name = None + caption = options.get('caption', '') + + base, source_ext = os.path.splitext(output_base) + if source_ext in ('.py', '.rst', '.txt'): + output_base = base + else: + source_ext = '' + + # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames + output_base = output_base.replace('.', '-') + + # is it in doctest format? + is_doctest = contains_doctest(code) + if 'format' in options: + if options['format'] == 'python': + is_doctest = False + else: + is_doctest = True + + # determine output directory name fragment + source_rel_name = relpath(source_file_name, setup.confdir) + source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep) + + # build_dir: where to place output files (temporarily) + build_dir = os.path.join(os.path.dirname(setup.app.doctreedir), + 'plot_directive', + source_rel_dir) + # get rid of .. in paths, also changes pathsep + # see note in Python docs for warning about symbolic links on Windows. + # need to compare source and dest paths at end + build_dir = os.path.normpath(build_dir) + os.makedirs(build_dir, exist_ok=True) + + # how to link to files from the RST file + try: + build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') + except ValueError: + # on Windows, relpath raises ValueError when path and start are on + # different mounts/drives + build_dir_link = build_dir + + # get list of included rst files so that the output is updated when any + # plots in the included files change. These attributes are modified by the + # include directive (see the docutils.parsers.rst.directives.misc module). + try: + source_file_includes = [os.path.join(os.getcwd(), t[0]) + for t in state.document.include_log] + except AttributeError: + # the document.include_log attribute only exists in docutils >=0.17, + # before that we need to inspect the state machine + possible_sources = {os.path.join(setup.confdir, t[0]) + for t in state_machine.input_lines.items} + source_file_includes = [f for f in possible_sources + if os.path.isfile(f)] + # remove the source file itself from the includes + try: + source_file_includes.remove(source_file_name) + except ValueError: + pass + + # save script (if necessary) + if options['show-source-link']: + Path(build_dir, output_base + source_ext).write_text( + doctest.script_from_examples(code) + if source_file_name == rst_file and is_doctest + else code, + encoding='utf-8') + + # make figures + try: + results = render_figures(code=code, + code_path=source_file_name, + output_dir=build_dir, + output_base=output_base, + context=keep_context, + function_name=function_name, + config=config, + context_reset=context_opt == 'reset', + close_figs=context_opt == 'close-figs', + code_includes=source_file_includes) + errors = [] + except PlotError as err: + reporter = state.memo.reporter + sm = reporter.system_message( + 2, "Exception occurred in plotting {}\n from {}:\n{}".format( + output_base, source_file_name, err), + line=lineno) + results = [(code, [])] + errors = [sm] + + # Properly indent the caption + if caption and config.plot_srcset: + caption = ':caption: ' + caption.replace('\n', ' ') + elif caption: + caption = '\n' + '\n'.join(' ' + line.strip() + for line in caption.split('\n')) + # generate output restructuredtext + total_lines = [] + for j, (code_piece, images) in enumerate(results): + if options['include-source']: + if is_doctest: + lines = ['', *code_piece.splitlines()] + else: + lines = ['.. code-block:: python', '', + *textwrap.indent(code_piece, ' ').splitlines()] + source_code = "\n".join(lines) + else: + source_code = "" + + if nofigs: + images = [] + + if 'alt' in options: + options['alt'] = options['alt'].replace('\n', ' ') + + opts = [ + f':{key}: {val}' for key, val in options.items() + if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] + + # Not-None src_name signals the need for a source download in the + # generated html + if j == 0 and options['show-source-link']: + src_name = output_base + source_ext + else: + src_name = None + if config.plot_srcset: + srcset = [*_parse_srcset(config.plot_srcset).values()] + template = TEMPLATE_SRCSET + else: + srcset = None + template = TEMPLATE + + result = jinja2.Template(config.plot_template or template).render( + default_fmt=default_fmt, + build_dir=build_dir_link, + src_name=src_name, + multi_image=len(images) > 1, + options=opts, + srcset=srcset, + images=images, + source_code=source_code, + html_show_formats=config.plot_html_show_formats and len(images), + caption=caption) + total_lines.extend(result.split("\n")) + total_lines.extend("\n") + + if total_lines: + state_machine.insert_input(total_lines, source=source_file_name) + + return errors diff --git a/python_embeded/Lib/site-packages/matplotlib/sphinxext/roles.py b/python_embeded/Lib/site-packages/matplotlib/sphinxext/roles.py new file mode 100644 index 0000000000000000000000000000000000000000..301adcd8a5f5e0b18d28df297ee2025947e5c90d --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/sphinxext/roles.py @@ -0,0 +1,147 @@ +""" +Custom roles for the Matplotlib documentation. + +.. warning:: + + These roles are considered semi-public. They are only intended to be used in + the Matplotlib documentation. + +However, it can happen that downstream packages end up pulling these roles into +their documentation, which will result in documentation build errors. The following +describes the exact mechanism and how to fix the errors. + +There are two ways, Matplotlib docstrings can end up in downstream documentation. +You have to subclass a Matplotlib class and either use the ``:inherited-members:`` +option in your autodoc configuration, or you have to override a method without +specifying a new docstring; the new method will inherit the original docstring and +still render in your autodoc. If the docstring contains one of the custom sphinx +roles, you'll see one of the following error messages: + +.. code-block:: none + + Unknown interpreted text role "mpltype". + Unknown interpreted text role "rc". + +To fix this, you can add this module as extension to your sphinx :file:`conf.py`:: + + extensions = [ + 'matplotlib.sphinxext.roles', + # Other extensions. + ] + +.. warning:: + + Direct use of these roles in other packages is not officially supported. We + reserve the right to modify or remove these roles without prior notification. +""" + +from urllib.parse import urlsplit, urlunsplit + +from docutils import nodes + +import matplotlib +from matplotlib import rcParamsDefault + + +class _QueryReference(nodes.Inline, nodes.TextElement): + """ + Wraps a reference or pending reference to add a query string. + + The query string is generated from the attributes added to this node. + + Also equivalent to a `~docutils.nodes.literal` node. + """ + + def to_query_string(self): + """Generate query string from node attributes.""" + return '&'.join(f'{name}={value}' for name, value in self.attlist()) + + +def _visit_query_reference_node(self, node): + """ + Resolve *node* into query strings on its ``reference`` children. + + Then act as if this is a `~docutils.nodes.literal`. + """ + query = node.to_query_string() + for refnode in node.findall(nodes.reference): + uri = urlsplit(refnode['refuri'])._replace(query=query) + refnode['refuri'] = urlunsplit(uri) + + self.visit_literal(node) + + +def _depart_query_reference_node(self, node): + """ + Act as if this is a `~docutils.nodes.literal`. + """ + self.depart_literal(node) + + +def _rcparam_role(name, rawtext, text, lineno, inliner, options=None, content=None): + """ + Sphinx role ``:rc:`` to highlight and link ``rcParams`` entries. + + Usage: Give the desired ``rcParams`` key as parameter. + + :code:`:rc:`figure.dpi`` will render as: :rc:`figure.dpi` + """ + # Generate a pending cross-reference so that Sphinx will ensure this link + # isn't broken at some point in the future. + title = f'rcParams["{text}"]' + target = 'matplotlibrc-sample' + ref_nodes, messages = inliner.interpreted(title, f'{title} <{target}>', + 'ref', lineno) + + qr = _QueryReference(rawtext, highlight=text) + qr += ref_nodes + node_list = [qr] + + # The default backend would be printed as "agg", but that's not correct (as + # the default is actually determined by fallback). + if text in rcParamsDefault and text != "backend": + node_list.extend([ + nodes.Text(' (default: '), + nodes.literal('', repr(rcParamsDefault[text])), + nodes.Text(')'), + ]) + + return node_list, messages + + +def _mpltype_role(name, rawtext, text, lineno, inliner, options=None, content=None): + """ + Sphinx role ``:mpltype:`` for custom matplotlib types. + + In Matplotlib, there are a number of type-like concepts that do not have a + direct type representation; example: color. This role allows to properly + highlight them in the docs and link to their definition. + + Currently supported values: + + - :code:`:mpltype:`color`` will render as: :mpltype:`color` + + """ + mpltype = text + type_to_link_target = { + 'color': 'colors_def', + } + if mpltype not in type_to_link_target: + raise ValueError(f"Unknown mpltype: {mpltype!r}") + + node_list, messages = inliner.interpreted( + mpltype, f'{mpltype} <{type_to_link_target[mpltype]}>', 'ref', lineno) + return node_list, messages + + +def setup(app): + app.add_role("rc", _rcparam_role) + app.add_role("mpltype", _mpltype_role) + app.add_node( + _QueryReference, + html=(_visit_query_reference_node, _depart_query_reference_node), + latex=(_visit_query_reference_node, _depart_query_reference_node), + text=(_visit_query_reference_node, _depart_query_reference_node), + ) + return {"version": matplotlib.__version__, + "parallel_read_safe": True, "parallel_write_safe": True} diff --git a/python_embeded/Lib/site-packages/matplotlib/style/__init__.py b/python_embeded/Lib/site-packages/matplotlib/style/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..488c6d6ae1ec310cdd84bb209b4103da26fed284 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/style/__init__.py @@ -0,0 +1,4 @@ +from .core import available, context, library, reload_library, use + + +__all__ = ["available", "context", "library", "reload_library", "use"] diff --git a/python_embeded/Lib/site-packages/matplotlib/style/core.py b/python_embeded/Lib/site-packages/matplotlib/style/core.py new file mode 100644 index 0000000000000000000000000000000000000000..e36c3c37a882492afbb71716b4d98a46208bfe55 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/style/core.py @@ -0,0 +1,237 @@ +""" +Core functions and attributes for the matplotlib style library: + +``use`` + Select style sheet to override the current matplotlib settings. +``context`` + Context manager to use a style sheet temporarily. +``available`` + List available style sheets. +``library`` + A dictionary of style names and matplotlib settings. +""" + +import contextlib +import importlib.resources +import logging +import os +from pathlib import Path +import warnings + +import matplotlib as mpl +from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault + +_log = logging.getLogger(__name__) + +__all__ = ['use', 'context', 'available', 'library', 'reload_library'] + + +BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') +# Users may want multiple library paths, so store a list of paths. +USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] +STYLE_EXTENSION = 'mplstyle' +# A list of rcParams that should not be applied from styles +STYLE_BLACKLIST = { + 'interactive', 'backend', 'webagg.port', 'webagg.address', + 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', + 'toolbar', 'timezone', 'figure.max_open_warning', + 'figure.raise_window', 'savefig.directory', 'tk.window_focus', + 'docstring.hardcopy', 'date.epoch'} + + +@_docstring.Substitution( + "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower))) +) +def use(style): + """ + Use Matplotlib style settings from a style specification. + + The style name of 'default' is reserved for reverting back to + the default style settings. + + .. note:: + + This updates the `.rcParams` with the settings from the style. + `.rcParams` not defined in the style are kept. + + Parameters + ---------- + style : str, dict, Path or list + + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + Notes + ----- + The following `.rcParams` are not related to style and will be ignored if + found in a style specification: + + %s + """ + if isinstance(style, (str, Path)) or hasattr(style, 'keys'): + # If name is a single str, Path or dict, make it a single element list. + styles = [style] + else: + styles = style + + style_alias = {'mpl20': 'default', 'mpl15': 'classic'} + + for style in styles: + if isinstance(style, str): + style = style_alias.get(style, style) + if style == "default": + # Deprecation warnings were already handled when creating + # rcParamsDefault, no need to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + # don't trigger RcParams.__getitem__('backend') + style = {k: rcParamsDefault[k] for k in rcParamsDefault + if k not in STYLE_BLACKLIST} + elif style in library: + style = library[style] + elif "." in style: + pkg, _, name = style.rpartition(".") + try: + path = importlib.resources.files(pkg) / f"{name}.{STYLE_EXTENSION}" + style = _rc_params_in_file(path) + except (ModuleNotFoundError, OSError, TypeError) as exc: + # There is an ambiguity whether a dotted name refers to a + # package.style_name or to a dotted file path. Currently, + # we silently try the first form and then the second one; + # in the future, we may consider forcing file paths to + # either use Path objects or be prepended with "./" and use + # the slash as marker for file paths. + pass + if isinstance(style, (str, Path)): + try: + style = _rc_params_in_file(style) + except OSError as err: + raise OSError( + f"{style!r} is not a valid package style, path of style " + f"file, URL of style file, or library style name (library " + f"styles are listed in `style.available`)") from err + filtered = {} + for k in style: # don't trigger RcParams.__getitem__('backend') + if k in STYLE_BLACKLIST: + _api.warn_external( + f"Style includes a parameter, {k!r}, that is not " + f"related to style. Ignoring this parameter.") + else: + filtered[k] = style[k] + mpl.rcParams.update(filtered) + + +@contextlib.contextmanager +def context(style, after_reset=False): + """ + Context manager for using style settings temporarily. + + Parameters + ---------- + style : str, dict, Path or list + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + after_reset : bool + If True, apply style after resetting settings to their defaults; + otherwise, apply style on top of the current settings. + """ + with mpl.rc_context(): + if after_reset: + mpl.rcdefaults() + use(style) + yield + + +def update_user_library(library): + """Update style library with user-defined rc files.""" + for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): + styles = read_style_directory(stylelib_path) + update_nested_dict(library, styles) + return library + + +def read_style_directory(style_dir): + """Return dictionary of styles defined in *style_dir*.""" + styles = dict() + for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"): + with warnings.catch_warnings(record=True) as warns: + styles[path.stem] = _rc_params_in_file(path) + for w in warns: + _log.warning('In %s: %s', path, w.message) + return styles + + +def update_nested_dict(main_dict, new_dict): + """ + Update nested dict (only level of nesting) with new values. + + Unlike `dict.update`, this assumes that the values of the parent dict are + dicts (or dict-like), so you shouldn't replace the nested dict if it + already exists. Instead you should update the sub-dict. + """ + # update named styles specified by user + for name, rc_dict in new_dict.items(): + main_dict.setdefault(name, {}).update(rc_dict) + return main_dict + + +# Load style library +# ================== +_base_library = read_style_directory(BASE_LIBRARY_PATH) +library = {} +available = [] + + +def reload_library(): + """Reload the style library.""" + library.clear() + library.update(update_user_library(_base_library)) + available[:] = sorted(library.keys()) + + +reload_library() diff --git a/python_embeded/Lib/site-packages/matplotlib/style/core.pyi b/python_embeded/Lib/site-packages/matplotlib/style/core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5734b017f7c41ee09908c191d18e8f557ed814a2 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/style/core.pyi @@ -0,0 +1,21 @@ +from collections.abc import Generator +import contextlib + +from matplotlib import RcParams +from matplotlib.typing import RcStyleType + +USER_LIBRARY_PATHS: list[str] = ... +STYLE_EXTENSION: str = ... + +def use(style: RcStyleType) -> None: ... +@contextlib.contextmanager +def context( + style: RcStyleType, after_reset: bool = ... +) -> Generator[None, None, None]: ... + +library: dict[str, RcParams] +available: list[str] + +def reload_library() -> None: ... + +__all__ = ['use', 'context', 'available', 'library', 'reload_library'] diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/__init__.py b/python_embeded/Lib/site-packages/matplotlib/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19113d3996268ca6d3cec637785f7a30da0aae2f --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/__init__.py @@ -0,0 +1,234 @@ +""" +Helper functions for testing. +""" +from pathlib import Path +from tempfile import TemporaryDirectory +import locale +import logging +import os +import subprocess +import sys + +import matplotlib as mpl +from matplotlib import _api + +_log = logging.getLogger(__name__) + + +def set_font_settings_for_testing(): + mpl.rcParams['font.family'] = 'DejaVu Sans' + mpl.rcParams['text.hinting'] = 'none' + mpl.rcParams['text.hinting_factor'] = 8 + + +def set_reproducibility_for_testing(): + mpl.rcParams['svg.hashsalt'] = 'matplotlib' + + +def setup(): + # The baseline images are created in this locale, so we should use + # it during all of the tests. + + try: + locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') + except locale.Error: + try: + locale.setlocale(locale.LC_ALL, 'English_United States.1252') + except locale.Error: + _log.warning( + "Could not set locale to English/United States. " + "Some date-related tests may fail.") + + mpl.use('Agg') + + with _api.suppress_matplotlib_deprecation_warning(): + mpl.rcdefaults() # Start with all defaults + + # These settings *must* be hardcoded for running the comparison tests and + # are not necessarily the default values as specified in rcsetup.py. + set_font_settings_for_testing() + set_reproducibility_for_testing() + + +def subprocess_run_for_testing(command, env=None, timeout=60, stdout=None, + stderr=None, check=False, text=True, + capture_output=False): + """ + Create and run a subprocess. + + Thin wrapper around `subprocess.run`, intended for testing. Will + mark fork() failures on Cygwin as expected failures: not a + success, but not indicating a problem with the code either. + + Parameters + ---------- + args : list of str + env : dict[str, str] + timeout : float + stdout, stderr + check : bool + text : bool + Also called ``universal_newlines`` in subprocess. I chose this + name since the main effect is returning bytes (`False`) vs. str + (`True`), though it also tries to normalize newlines across + platforms. + capture_output : bool + Set stdout and stderr to subprocess.PIPE + + Returns + ------- + proc : subprocess.Popen + + See Also + -------- + subprocess.run + + Raises + ------ + pytest.xfail + If platform is Cygwin and subprocess reports a fork() failure. + """ + if capture_output: + stdout = stderr = subprocess.PIPE + try: + proc = subprocess.run( + command, env=env, + timeout=timeout, check=check, + stdout=stdout, stderr=stderr, + text=text + ) + except BlockingIOError: + if sys.platform == "cygwin": + # Might want to make this more specific + import pytest + pytest.xfail("Fork failure") + raise + return proc + + +def subprocess_run_helper(func, *args, timeout, extra_env=None): + """ + Run a function in a sub-process. + + Parameters + ---------- + func : function + The function to be run. It must be in a module that is importable. + *args : str + Any additional command line arguments to be passed in + the first argument to ``subprocess.run``. + extra_env : dict[str, str] + Any additional environment variables to be set for the subprocess. + """ + target = func.__name__ + module = func.__module__ + file = func.__code__.co_filename + proc = subprocess_run_for_testing( + [ + sys.executable, + "-c", + f"import importlib.util;" + f"_spec = importlib.util.spec_from_file_location({module!r}, {file!r});" + f"_module = importlib.util.module_from_spec(_spec);" + f"_spec.loader.exec_module(_module);" + f"_module.{target}()", + *args + ], + env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})}, + timeout=timeout, check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + return proc + + +def _check_for_pgf(texsystem): + """ + Check if a given TeX system + pgf is available + + Parameters + ---------- + texsystem : str + The executable name to check + """ + with TemporaryDirectory() as tmpdir: + tex_path = Path(tmpdir, "test.tex") + tex_path.write_text(r""" + \documentclass{article} + \usepackage{pgf} + \begin{document} + \typeout{pgfversion=\pgfversion} + \makeatletter + \@@end + """, encoding="utf-8") + try: + subprocess.check_call( + [texsystem, "-halt-on-error", str(tex_path)], cwd=tmpdir, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except (OSError, subprocess.CalledProcessError): + return False + return True + + +def _has_tex_package(package): + try: + mpl.dviread.find_tex_file(f"{package}.sty") + return True + except FileNotFoundError: + return False + + +def ipython_in_subprocess(requested_backend_or_gui_framework, all_expected_backends): + import pytest + IPython = pytest.importorskip("IPython") + + if sys.platform == "win32": + pytest.skip("Cannot change backend running IPython in subprocess on Windows") + + if (IPython.version_info[:3] == (8, 24, 0) and + requested_backend_or_gui_framework == "osx"): + pytest.skip("Bug using macosx backend in IPython 8.24.0 fixed in 8.24.1") + + # This code can be removed when Python 3.12, the latest version supported + # by IPython < 8.24, reaches end-of-life in late 2028. + for min_version, backend in all_expected_backends.items(): + if IPython.version_info[:2] >= min_version: + expected_backend = backend + break + + code = ("import matplotlib as mpl, matplotlib.pyplot as plt;" + "fig, ax=plt.subplots(); ax.plot([1, 3, 2]); mpl.get_backend()") + proc = subprocess_run_for_testing( + [ + "ipython", + "--no-simple-prompt", + f"--matplotlib={requested_backend_or_gui_framework}", + "-c", code, + ], + check=True, + capture_output=True, + ) + + assert proc.stdout.strip().endswith(f"'{expected_backend}'") + + +def is_ci_environment(): + # Common CI variables + ci_environment_variables = [ + 'CI', # Generic CI environment variable + 'CONTINUOUS_INTEGRATION', # Generic CI environment variable + 'TRAVIS', # Travis CI + 'CIRCLECI', # CircleCI + 'JENKINS', # Jenkins + 'GITLAB_CI', # GitLab CI + 'GITHUB_ACTIONS', # GitHub Actions + 'TEAMCITY_VERSION' # TeamCity + # Add other CI environment variables as needed + ] + + for env_var in ci_environment_variables: + if os.getenv(env_var): + return True + + return False diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/__init__.pyi b/python_embeded/Lib/site-packages/matplotlib/testing/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6917b6a5a38080b389f5d970beb8973c1c041206 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/__init__.pyi @@ -0,0 +1,54 @@ +from collections.abc import Callable +import subprocess +from typing import Any, IO, Literal, overload + +def set_font_settings_for_testing() -> None: ... +def set_reproducibility_for_testing() -> None: ... +def setup() -> None: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + *, + text: Literal[True], + capture_output: bool = ..., +) -> subprocess.CompletedProcess[str]: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + text: Literal[False] = ..., + capture_output: bool = ..., +) -> subprocess.CompletedProcess[bytes]: ... +@overload +def subprocess_run_for_testing( + command: list[str], + env: dict[str, str] | None = ..., + timeout: float | None = ..., + stdout: int | IO[Any] | None = ..., + stderr: int | IO[Any] | None = ..., + check: bool = ..., + text: bool = ..., + capture_output: bool = ..., +) -> subprocess.CompletedProcess[bytes] | subprocess.CompletedProcess[str]: ... +def subprocess_run_helper( + func: Callable[[], None], + *args: Any, + timeout: float, + extra_env: dict[str, str] | None = ..., +) -> subprocess.CompletedProcess[str]: ... +def _check_for_pgf(texsystem: str) -> bool: ... +def _has_tex_package(package: str) -> bool: ... +def ipython_in_subprocess( + requested_backend_or_gui_framework: str, + all_expected_backends: dict[tuple[int, int], str], +) -> None: ... +def is_ci_environment() -> bool: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/_markers.py b/python_embeded/Lib/site-packages/matplotlib/testing/_markers.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ef8687a8b39766ba0385b5145b841043251de5 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/_markers.py @@ -0,0 +1,49 @@ +""" +pytest markers for the internal Matplotlib test suite. +""" + +import logging +import shutil + +import pytest + +import matplotlib.testing +import matplotlib.testing.compare +from matplotlib import _get_executable_info, ExecutableNotFoundError + + +_log = logging.getLogger(__name__) + + +def _checkdep_usetex() -> bool: + if not shutil.which("tex"): + _log.warning("usetex mode requires TeX.") + return False + try: + _get_executable_info("dvipng") + except ExecutableNotFoundError: + _log.warning("usetex mode requires dvipng.") + return False + try: + _get_executable_info("gs") + except ExecutableNotFoundError: + _log.warning("usetex mode requires ghostscript.") + return False + return True + + +needs_ghostscript = pytest.mark.skipif( + "eps" not in matplotlib.testing.compare.converter, + reason="This test needs a ghostscript installation") +needs_pgf_lualatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('lualatex'), + reason='lualatex + pgf is required') +needs_pgf_pdflatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('pdflatex'), + reason='pdflatex + pgf is required') +needs_pgf_xelatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('xelatex'), + reason='xelatex + pgf is required') +needs_usetex = pytest.mark.skipif( + not _checkdep_usetex(), + reason="This test needs a TeX installation") diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/compare.py b/python_embeded/Lib/site-packages/matplotlib/testing/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..3aeddcbe2b5e9cf99a665171cf5c58e33fc90497 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/compare.py @@ -0,0 +1,527 @@ +""" +Utilities for comparing image results. +""" + +import atexit +import functools +import hashlib +import logging +import os +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory, TemporaryFile +import weakref +import re + +import numpy as np +from PIL import Image + +import matplotlib as mpl +from matplotlib import cbook +from matplotlib.testing.exceptions import ImageComparisonFailure + +_log = logging.getLogger(__name__) + +__all__ = ['calculate_rms', 'comparable_formats', 'compare_images'] + + +def make_test_filename(fname, purpose): + """ + Make a new filename by inserting *purpose* before the file's extension. + """ + base, ext = os.path.splitext(fname) + return f'{base}-{purpose}{ext}' + + +def _get_cache_path(): + cache_dir = Path(mpl.get_cachedir(), 'test_cache') + cache_dir.mkdir(parents=True, exist_ok=True) + return cache_dir + + +def get_cache_dir(): + return str(_get_cache_path()) + + +def get_file_hash(path, block_size=2 ** 20): + sha256 = hashlib.sha256(usedforsecurity=False) + with open(path, 'rb') as fd: + while True: + data = fd.read(block_size) + if not data: + break + sha256.update(data) + + if Path(path).suffix == '.pdf': + sha256.update(str(mpl._get_executable_info("gs").version).encode('utf-8')) + elif Path(path).suffix == '.svg': + sha256.update(str(mpl._get_executable_info("inkscape").version).encode('utf-8')) + + return sha256.hexdigest() + + +class _ConverterError(Exception): + pass + + +class _Converter: + def __init__(self): + self._proc = None + # Explicitly register deletion from an atexit handler because if we + # wait until the object is GC'd (which occurs later), then some module + # globals (e.g. signal.SIGKILL) has already been set to None, and + # kill() doesn't work anymore... + atexit.register(self.__del__) + + def __del__(self): + if self._proc: + self._proc.kill() + self._proc.wait() + for stream in filter(None, [self._proc.stdin, + self._proc.stdout, + self._proc.stderr]): + stream.close() + self._proc = None + + def _read_until(self, terminator): + """Read until the prompt is reached.""" + buf = bytearray() + while True: + c = self._proc.stdout.read(1) + if not c: + raise _ConverterError(os.fsdecode(bytes(buf))) + buf.extend(c) + if buf.endswith(terminator): + return bytes(buf) + + +class _GSConverter(_Converter): + def __call__(self, orig, dest): + if not self._proc: + self._proc = subprocess.Popen( + [mpl._get_executable_info("gs").executable, + "-dNOSAFER", "-dNOPAUSE", "-dEPSCrop", "-sDEVICE=png16m"], + # As far as I can see, ghostscript never outputs to stderr. + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + self._read_until(b"\nGS") + except _ConverterError as e: + raise OSError(f"Failed to start Ghostscript:\n\n{e.args[0]}") from None + + def encode_and_escape(name): + return (os.fsencode(name) + .replace(b"\\", b"\\\\") + .replace(b"(", br"\(") + .replace(b")", br"\)")) + + self._proc.stdin.write( + b"<< /OutputFile (" + + encode_and_escape(dest) + + b") >> setpagedevice (" + + encode_and_escape(orig) + + b") run flush\n") + self._proc.stdin.flush() + # GS> if nothing left on the stack; GS if n items left on the stack. + err = self._read_until((b"GS<", b"GS>")) + stack = self._read_until(b">") if err.endswith(b"GS<") else b"" + if stack or not os.path.exists(dest): + stack_size = int(stack[:-1]) if stack else 0 + self._proc.stdin.write(b"pop\n" * stack_size) + # Using the systemencoding should at least get the filenames right. + raise ImageComparisonFailure( + (err + stack).decode(sys.getfilesystemencoding(), "replace")) + + +class _SVGConverter(_Converter): + def __call__(self, orig, dest): + old_inkscape = mpl._get_executable_info("inkscape").version.major < 1 + terminator = b"\n>" if old_inkscape else b"> " + if not hasattr(self, "_tmpdir"): + self._tmpdir = TemporaryDirectory() + # On Windows, we must make sure that self._proc has terminated + # (which __del__ does) before clearing _tmpdir. + weakref.finalize(self._tmpdir, self.__del__) + if (not self._proc # First run. + or self._proc.poll() is not None): # Inkscape terminated. + if self._proc is not None and self._proc.poll() is not None: + for stream in filter(None, [self._proc.stdin, + self._proc.stdout, + self._proc.stderr]): + stream.close() + env = { + **os.environ, + # If one passes e.g. a png file to Inkscape, it will try to + # query the user for conversion options via a GUI (even with + # `--without-gui`). Unsetting `DISPLAY` prevents this (and + # causes GTK to crash and Inkscape to terminate, but that'll + # just be reported as a regular exception below). + "DISPLAY": "", + # Do not load any user options. + "INKSCAPE_PROFILE_DIR": self._tmpdir.name, + } + # Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes + # deadlock when stderr is redirected to a pipe, so we redirect it + # to a temporary file instead. This is not necessary anymore as of + # Inkscape 0.92.1. + stderr = TemporaryFile() + self._proc = subprocess.Popen( + ["inkscape", "--without-gui", "--shell"] if old_inkscape else + ["inkscape", "--shell"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, + env=env, cwd=self._tmpdir.name) + # Slight abuse, but makes shutdown handling easier. + self._proc.stderr = stderr + try: + self._read_until(terminator) + except _ConverterError as err: + raise OSError( + "Failed to start Inkscape in interactive mode:\n\n" + + err.args[0]) from err + + # Inkscape's shell mode does not support escaping metacharacters in the + # filename ("\n", and ":;" for inkscape>=1). Avoid any problems by + # running from a temporary directory and using fixed filenames. + inkscape_orig = Path(self._tmpdir.name, os.fsdecode(b"f.svg")) + inkscape_dest = Path(self._tmpdir.name, os.fsdecode(b"f.png")) + try: + inkscape_orig.symlink_to(Path(orig).resolve()) + except OSError: + shutil.copyfile(orig, inkscape_orig) + self._proc.stdin.write( + b"f.svg --export-png=f.png\n" if old_inkscape else + b"file-open:f.svg;export-filename:f.png;export-do;file-close\n") + self._proc.stdin.flush() + try: + self._read_until(terminator) + except _ConverterError as err: + # Inkscape's output is not localized but gtk's is, so the output + # stream probably has a mixed encoding. Using the filesystem + # encoding should at least get the filenames right... + self._proc.stderr.seek(0) + raise ImageComparisonFailure( + self._proc.stderr.read().decode( + sys.getfilesystemencoding(), "replace")) from err + os.remove(inkscape_orig) + shutil.move(inkscape_dest, dest) + + def __del__(self): + super().__del__() + if hasattr(self, "_tmpdir"): + self._tmpdir.cleanup() + + +class _SVGWithMatplotlibFontsConverter(_SVGConverter): + """ + A SVG converter which explicitly adds the fonts shipped by Matplotlib to + Inkspace's font search path, to better support `svg.fonttype = "none"` + (which is in particular used by certain mathtext tests). + """ + + def __call__(self, orig, dest): + if not hasattr(self, "_tmpdir"): + self._tmpdir = TemporaryDirectory() + shutil.copytree(cbook._get_data_path("fonts/ttf"), + Path(self._tmpdir.name, "fonts")) + return super().__call__(orig, dest) + + +def _update_converter(): + try: + mpl._get_executable_info("gs") + except mpl.ExecutableNotFoundError: + pass + else: + converter['pdf'] = converter['eps'] = _GSConverter() + try: + mpl._get_executable_info("inkscape") + except mpl.ExecutableNotFoundError: + pass + else: + converter['svg'] = _SVGConverter() + + +#: A dictionary that maps filename extensions to functions which themselves +#: convert between arguments `old` and `new` (filenames). +converter = {} +_update_converter() +_svg_with_matplotlib_fonts_converter = _SVGWithMatplotlibFontsConverter() + + +def comparable_formats(): + """ + Return the list of file formats that `.compare_images` can compare + on this system. + + Returns + ------- + list of str + E.g. ``['png', 'pdf', 'svg', 'eps']``. + + """ + return ['png', *converter] + + +def convert(filename, cache): + """ + Convert the named file to png; return the name of the created file. + + If *cache* is True, the result of the conversion is cached in + `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a + hash of the exact contents of the input file. Old cache entries are + automatically deleted as needed to keep the size of the cache capped to + twice the size of all baseline images. + """ + path = Path(filename) + if not path.exists(): + raise OSError(f"{path} does not exist") + if path.suffix[1:] not in converter: + import pytest + pytest.skip(f"Don't know how to convert {path.suffix} files to png") + newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png" + + # Only convert the file if the destination doesn't already exist or + # is out of date. + if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime: + cache_dir = _get_cache_path() if cache else None + + if cache_dir is not None: + _register_conversion_cache_cleaner_once() + hash_value = get_file_hash(path) + cached_path = cache_dir / (hash_value + newpath.suffix) + if cached_path.exists(): + _log.debug("For %s: reusing cached conversion.", filename) + shutil.copyfile(cached_path, newpath) + return str(newpath) + + _log.debug("For %s: converting to png.", filename) + convert = converter[path.suffix[1:]] + if path.suffix == ".svg": + contents = path.read_text() + # NOTE: This check should be kept in sync with font styling in + # `lib/matplotlib/backends/backend_svg.py`. If it changes, then be sure to + # re-generate any SVG test files using this mode, or else such tests will + # fail to use the converter for the expected images (but will for the + # results), and the tests will fail strangely. + if re.search( + # searches for attributes : + # style=[font|font-size|font-weight| + # font-family|font-variant|font-style] + # taking care of the possibility of multiple style attributes + # before the font styling (i.e. opacity) + r'style="[^"]*font(|-size|-weight|-family|-variant|-style):', + contents # raw contents of the svg file + ): + # for svg.fonttype = none, we explicitly patch the font search + # path so that fonts shipped by Matplotlib are found. + convert = _svg_with_matplotlib_fonts_converter + convert(path, newpath) + + if cache_dir is not None: + _log.debug("For %s: caching conversion result.", filename) + shutil.copyfile(newpath, cached_path) + + return str(newpath) + + +def _clean_conversion_cache(): + # This will actually ignore mpl_toolkits baseline images, but they're + # relatively small. + baseline_images_size = sum( + path.stat().st_size + for path in Path(mpl.__file__).parent.glob("**/baseline_images/**/*")) + # 2x: one full copy of baselines, and one full copy of test results + # (actually an overestimate: we don't convert png baselines and results). + max_cache_size = 2 * baseline_images_size + # Reduce cache until it fits. + with cbook._lock_path(_get_cache_path()): + cache_stat = { + path: path.stat() for path in _get_cache_path().glob("*")} + cache_size = sum(stat.st_size for stat in cache_stat.values()) + paths_by_atime = sorted( # Oldest at the end. + cache_stat, key=lambda path: cache_stat[path].st_atime, + reverse=True) + while cache_size > max_cache_size: + path = paths_by_atime.pop() + cache_size -= cache_stat[path].st_size + path.unlink() + + +@functools.cache # Ensure this is only registered once. +def _register_conversion_cache_cleaner_once(): + atexit.register(_clean_conversion_cache) + + +def crop_to_same(actual_path, actual_image, expected_path, expected_image): + # clip the images to the same size -- this is useful only when + # comparing eps to pdf + if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf': + aw, ah, ad = actual_image.shape + ew, eh, ed = expected_image.shape + actual_image = actual_image[int(aw / 2 - ew / 2):int( + aw / 2 + ew / 2), int(ah / 2 - eh / 2):int(ah / 2 + eh / 2)] + return actual_image, expected_image + + +def calculate_rms(expected_image, actual_image): + """ + Calculate the per-pixel errors, then compute the root mean square error. + """ + if expected_image.shape != actual_image.shape: + raise ImageComparisonFailure( + f"Image sizes do not match expected size: {expected_image.shape} " + f"actual size {actual_image.shape}") + # Convert to float to avoid overflowing finite integer types. + return np.sqrt(((expected_image - actual_image).astype(float) ** 2).mean()) + + +# NOTE: compare_image and save_diff_image assume that the image does not have +# 16-bit depth, as Pillow converts these to RGB incorrectly. + + +def _load_image(path): + img = Image.open(path) + # In an RGBA image, if the smallest value in the alpha channel is 255, all + # values in it must be 255, meaning that the image is opaque. If so, + # discard the alpha channel so that it may compare equal to an RGB image. + if img.mode != "RGBA" or img.getextrema()[3][0] == 255: + img = img.convert("RGB") + return np.asarray(img) + + +def compare_images(expected, actual, tol, in_decorator=False): + """ + Compare two "image" files checking differences within a tolerance. + + The two given filenames may point to files which are convertible to + PNG via the `.converter` dictionary. The underlying RMS is calculated + with the `.calculate_rms` function. + + Parameters + ---------- + expected : str + The filename of the expected image. + actual : str + The filename of the actual image. + tol : float + The tolerance (a color value difference, where 255 is the + maximal difference). The test fails if the average pixel + difference is greater than this value. + in_decorator : bool + Determines the output format. If called from image_comparison + decorator, this should be True. (default=False) + + Returns + ------- + None or dict or str + Return *None* if the images are equal within the given tolerance. + + If the images differ, the return value depends on *in_decorator*. + If *in_decorator* is true, a dict with the following entries is + returned: + + - *rms*: The RMS of the image difference. + - *expected*: The filename of the expected image. + - *actual*: The filename of the actual image. + - *diff_image*: The filename of the difference image. + - *tol*: The comparison tolerance. + + Otherwise, a human-readable multi-line string representation of this + information is returned. + + Examples + -------- + :: + + img1 = "./baseline/plot.png" + img2 = "./output/plot.png" + compare_images(img1, img2, 0.001) + + """ + actual = os.fspath(actual) + if not os.path.exists(actual): + raise Exception(f"Output image {actual} does not exist.") + if os.stat(actual).st_size == 0: + raise Exception(f"Output image file {actual} is empty.") + + # Convert the image to png + expected = os.fspath(expected) + if not os.path.exists(expected): + raise OSError(f'Baseline image {expected!r} does not exist.') + extension = expected.split('.')[-1] + if extension != 'png': + actual = convert(actual, cache=True) + expected = convert(expected, cache=True) + + # open the image files + expected_image = _load_image(expected) + actual_image = _load_image(actual) + + actual_image, expected_image = crop_to_same( + actual, actual_image, expected, expected_image) + + diff_image = make_test_filename(actual, 'failed-diff') + + if tol <= 0: + if np.array_equal(expected_image, actual_image): + return None + + # convert to signed integers, so that the images can be subtracted without + # overflow + expected_image = expected_image.astype(np.int16) + actual_image = actual_image.astype(np.int16) + + rms = calculate_rms(expected_image, actual_image) + + if rms <= tol: + return None + + save_diff_image(expected, actual, diff_image) + + results = dict(rms=rms, expected=str(expected), + actual=str(actual), diff=str(diff_image), tol=tol) + + if not in_decorator: + # Then the results should be a string suitable for stdout. + template = ['Error: Image files did not match.', + 'RMS Value: {rms}', + 'Expected: \n {expected}', + 'Actual: \n {actual}', + 'Difference:\n {diff}', + 'Tolerance: \n {tol}', ] + results = '\n '.join([line.format(**results) for line in template]) + return results + + +def save_diff_image(expected, actual, output): + """ + Parameters + ---------- + expected : str + File path of expected image. + actual : str + File path of actual image. + output : str + File path to save difference image to. + """ + expected_image = _load_image(expected) + actual_image = _load_image(actual) + actual_image, expected_image = crop_to_same( + actual, actual_image, expected, expected_image) + expected_image = np.array(expected_image, float) + actual_image = np.array(actual_image, float) + if expected_image.shape != actual_image.shape: + raise ImageComparisonFailure( + f"Image sizes do not match expected size: {expected_image.shape} " + f"actual size {actual_image.shape}") + abs_diff = np.abs(expected_image - actual_image) + + # expand differences in luminance domain + abs_diff *= 10 + abs_diff = np.clip(abs_diff, 0, 255).astype(np.uint8) + + if abs_diff.shape[2] == 4: # Hard-code the alpha channel to fully solid + abs_diff[:, :, 3] = 255 + + Image.fromarray(abs_diff).save(output, format="png") diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/compare.pyi b/python_embeded/Lib/site-packages/matplotlib/testing/compare.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f11b3bebc1a0f4186448b1e8d6a8f11f06e3b4f --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/compare.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable +from typing import Literal, overload + +from numpy.typing import NDArray + +__all__ = ["calculate_rms", "comparable_formats", "compare_images"] + +def make_test_filename(fname: str, purpose: str) -> str: ... +def get_cache_dir() -> str: ... +def get_file_hash(path: str, block_size: int = ...) -> str: ... + +converter: dict[str, Callable[[str, str], None]] = {} + +def comparable_formats() -> list[str]: ... +def convert(filename: str, cache: bool) -> str: ... +def crop_to_same( + actual_path: str, actual_image: NDArray, expected_path: str, expected_image: NDArray +) -> tuple[NDArray, NDArray]: ... +def calculate_rms(expected_image: NDArray, actual_image: NDArray) -> float: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: Literal[True] +) -> None | dict[str, float | str]: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: Literal[False] +) -> None | str: ... +@overload +def compare_images( + expected: str, actual: str, tol: float, in_decorator: bool = ... +) -> None | str | dict[str, float | str]: ... +def save_diff_image(expected: str, actual: str, output: str) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/conftest.py b/python_embeded/Lib/site-packages/matplotlib/testing/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..2961e7f02f3f9081f9918f090233281e18db2c2e --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/conftest.py @@ -0,0 +1,178 @@ +import pytest +import sys +import matplotlib +from matplotlib import _api + + +def pytest_configure(config): + # config is initialized here rather than in pytest.ini so that `pytest + # --pyargs matplotlib` (which would not find pytest.ini) works. The only + # entries in pytest.ini set minversion (which is checked earlier), + # testpaths/python_files, as they are required to properly find the tests + for key, value in [ + ("markers", "flaky: (Provided by pytest-rerunfailures.)"), + ("markers", "timeout: (Provided by pytest-timeout.)"), + ("markers", "backend: Set alternate Matplotlib backend temporarily."), + ("markers", "baseline_images: Compare output against references."), + ("markers", "pytz: Tests that require pytz to be installed."), + ("filterwarnings", "error"), + ("filterwarnings", + "ignore:.*The py23 module has been deprecated:DeprecationWarning"), + ("filterwarnings", + r"ignore:DynamicImporter.find_spec\(\) not found; " + r"falling back to find_module\(\):ImportWarning"), + ]: + config.addinivalue_line(key, value) + + matplotlib.use('agg', force=True) + matplotlib._called_from_pytest = True + matplotlib._init_tests() + + +def pytest_unconfigure(config): + matplotlib._called_from_pytest = False + + +@pytest.fixture(autouse=True) +def mpl_test_settings(request): + from matplotlib.testing.decorators import _cleanup_cm + + with _cleanup_cm(): + + backend = None + backend_marker = request.node.get_closest_marker('backend') + prev_backend = matplotlib.get_backend() + if backend_marker is not None: + assert len(backend_marker.args) == 1, \ + "Marker 'backend' must specify 1 backend." + backend, = backend_marker.args + skip_on_importerror = backend_marker.kwargs.get( + 'skip_on_importerror', False) + + # special case Qt backend importing to avoid conflicts + if backend.lower().startswith('qt5'): + if any(sys.modules.get(k) for k in ('PyQt4', 'PySide')): + pytest.skip('Qt4 binding already imported') + + matplotlib.testing.setup() + with _api.suppress_matplotlib_deprecation_warning(): + if backend is not None: + # This import must come after setup() so it doesn't load the + # default backend prematurely. + import matplotlib.pyplot as plt + try: + plt.switch_backend(backend) + except ImportError as exc: + # Should only occur for the cairo backend tests, if neither + # pycairo nor cairocffi are installed. + if 'cairo' in backend.lower() or skip_on_importerror: + pytest.skip("Failed to switch to backend " + f"{backend} ({exc}).") + else: + raise + # Default of cleanup and image_comparison too. + matplotlib.style.use(["classic", "_classic_test_patch"]) + try: + yield + finally: + if backend is not None: + plt.close("all") + matplotlib.use(prev_backend) + + +@pytest.fixture +def pd(): + """ + Fixture to import and configure pandas. Using this fixture, the test is skipped when + pandas is not installed. Use this fixture instead of importing pandas in test files. + + Examples + -------- + Request the pandas fixture by passing in ``pd`` as an argument to the test :: + + def test_matshow_pandas(pd): + + df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6]}) + im = plt.figure().subplots().matshow(df) + np.testing.assert_array_equal(im.get_array(), df) + """ + pd = pytest.importorskip('pandas') + try: + from pandas.plotting import ( + deregister_matplotlib_converters as deregister) + deregister() + except ImportError: + pass + return pd + + +@pytest.fixture +def xr(): + """ + Fixture to import xarray so that the test is skipped when xarray is not installed. + Use this fixture instead of importing xrray in test files. + + Examples + -------- + Request the xarray fixture by passing in ``xr`` as an argument to the test :: + + def test_imshow_xarray(xr): + + ds = xr.DataArray(np.random.randn(2, 3)) + im = plt.figure().subplots().imshow(ds) + np.testing.assert_array_equal(im.get_array(), ds) + """ + + xr = pytest.importorskip('xarray') + return xr + + +@pytest.fixture +def text_placeholders(monkeypatch): + """ + Replace texts with placeholder rectangles. + + The rectangle size only depends on the font size and the number of characters. It is + thus insensitive to font properties and rendering details. This should be used for + tests that depend on text geometries but not the actual text rendering, e.g. layout + tests. + """ + from matplotlib.patches import Rectangle + + def patched_get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi): + """ + Replace ``_get_text_metrics_with_cache`` with fixed results. + + The usual ``renderer.get_text_width_height_descent`` would depend on font + metrics; instead the fixed results are based on font size and the length of the + string only. + """ + # While get_window_extent returns pixels and font size is in points, font size + # includes ascenders and descenders. Leaving out this factor and setting + # descent=0 ends up with a box that is relatively close to DejaVu Sans. + height = fontprop.get_size() + width = len(text) * height / 1.618 # Golden ratio for character size. + descent = 0 + return width, height, descent + + def patched_text_draw(self, renderer): + """ + Replace ``Text.draw`` with a fixed bounding box Rectangle. + + The bounding box corresponds to ``Text.get_window_extent``, which ultimately + depends on the above patched ``_get_text_metrics_with_cache``. + """ + if renderer is not None: + self._renderer = renderer + if not self.get_visible(): + return + if self.get_text() == '': + return + bbox = self.get_window_extent() + rect = Rectangle(bbox.p0, bbox.width, bbox.height, + facecolor=self.get_color(), edgecolor='none') + rect.draw(renderer) + + monkeypatch.setattr('matplotlib.text._get_text_metrics_with_cache', + patched_get_text_metrics_with_cache) + monkeypatch.setattr('matplotlib.text.Text.draw', patched_text_draw) diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/conftest.pyi b/python_embeded/Lib/site-packages/matplotlib/testing/conftest.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f5d90bc88f738244c463b6a070a756ace8c56202 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/conftest.pyi @@ -0,0 +1,14 @@ +from types import ModuleType + +import pytest + +def pytest_configure(config: pytest.Config) -> None: ... +def pytest_unconfigure(config: pytest.Config) -> None: ... +@pytest.fixture +def mpl_test_settings(request: pytest.FixtureRequest) -> None: ... +@pytest.fixture +def pd() -> ModuleType: ... +@pytest.fixture +def xr() -> ModuleType: ... +@pytest.fixture +def text_placeholders(monkeypatch: pytest.MonkeyPatch) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/decorators.py b/python_embeded/Lib/site-packages/matplotlib/testing/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..6f1af7debdb3160b9975b5278d2864e1b79d64e3 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/decorators.py @@ -0,0 +1,464 @@ +import contextlib +import functools +import inspect +import os +from platform import uname +from pathlib import Path +import shutil +import string +import sys +import warnings + +from packaging.version import parse as parse_version + +import matplotlib.style +import matplotlib.units +import matplotlib.testing +from matplotlib import _pylab_helpers, cbook, ft2font, pyplot as plt, ticker +from .compare import comparable_formats, compare_images, make_test_filename +from .exceptions import ImageComparisonFailure + + +@contextlib.contextmanager +def _cleanup_cm(): + orig_units_registry = matplotlib.units.registry.copy() + try: + with warnings.catch_warnings(), matplotlib.rc_context(): + yield + finally: + matplotlib.units.registry.clear() + matplotlib.units.registry.update(orig_units_registry) + plt.close("all") + + +def _check_freetype_version(ver): + if ver is None: + return True + + if isinstance(ver, str): + ver = (ver, ver) + ver = [parse_version(x) for x in ver] + found = parse_version(ft2font.__freetype_version__) + + return ver[0] <= found <= ver[1] + + +def _checked_on_freetype_version(required_freetype_version): + import pytest + return pytest.mark.xfail( + not _check_freetype_version(required_freetype_version), + reason=f"Mismatched version of freetype. " + f"Test requires '{required_freetype_version}', " + f"you have '{ft2font.__freetype_version__}'", + raises=ImageComparisonFailure, strict=False) + + +def remove_ticks_and_titles(figure): + figure.suptitle("") + null_formatter = ticker.NullFormatter() + def remove_ticks(ax): + """Remove ticks in *ax* and all its child Axes.""" + ax.set_title("") + ax.xaxis.set_major_formatter(null_formatter) + ax.xaxis.set_minor_formatter(null_formatter) + ax.yaxis.set_major_formatter(null_formatter) + ax.yaxis.set_minor_formatter(null_formatter) + try: + ax.zaxis.set_major_formatter(null_formatter) + ax.zaxis.set_minor_formatter(null_formatter) + except AttributeError: + pass + for child in ax.child_axes: + remove_ticks(child) + for ax in figure.get_axes(): + remove_ticks(ax) + + +@contextlib.contextmanager +def _collect_new_figures(): + """ + After:: + + with _collect_new_figures() as figs: + some_code() + + the list *figs* contains the figures that have been created during the + execution of ``some_code``, sorted by figure number. + """ + managers = _pylab_helpers.Gcf.figs + preexisting = [manager for manager in managers.values()] + new_figs = [] + try: + yield new_figs + finally: + new_managers = sorted([manager for manager in managers.values() + if manager not in preexisting], + key=lambda manager: manager.num) + new_figs[:] = [manager.canvas.figure for manager in new_managers] + + +def _raise_on_image_difference(expected, actual, tol): + __tracebackhide__ = True + + err = compare_images(expected, actual, tol, in_decorator=True) + if err: + for key in ["actual", "expected", "diff"]: + err[key] = os.path.relpath(err[key]) + raise ImageComparisonFailure( + ('images not close (RMS %(rms).3f):' + '\n\t%(actual)s\n\t%(expected)s\n\t%(diff)s') % err) + + +class _ImageComparisonBase: + """ + Image comparison base class + + This class provides *just* the comparison-related functionality and avoids + any code that would be specific to any testing framework. + """ + + def __init__(self, func, tol, remove_text, savefig_kwargs): + self.func = func + self.baseline_dir, self.result_dir = _image_directories(func) + self.tol = tol + self.remove_text = remove_text + self.savefig_kwargs = savefig_kwargs + + def copy_baseline(self, baseline, extension): + baseline_path = self.baseline_dir / baseline + orig_expected_path = baseline_path.with_suffix(f'.{extension}') + if extension == 'eps' and not orig_expected_path.exists(): + orig_expected_path = orig_expected_path.with_suffix('.pdf') + expected_fname = make_test_filename( + self.result_dir / orig_expected_path.name, 'expected') + try: + # os.symlink errors if the target already exists. + with contextlib.suppress(OSError): + os.remove(expected_fname) + try: + if 'microsoft' in uname().release.lower(): + raise OSError # On WSL, symlink breaks silently + os.symlink(orig_expected_path, expected_fname) + except OSError: # On Windows, symlink *may* be unavailable. + shutil.copyfile(orig_expected_path, expected_fname) + except OSError as err: + raise ImageComparisonFailure( + f"Missing baseline image {expected_fname} because the " + f"following file cannot be accessed: " + f"{orig_expected_path}") from err + return expected_fname + + def compare(self, fig, baseline, extension, *, _lock=False): + __tracebackhide__ = True + + if self.remove_text: + remove_ticks_and_titles(fig) + + actual_path = (self.result_dir / baseline).with_suffix(f'.{extension}') + kwargs = self.savefig_kwargs.copy() + if extension == 'pdf': + kwargs.setdefault('metadata', + {'Creator': None, 'Producer': None, + 'CreationDate': None}) + + lock = (cbook._lock_path(actual_path) + if _lock else contextlib.nullcontext()) + with lock: + try: + fig.savefig(actual_path, **kwargs) + finally: + # Matplotlib has an autouse fixture to close figures, but this + # makes things more convenient for third-party users. + plt.close(fig) + expected_path = self.copy_baseline(baseline, extension) + _raise_on_image_difference(expected_path, actual_path, self.tol) + + +def _pytest_image_comparison(baseline_images, extensions, tol, + freetype_version, remove_text, savefig_kwargs, + style): + """ + Decorate function with image comparison for pytest. + + This function creates a decorator that wraps a figure-generating function + with image comparison code. + """ + import pytest + + KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY + + def decorator(func): + old_sig = inspect.signature(func) + + @functools.wraps(func) + @pytest.mark.parametrize('extension', extensions) + @matplotlib.style.context(style) + @_checked_on_freetype_version(freetype_version) + @functools.wraps(func) + def wrapper(*args, extension, request, **kwargs): + __tracebackhide__ = True + if 'extension' in old_sig.parameters: + kwargs['extension'] = extension + if 'request' in old_sig.parameters: + kwargs['request'] = request + + if extension not in comparable_formats(): + reason = { + 'pdf': 'because Ghostscript is not installed', + 'eps': 'because Ghostscript is not installed', + 'svg': 'because Inkscape is not installed', + }.get(extension, 'on this system') + pytest.skip(f"Cannot compare {extension} files {reason}") + + img = _ImageComparisonBase(func, tol=tol, remove_text=remove_text, + savefig_kwargs=savefig_kwargs) + matplotlib.testing.set_font_settings_for_testing() + + with _collect_new_figures() as figs: + func(*args, **kwargs) + + # If the test is parametrized in any way other than applied via + # this decorator, then we need to use a lock to prevent two + # processes from touching the same output file. + needs_lock = any( + marker.args[0] != 'extension' + for marker in request.node.iter_markers('parametrize')) + + if baseline_images is not None: + our_baseline_images = baseline_images + else: + # Allow baseline image list to be produced on the fly based on + # current parametrization. + our_baseline_images = request.getfixturevalue( + 'baseline_images') + + assert len(figs) == len(our_baseline_images), ( + f"Test generated {len(figs)} images but there are " + f"{len(our_baseline_images)} baseline images") + for fig, baseline in zip(figs, our_baseline_images): + img.compare(fig, baseline, extension, _lock=needs_lock) + + parameters = list(old_sig.parameters.values()) + if 'extension' not in old_sig.parameters: + parameters += [inspect.Parameter('extension', KEYWORD_ONLY)] + if 'request' not in old_sig.parameters: + parameters += [inspect.Parameter("request", KEYWORD_ONLY)] + new_sig = old_sig.replace(parameters=parameters) + wrapper.__signature__ = new_sig + + # Reach a bit into pytest internals to hoist the marks from our wrapped + # function. + new_marks = getattr(func, 'pytestmark', []) + wrapper.pytestmark + wrapper.pytestmark = new_marks + + return wrapper + + return decorator + + +def image_comparison(baseline_images, extensions=None, tol=0, + freetype_version=None, remove_text=False, + savefig_kwarg=None, + # Default of mpl_test_settings fixture and cleanup too. + style=("classic", "_classic_test_patch")): + """ + Compare images generated by the test with those specified in + *baseline_images*, which must correspond, else an `.ImageComparisonFailure` + exception will be raised. + + Parameters + ---------- + baseline_images : list or None + A list of strings specifying the names of the images generated by + calls to `.Figure.savefig`. + + If *None*, the test function must use the ``baseline_images`` fixture, + either as a parameter or with `pytest.mark.usefixtures`. This value is + only allowed when using pytest. + + extensions : None or list of str + The list of extensions to test, e.g. ``['png', 'pdf']``. + + If *None*, defaults to all supported extensions: png, pdf, and svg. + + When testing a single extension, it can be directly included in the + names passed to *baseline_images*. In that case, *extensions* must not + be set. + + In order to keep the size of the test suite from ballooning, we only + include the ``svg`` or ``pdf`` outputs if the test is explicitly + exercising a feature dependent on that backend (see also the + `check_figures_equal` decorator for that purpose). + + tol : float, default: 0 + The RMS threshold above which the test is considered failed. + + Due to expected small differences in floating-point calculations, on + 32-bit systems an additional 0.06 is added to this threshold. + + freetype_version : str or tuple + The expected freetype version or range of versions for this test to + pass. + + remove_text : bool + Remove the title and tick text from the figure before comparison. This + is useful to make the baseline images independent of variations in text + rendering between different versions of FreeType. + + This does not remove other, more deliberate, text, such as legends and + annotations. + + savefig_kwarg : dict + Optional arguments that are passed to the savefig method. + + style : str, dict, or list + The optional style(s) to apply to the image test. The test itself + can also apply additional styles if desired. Defaults to ``["classic", + "_classic_test_patch"]``. + """ + + if baseline_images is not None: + # List of non-empty filename extensions. + baseline_exts = [*filter(None, {Path(baseline).suffix[1:] + for baseline in baseline_images})] + if baseline_exts: + if extensions is not None: + raise ValueError( + "When including extensions directly in 'baseline_images', " + "'extensions' cannot be set as well") + if len(baseline_exts) > 1: + raise ValueError( + "When including extensions directly in 'baseline_images', " + "all baselines must share the same suffix") + extensions = baseline_exts + baseline_images = [ # Chop suffix out from baseline_images. + Path(baseline).stem for baseline in baseline_images] + if extensions is None: + # Default extensions to test, if not set via baseline_images. + extensions = ['png', 'pdf', 'svg'] + if savefig_kwarg is None: + savefig_kwarg = dict() # default no kwargs to savefig + if sys.maxsize <= 2**32: + tol += 0.06 + return _pytest_image_comparison( + baseline_images=baseline_images, extensions=extensions, tol=tol, + freetype_version=freetype_version, remove_text=remove_text, + savefig_kwargs=savefig_kwarg, style=style) + + +def check_figures_equal(*, extensions=("png", "pdf", "svg"), tol=0): + """ + Decorator for test cases that generate and compare two figures. + + The decorated function must take two keyword arguments, *fig_test* + and *fig_ref*, and draw the test and reference images on them. + After the function returns, the figures are saved and compared. + + This decorator should be preferred over `image_comparison` when possible in + order to keep the size of the test suite from ballooning. + + Parameters + ---------- + extensions : list, default: ["png", "pdf", "svg"] + The extensions to test. + tol : float + The RMS threshold above which the test is considered failed. + + Raises + ------ + RuntimeError + If any new figures are created (and not subsequently closed) inside + the test function. + + Examples + -------- + Check that calling `.Axes.plot` with a single argument plots it against + ``[0, 1, 2, ...]``:: + + @check_figures_equal() + def test_plot(fig_test, fig_ref): + fig_test.subplots().plot([1, 3, 5]) + fig_ref.subplots().plot([0, 1, 2], [1, 3, 5]) + + """ + ALLOWED_CHARS = set(string.digits + string.ascii_letters + '_-[]()') + KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY + + def decorator(func): + import pytest + + _, result_dir = _image_directories(func) + old_sig = inspect.signature(func) + + if not {"fig_test", "fig_ref"}.issubset(old_sig.parameters): + raise ValueError("The decorated function must have at least the " + "parameters 'fig_test' and 'fig_ref', but your " + f"function has the signature {old_sig}") + + @pytest.mark.parametrize("ext", extensions) + def wrapper(*args, ext, request, **kwargs): + if 'ext' in old_sig.parameters: + kwargs['ext'] = ext + if 'request' in old_sig.parameters: + kwargs['request'] = request + + file_name = "".join(c for c in request.node.name + if c in ALLOWED_CHARS) + try: + fig_test = plt.figure("test") + fig_ref = plt.figure("reference") + with _collect_new_figures() as figs: + func(*args, fig_test=fig_test, fig_ref=fig_ref, **kwargs) + if figs: + raise RuntimeError('Number of open figures changed during ' + 'test. Make sure you are plotting to ' + 'fig_test or fig_ref, or if this is ' + 'deliberate explicitly close the ' + 'new figure(s) inside the test.') + test_image_path = result_dir / (file_name + "." + ext) + ref_image_path = result_dir / (file_name + "-expected." + ext) + fig_test.savefig(test_image_path) + fig_ref.savefig(ref_image_path) + _raise_on_image_difference( + ref_image_path, test_image_path, tol=tol + ) + finally: + plt.close(fig_test) + plt.close(fig_ref) + + parameters = [ + param + for param in old_sig.parameters.values() + if param.name not in {"fig_test", "fig_ref"} + ] + if 'ext' not in old_sig.parameters: + parameters += [inspect.Parameter("ext", KEYWORD_ONLY)] + if 'request' not in old_sig.parameters: + parameters += [inspect.Parameter("request", KEYWORD_ONLY)] + new_sig = old_sig.replace(parameters=parameters) + wrapper.__signature__ = new_sig + + # reach a bit into pytest internals to hoist the marks from + # our wrapped function + new_marks = getattr(func, "pytestmark", []) + wrapper.pytestmark + wrapper.pytestmark = new_marks + + return wrapper + + return decorator + + +def _image_directories(func): + """ + Compute the baseline and result image directories for testing *func*. + + For test module ``foo.bar.test_baz``, the baseline directory is at + ``foo/bar/baseline_images/test_baz`` and the result directory at + ``$(pwd)/result_images/test_baz``. The result directory is created if it + doesn't exist. + """ + module_path = Path(inspect.getfile(func)) + baseline_dir = module_path.parent / "baseline_images" / module_path.stem + result_dir = Path().resolve() / "result_images" / module_path.stem + result_dir.mkdir(parents=True, exist_ok=True) + return baseline_dir, result_dir diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/decorators.pyi b/python_embeded/Lib/site-packages/matplotlib/testing/decorators.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f1b6c5e595cbca4899cf169a6a85b917ad98bfb4 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/decorators.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +from matplotlib.figure import Figure +from matplotlib.typing import RcStyleType + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def remove_ticks_and_titles(figure: Figure) -> None: ... +def image_comparison( + baseline_images: list[str] | None, + extensions: list[str] | None = ..., + tol: float = ..., + freetype_version: tuple[str, str] | str | None = ..., + remove_text: bool = ..., + savefig_kwarg: dict[str, Any] | None = ..., + style: RcStyleType = ..., +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def check_figures_equal( + *, extensions: Sequence[str] = ..., tol: float = ... +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def _image_directories(func: Callable) -> tuple[Path, Path]: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/exceptions.py b/python_embeded/Lib/site-packages/matplotlib/testing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c39a39207747c75d768ea2dd498dfed364eb88c5 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/exceptions.py @@ -0,0 +1,4 @@ +class ImageComparisonFailure(AssertionError): + """ + Raise this exception to mark a test as a comparison between two images. + """ diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/widgets.py b/python_embeded/Lib/site-packages/matplotlib/testing/widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..3962567aa7c03eb978db53e3d6007446bb177d28 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/widgets.py @@ -0,0 +1,119 @@ +""" +======================== +Widget testing utilities +======================== + +See also :mod:`matplotlib.tests.test_widgets`. +""" + +from unittest import mock + +import matplotlib.pyplot as plt + + +def get_ax(): + """Create a plot and return its Axes.""" + fig, ax = plt.subplots(1, 1) + ax.plot([0, 200], [0, 200]) + ax.set_aspect(1.0) + fig.canvas.draw() + return ax + + +def noop(*args, **kwargs): + pass + + +def mock_event(ax, button=1, xdata=0, ydata=0, key=None, step=1): + r""" + Create a mock event that can stand in for `.Event` and its subclasses. + + This event is intended to be used in tests where it can be passed into + event handling functions. + + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The Axes the event will be in. + xdata : float + x coord of mouse in data coords. + ydata : float + y coord of mouse in data coords. + button : None or `MouseButton` or {'up', 'down'} + The mouse button pressed in this event (see also `.MouseEvent`). + key : None or str + The key pressed when the mouse event triggered (see also `.KeyEvent`). + step : int + Number of scroll steps (positive for 'up', negative for 'down'). + + Returns + ------- + event + A `.Event`\-like Mock instance. + """ + event = mock.Mock() + event.button = button + event.x, event.y = ax.transData.transform([(xdata, ydata), + (xdata, ydata)])[0] + event.xdata, event.ydata = xdata, ydata + event.inaxes = ax + event.canvas = ax.get_figure(root=True).canvas + event.key = key + event.step = step + event.guiEvent = None + event.name = 'Custom' + return event + + +def do_event(tool, etype, button=1, xdata=0, ydata=0, key=None, step=1): + """ + Trigger an event on the given tool. + + Parameters + ---------- + tool : matplotlib.widgets.AxesWidget + etype : str + The event to trigger. + xdata : float + x coord of mouse in data coords. + ydata : float + y coord of mouse in data coords. + button : None or `MouseButton` or {'up', 'down'} + The mouse button pressed in this event (see also `.MouseEvent`). + key : None or str + The key pressed when the mouse event triggered (see also `.KeyEvent`). + step : int + Number of scroll steps (positive for 'up', negative for 'down'). + """ + event = mock_event(tool.ax, button, xdata, ydata, key, step) + func = getattr(tool, etype) + func(event) + + +def click_and_drag(tool, start, end, key=None): + """ + Helper to simulate a mouse drag operation. + + Parameters + ---------- + tool : `~matplotlib.widgets.Widget` + start : [float, float] + Starting point in data coordinates. + end : [float, float] + End point in data coordinates. + key : None or str + An optional key that is pressed during the whole operation + (see also `.KeyEvent`). + """ + if key is not None: + # Press key + do_event(tool, 'on_key_press', xdata=start[0], ydata=start[1], + button=1, key=key) + # Click, move, and release mouse + do_event(tool, 'press', xdata=start[0], ydata=start[1], button=1) + do_event(tool, 'onmove', xdata=end[0], ydata=end[1], button=1) + do_event(tool, 'release', xdata=end[0], ydata=end[1], button=1) + if key is not None: + # Release key + do_event(tool, 'on_key_release', xdata=end[0], ydata=end[1], + button=1, key=key) diff --git a/python_embeded/Lib/site-packages/matplotlib/testing/widgets.pyi b/python_embeded/Lib/site-packages/matplotlib/testing/widgets.pyi new file mode 100644 index 0000000000000000000000000000000000000000..858ff457158283bae9db974e05098890ef5ac260 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/testing/widgets.pyi @@ -0,0 +1,31 @@ +from typing import Any, Literal + +from matplotlib.axes import Axes +from matplotlib.backend_bases import Event, MouseButton +from matplotlib.widgets import AxesWidget, Widget + +def get_ax() -> Axes: ... +def noop(*args: Any, **kwargs: Any) -> None: ... +def mock_event( + ax: Axes, + button: MouseButton | int | Literal["up", "down"] | None = ..., + xdata: float = ..., + ydata: float = ..., + key: str | None = ..., + step: int = ..., +) -> Event: ... +def do_event( + tool: AxesWidget, + etype: str, + button: MouseButton | int | Literal["up", "down"] | None = ..., + xdata: float = ..., + ydata: float = ..., + key: str | None = ..., + step: int = ..., +) -> None: ... +def click_and_drag( + tool: Widget, + start: tuple[float, float], + end: tuple[float, float], + key: str | None = ..., +) -> None: ... diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/__init__.py b/python_embeded/Lib/site-packages/matplotlib/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8cce4fe4558d30d6c71ec7a63e347a0fb9bf7ada --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/__init__.py @@ -0,0 +1,10 @@ +from pathlib import Path + + +# Check that the test directories exist. +if not (Path(__file__).parent / 'baseline_images').exists(): + raise OSError( + 'The baseline image directory does not exist. ' + 'This is most likely because the test data is not installed. ' + 'You may need to install matplotlib from source to get the ' + 'test data.') diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/conftest.py b/python_embeded/Lib/site-packages/matplotlib/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..6afd566750e9de31bd05c37c6e60dde3d7172db7 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/conftest.py @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import ( # noqa + mpl_test_settings, pytest_configure, pytest_unconfigure, pd, text_placeholders, xr) diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/test_afm.py b/python_embeded/Lib/site-packages/matplotlib/tests/test_afm.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c6a83937cd68e3ae20a14d8babb9a99bd5a4f5 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/test_afm.py @@ -0,0 +1,137 @@ +from io import BytesIO +import pytest +import logging + +from matplotlib import _afm +from matplotlib import font_manager as fm + + +# See note in afm.py re: use of comma as decimal separator in the +# UnderlineThickness field and re: use of non-ASCII characters in the Notice +# field. +AFM_TEST_DATA = b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +FontName MyFont-Bold +EncodingScheme FontSpecific +FullName My Font Bold +FamilyName Test Fonts +Weight Bold +ItalicAngle 0.0 +IsFixedPitch false +UnderlinePosition -100 +UnderlineThickness 56,789 +Version 001.000 +Notice Copyright \xa9 2017 No one. +FontBBox 0 -321 1234 369 +StartCharMetrics 3 +C 0 ; WX 250 ; N space ; B 0 0 0 0 ; +C 42 ; WX 1141 ; N foo ; B 40 60 800 360 ; +C 99 ; WX 583 ; N bar ; B 40 -10 543 210 ; +EndCharMetrics +EndFontMetrics +""" + + +def test_nonascii_str(): + # This tests that we also decode bytes as utf-8 properly. + # Else, font files with non ascii characters fail to load. + inp_str = "привет" + byte_str = inp_str.encode("utf8") + + ret = _afm._to_str(byte_str) + assert ret == inp_str + + +def test_parse_header(): + fh = BytesIO(AFM_TEST_DATA) + header = _afm._parse_header(fh) + assert header == { + b'StartFontMetrics': 2.0, + b'FontName': 'MyFont-Bold', + b'EncodingScheme': 'FontSpecific', + b'FullName': 'My Font Bold', + b'FamilyName': 'Test Fonts', + b'Weight': 'Bold', + b'ItalicAngle': 0.0, + b'IsFixedPitch': False, + b'UnderlinePosition': -100, + b'UnderlineThickness': 56.789, + b'Version': '001.000', + b'Notice': b'Copyright \xa9 2017 No one.', + b'FontBBox': [0, -321, 1234, 369], + b'StartCharMetrics': 3, + } + + +def test_parse_char_metrics(): + fh = BytesIO(AFM_TEST_DATA) + _afm._parse_header(fh) # position + metrics = _afm._parse_char_metrics(fh) + assert metrics == ( + {0: (250.0, 'space', [0, 0, 0, 0]), + 42: (1141.0, 'foo', [40, 60, 800, 360]), + 99: (583.0, 'bar', [40, -10, 543, 210]), + }, + {'space': (250.0, 'space', [0, 0, 0, 0]), + 'foo': (1141.0, 'foo', [40, 60, 800, 360]), + 'bar': (583.0, 'bar', [40, -10, 543, 210]), + }) + + +def test_get_familyname_guessed(): + fh = BytesIO(AFM_TEST_DATA) + font = _afm.AFM(fh) + del font._header[b'FamilyName'] # remove FamilyName, so we have to guess + assert font.get_familyname() == 'My Font' + + +def test_font_manager_weight_normalization(): + font = _afm.AFM(BytesIO( + AFM_TEST_DATA.replace(b"Weight Bold\n", b"Weight Custom\n"))) + assert fm.afmFontProperty("", font).weight == "normal" + + +@pytest.mark.parametrize( + "afm_data", + [ + b"""nope +really nope""", + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +FontName MyFont-Bold +EncodingScheme FontSpecific""", + ], +) +def test_bad_afm(afm_data): + fh = BytesIO(afm_data) + with pytest.raises(RuntimeError): + _afm._parse_header(fh) + + +@pytest.mark.parametrize( + "afm_data", + [ + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +Aardvark bob +FontName MyFont-Bold +EncodingScheme FontSpecific +StartCharMetrics 3""", + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +ItalicAngle zero degrees +FontName MyFont-Bold +EncodingScheme FontSpecific +StartCharMetrics 3""", + ], +) +def test_malformed_header(afm_data, caplog): + fh = BytesIO(afm_data) + with caplog.at_level(logging.ERROR): + _afm._parse_header(fh) + + assert len(caplog.records) == 1 diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/test_agg.py b/python_embeded/Lib/site-packages/matplotlib/tests/test_agg.py new file mode 100644 index 0000000000000000000000000000000000000000..59387793605a0fe0f0b609773cf4f0641a3f6191 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/test_agg.py @@ -0,0 +1,340 @@ +import io + +import numpy as np +from numpy.testing import assert_array_almost_equal +from PIL import features, Image, TiffTags +import pytest + + +from matplotlib import ( + collections, patheffects, pyplot as plt, transforms as mtransforms, + rcParams, rc_context) +from matplotlib.backends.backend_agg import RendererAgg +from matplotlib.figure import Figure +from matplotlib.image import imread +from matplotlib.path import Path +from matplotlib.testing.decorators import image_comparison +from matplotlib.transforms import IdentityTransform + + +def test_repeated_save_with_alpha(): + # We want an image which has a background color of bluish green, with an + # alpha of 0.25. + + fig = Figure([1, 0.4]) + fig.set_facecolor((0, 1, 0.4)) + fig.patch.set_alpha(0.25) + + # The target color is fig.patch.get_facecolor() + + buf = io.BytesIO() + + fig.savefig(buf, + facecolor=fig.get_facecolor(), + edgecolor='none') + + # Save the figure again to check that the + # colors don't bleed from the previous renderer. + buf.seek(0) + fig.savefig(buf, + facecolor=fig.get_facecolor(), + edgecolor='none') + + # Check the first pixel has the desired color & alpha + # (approx: 0, 1.0, 0.4, 0.25) + buf.seek(0) + assert_array_almost_equal(tuple(imread(buf)[0, 0]), + (0.0, 1.0, 0.4, 0.250), + decimal=3) + + +def test_large_single_path_collection(): + buff = io.BytesIO() + + # Generates a too-large single path in a path collection that + # would cause a segfault if the draw_markers optimization is + # applied. + f, ax = plt.subplots() + collection = collections.PathCollection( + [Path([[-10, 5], [10, 5], [10, -5], [-10, -5], [-10, 5]])]) + ax.add_artist(collection) + ax.set_xlim(10**-3, 1) + plt.savefig(buff) + + +def test_marker_with_nan(): + # This creates a marker with nans in it, which was segfaulting the + # Agg backend (see #3722) + fig, ax = plt.subplots(1) + steps = 1000 + data = np.arange(steps) + ax.semilogx(data) + ax.fill_between(data, data*0.8, data*1.2) + buf = io.BytesIO() + fig.savefig(buf, format='png') + + +def test_long_path(): + buff = io.BytesIO() + fig = Figure() + ax = fig.subplots() + points = np.ones(100_000) + points[::2] *= -1 + ax.plot(points) + fig.savefig(buff, format='png') + + +@image_comparison(['agg_filter.png'], remove_text=True) +def test_agg_filter(): + def smooth1d(x, window_len): + # copied from https://scipy-cookbook.readthedocs.io/ + s = np.r_[ + 2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]] + w = np.hanning(window_len) + y = np.convolve(w/w.sum(), s, mode='same') + return y[window_len-1:-window_len+1] + + def smooth2d(A, sigma=3): + window_len = max(int(sigma), 3) * 2 + 1 + A = np.apply_along_axis(smooth1d, 0, A, window_len) + A = np.apply_along_axis(smooth1d, 1, A, window_len) + return A + + class BaseFilter: + + def get_pad(self, dpi): + return 0 + + def process_image(self, padded_src, dpi): + raise NotImplementedError("Should be overridden by subclasses") + + def __call__(self, im, dpi): + pad = self.get_pad(dpi) + padded_src = np.pad(im, [(pad, pad), (pad, pad), (0, 0)], + "constant") + tgt_image = self.process_image(padded_src, dpi) + return tgt_image, -pad, -pad + + class OffsetFilter(BaseFilter): + + def __init__(self, offsets=(0, 0)): + self.offsets = offsets + + def get_pad(self, dpi): + return int(max(self.offsets) / 72 * dpi) + + def process_image(self, padded_src, dpi): + ox, oy = self.offsets + a1 = np.roll(padded_src, int(ox / 72 * dpi), axis=1) + a2 = np.roll(a1, -int(oy / 72 * dpi), axis=0) + return a2 + + class GaussianFilter(BaseFilter): + """Simple Gaussian filter.""" + + def __init__(self, sigma, alpha=0.5, color=(0, 0, 0)): + self.sigma = sigma + self.alpha = alpha + self.color = color + + def get_pad(self, dpi): + return int(self.sigma*3 / 72 * dpi) + + def process_image(self, padded_src, dpi): + tgt_image = np.empty_like(padded_src) + tgt_image[:, :, :3] = self.color + tgt_image[:, :, 3] = smooth2d(padded_src[:, :, 3] * self.alpha, + self.sigma / 72 * dpi) + return tgt_image + + class DropShadowFilter(BaseFilter): + + def __init__(self, sigma, alpha=0.3, color=(0, 0, 0), offsets=(0, 0)): + self.gauss_filter = GaussianFilter(sigma, alpha, color) + self.offset_filter = OffsetFilter(offsets) + + def get_pad(self, dpi): + return max(self.gauss_filter.get_pad(dpi), + self.offset_filter.get_pad(dpi)) + + def process_image(self, padded_src, dpi): + t1 = self.gauss_filter.process_image(padded_src, dpi) + t2 = self.offset_filter.process_image(t1, dpi) + return t2 + + fig, ax = plt.subplots() + + # draw lines + line1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", + mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1") + line2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-", + mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1") + + gauss = DropShadowFilter(4) + + for line in [line1, line2]: + + # draw shadows with same lines with slight offset. + xx = line.get_xdata() + yy = line.get_ydata() + shadow, = ax.plot(xx, yy) + shadow.update_from(line) + + # offset transform + transform = mtransforms.offset_copy( + line.get_transform(), fig, x=4.0, y=-6.0, units='points') + shadow.set_transform(transform) + + # adjust zorder of the shadow lines so that it is drawn below the + # original lines + shadow.set_zorder(line.get_zorder() - 0.5) + shadow.set_agg_filter(gauss) + shadow.set_rasterized(True) # to support mixed-mode renderers + + ax.set_xlim(0., 1.) + ax.set_ylim(0., 1.) + + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + +def test_too_large_image(): + fig = plt.figure(figsize=(300, 2**25)) + buff = io.BytesIO() + with pytest.raises(ValueError): + fig.savefig(buff) + + +def test_chunksize(): + x = range(200) + + # Test without chunksize + fig, ax = plt.subplots() + ax.plot(x, np.sin(x)) + fig.canvas.draw() + + # Test with chunksize + fig, ax = plt.subplots() + rcParams['agg.path.chunksize'] = 105 + ax.plot(x, np.sin(x)) + fig.canvas.draw() + + +@pytest.mark.backend('Agg') +def test_jpeg_dpi(): + # Check that dpi is set correctly in jpg files. + plt.plot([0, 1, 2], [0, 1, 0]) + buf = io.BytesIO() + plt.savefig(buf, format="jpg", dpi=200) + im = Image.open(buf) + assert im.info['dpi'] == (200, 200) + + +def test_pil_kwargs_png(): + from PIL.PngImagePlugin import PngInfo + buf = io.BytesIO() + pnginfo = PngInfo() + pnginfo.add_text("Software", "test") + plt.figure().savefig(buf, format="png", pil_kwargs={"pnginfo": pnginfo}) + im = Image.open(buf) + assert im.info["Software"] == "test" + + +def test_pil_kwargs_tiff(): + buf = io.BytesIO() + pil_kwargs = {"description": "test image"} + plt.figure().savefig(buf, format="tiff", pil_kwargs=pil_kwargs) + im = Image.open(buf) + tags = {TiffTags.TAGS_V2[k].name: v for k, v in im.tag_v2.items()} + assert tags["ImageDescription"] == "test image" + + +@pytest.mark.skipif(not features.check("webp"), reason="WebP support not available") +def test_pil_kwargs_webp(): + plt.plot([0, 1, 2], [0, 1, 0]) + buf_small = io.BytesIO() + pil_kwargs_low = {"quality": 1} + plt.savefig(buf_small, format="webp", pil_kwargs=pil_kwargs_low) + assert len(pil_kwargs_low) == 1 + buf_large = io.BytesIO() + pil_kwargs_high = {"quality": 100} + plt.savefig(buf_large, format="webp", pil_kwargs=pil_kwargs_high) + assert len(pil_kwargs_high) == 1 + assert buf_large.getbuffer().nbytes > buf_small.getbuffer().nbytes + + +@pytest.mark.skipif(not features.check("webp"), reason="WebP support not available") +def test_webp_alpha(): + plt.plot([0, 1, 2], [0, 1, 0]) + buf = io.BytesIO() + plt.savefig(buf, format="webp", transparent=True) + im = Image.open(buf) + assert im.mode == "RGBA" + + +def test_draw_path_collection_error_handling(): + fig, ax = plt.subplots() + ax.scatter([1], [1]).set_paths(Path([(0, 1), (2, 3)])) + with pytest.raises(TypeError): + fig.canvas.draw() + + +def test_chunksize_fails(): + # NOTE: This test covers multiple independent test scenarios in a single + # function, because each scenario uses ~2GB of memory and we don't + # want parallel test executors to accidentally run multiple of these + # at the same time. + + N = 100_000 + dpi = 500 + w = 5*dpi + h = 6*dpi + + # make a Path that spans the whole w-h rectangle + x = np.linspace(0, w, N) + y = np.ones(N) * h + y[::2] = 0 + path = Path(np.vstack((x, y)).T) + # effectively disable path simplification (but leaving it "on") + path.simplify_threshold = 0 + + # setup the minimal GraphicsContext to draw a Path + ra = RendererAgg(w, h, dpi) + gc = ra.new_gc() + gc.set_linewidth(1) + gc.set_foreground('r') + + gc.set_hatch('/') + with pytest.raises(OverflowError, match='cannot split hatched path'): + ra.draw_path(gc, path, IdentityTransform()) + gc.set_hatch(None) + + with pytest.raises(OverflowError, match='cannot split filled path'): + ra.draw_path(gc, path, IdentityTransform(), (1, 0, 0)) + + # Set to zero to disable, currently defaults to 0, but let's be sure. + with rc_context({'agg.path.chunksize': 0}): + with pytest.raises(OverflowError, match='Please set'): + ra.draw_path(gc, path, IdentityTransform()) + + # Set big enough that we do not try to chunk. + with rc_context({'agg.path.chunksize': 1_000_000}): + with pytest.raises(OverflowError, match='Please reduce'): + ra.draw_path(gc, path, IdentityTransform()) + + # Small enough we will try to chunk, but big enough we will fail to render. + with rc_context({'agg.path.chunksize': 90_000}): + with pytest.raises(OverflowError, match='Please reduce'): + ra.draw_path(gc, path, IdentityTransform()) + + path.should_simplify = False + with pytest.raises(OverflowError, match="should_simplify is False"): + ra.draw_path(gc, path, IdentityTransform()) + + +def test_non_tuple_rgbaface(): + # This passes rgbaFace as a ndarray to draw_path. + fig = plt.figure() + fig.add_subplot(projection="3d").scatter( + [0, 1, 2], [0, 1, 2], path_effects=[patheffects.Stroke(linewidth=4)]) + fig.canvas.draw() diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/test_agg_filter.py b/python_embeded/Lib/site-packages/matplotlib/tests/test_agg_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8cff6858ae52a85028b4f8b3266b4d1880f687 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/test_agg_filter.py @@ -0,0 +1,33 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison + + +@image_comparison(baseline_images=['agg_filter_alpha'], + extensions=['png', 'pdf']) +def test_agg_filter_alpha(): + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + ax = plt.axes() + x, y = np.mgrid[0:7, 0:8] + data = x**2 - y**2 + mesh = ax.pcolormesh(data, cmap='Reds', zorder=5) + + def manual_alpha(im, dpi): + im[:, :, 3] *= 0.6 + print('CALLED') + return im, 0, 0 + + # Note: Doing alpha like this is not the same as setting alpha on + # the mesh itself. Currently meshes are drawn as independent patches, + # and we see fine borders around the blocks of color. See the SO + # question for an example: https://stackoverflow.com/q/20678817/ + mesh.set_agg_filter(manual_alpha) + + # Currently we must enable rasterization for this to have an effect in + # the PDF backend. + mesh.set_rasterized(True) + + ax.plot([0, 4, 7], [1, 3, 8]) diff --git a/python_embeded/Lib/site-packages/matplotlib/tests/test_animation.py b/python_embeded/Lib/site-packages/matplotlib/tests/test_animation.py new file mode 100644 index 0000000000000000000000000000000000000000..e3382f662c73cb80cf93f949df533b5812bb3981 --- /dev/null +++ b/python_embeded/Lib/site-packages/matplotlib/tests/test_animation.py @@ -0,0 +1,571 @@ +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys +import weakref + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib import pyplot as plt +from matplotlib import animation +from matplotlib.animation import PillowWriter +from matplotlib.testing.decorators import check_figures_equal + + +@pytest.fixture() +def anim(request): + """Create a simple animation (with options).""" + fig, ax = plt.subplots() + line, = ax.plot([], []) + + ax.set_xlim(0, 10) + ax.set_ylim(-1, 1) + + def init(): + line.set_data([], []) + return line, + + def animate(i): + x = np.linspace(0, 10, 100) + y = np.sin(x + i) + line.set_data(x, y) + return line, + + # "klass" can be passed to determine the class returned by the fixture + kwargs = dict(getattr(request, 'param', {})) # make a copy + klass = kwargs.pop('klass', animation.FuncAnimation) + if 'frames' not in kwargs: + kwargs['frames'] = 5 + return klass(fig=fig, func=animate, init_func=init, **kwargs) + + +class NullMovieWriter(animation.AbstractMovieWriter): + """ + A minimal MovieWriter. It doesn't actually write anything. + It just saves the arguments that were given to the setup() and + grab_frame() methods as attributes, and counts how many times + grab_frame() is called. + + This class doesn't have an __init__ method with the appropriate + signature, and it doesn't define an isAvailable() method, so + it cannot be added to the 'writers' registry. + """ + + def setup(self, fig, outfile, dpi, *args): + self.fig = fig + self.outfile = outfile + self.dpi = dpi + self.args = args + self._count = 0 + + def grab_frame(self, **savefig_kwargs): + from matplotlib.animation import _validate_grabframe_kwargs + _validate_grabframe_kwargs(savefig_kwargs) + self.savefig_kwargs = savefig_kwargs + self._count += 1 + + def finish(self): + pass + + +def test_null_movie_writer(anim): + # Test running an animation with NullMovieWriter. + plt.rcParams["savefig.facecolor"] = "auto" + filename = "unused.null" + dpi = 50 + savefig_kwargs = dict(foo=0) + writer = NullMovieWriter() + + anim.save(filename, dpi=dpi, writer=writer, + savefig_kwargs=savefig_kwargs) + + assert writer.fig == plt.figure(1) # The figure used by anim fixture + assert writer.outfile == filename + assert writer.dpi == dpi + assert writer.args == () + # we enrich the savefig kwargs to ensure we composite transparent + # output to an opaque background + for k, v in savefig_kwargs.items(): + assert writer.savefig_kwargs[k] == v + assert writer._count == anim._save_count + + +@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim']) +def test_animation_delete(anim): + if platform.python_implementation() == 'PyPy': + # Something in the test setup fixture lingers around into the test and + # breaks pytest.warns on PyPy. This garbage collection fixes it. + # https://foss.heptapod.net/pypy/pypy/-/issues/3536 + np.testing.break_cycles() + anim = animation.FuncAnimation(**anim) + with pytest.warns(Warning, match='Animation was deleted'): + del anim + np.testing.break_cycles() + + +def test_movie_writer_dpi_default(): + class DummyMovieWriter(animation.MovieWriter): + def _run(self): + pass + + # Test setting up movie writer with figure.dpi default. + fig = plt.figure() + + filename = "unused.null" + fps = 5 + codec = "unused" + bitrate = 1 + extra_args = ["unused"] + + writer = DummyMovieWriter(fps, codec, bitrate, extra_args) + writer.setup(fig, filename) + assert writer.dpi == fig.dpi + + +@animation.writers.register('null') +class RegisteredNullMovieWriter(NullMovieWriter): + + # To be able to add NullMovieWriter to the 'writers' registry, + # we must define an __init__ method with a specific signature, + # and we must define the class method isAvailable(). + # (These methods are not actually required to use an instance + # of this class as the 'writer' argument of Animation.save().) + + def __init__(self, fps=None, codec=None, bitrate=None, + extra_args=None, metadata=None): + pass + + @classmethod + def isAvailable(cls): + return True + + +WRITER_OUTPUT = [ + ('ffmpeg', 'movie.mp4'), + ('ffmpeg_file', 'movie.mp4'), + ('imagemagick', 'movie.gif'), + ('imagemagick_file', 'movie.gif'), + ('pillow', 'movie.gif'), + ('html', 'movie.html'), + ('null', 'movie.null') +] + + +def gen_writers(): + for writer, output in WRITER_OUTPUT: + if not animation.writers.is_available(writer): + mark = pytest.mark.skip( + f"writer '{writer}' not available on this system") + yield pytest.param(writer, None, output, marks=[mark]) + yield pytest.param(writer, None, Path(output), marks=[mark]) + continue + + writer_class = animation.writers[writer] + for frame_format in getattr(writer_class, 'supported_formats', [None]): + yield writer, frame_format, output + yield writer, frame_format, Path(output) + + +# Smoke test for saving animations. In the future, we should probably +# design more sophisticated tests which compare resulting frames a-la +# matplotlib.testing.image_comparison +@pytest.mark.parametrize('writer, frame_format, output', gen_writers()) +@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim']) +def test_save_animation_smoketest(tmpdir, writer, frame_format, output, anim): + if frame_format is not None: + plt.rcParams["animation.frame_format"] = frame_format + anim = animation.FuncAnimation(**anim) + dpi = None + codec = None + if writer == 'ffmpeg': + # Issue #8253 + anim._fig.set_size_inches((10.85, 9.21)) + dpi = 100. + codec = 'h264' + + # Use temporary directory for the file-based writers, which produce a file + # per frame with known names. + with tmpdir.as_cwd(): + anim.save(output, fps=30, writer=writer, bitrate=500, dpi=dpi, + codec=codec) + + del anim + + +@pytest.mark.parametrize('writer, frame_format, output', gen_writers()) +def test_grabframe(tmpdir, writer, frame_format, output): + WriterClass = animation.writers[writer] + + if frame_format is not None: + plt.rcParams["animation.frame_format"] = frame_format + + fig, ax = plt.subplots() + + dpi = None + codec = None + if writer == 'ffmpeg': + # Issue #8253 + fig.set_size_inches((10.85, 9.21)) + dpi = 100. + codec = 'h264' + + test_writer = WriterClass() + # Use temporary directory for the file-based writers, which produce a file + # per frame with known names. + with tmpdir.as_cwd(): + with test_writer.saving(fig, output, dpi): + # smoke test it works + test_writer.grab_frame() + for k in {'dpi', 'bbox_inches', 'format'}: + with pytest.raises( + TypeError, + match=f"grab_frame got an unexpected keyword argument {k!r}" + ): + test_writer.grab_frame(**{k: object()}) + + +@pytest.mark.parametrize('writer', [ + pytest.param( + 'ffmpeg', marks=pytest.mark.skipif( + not animation.FFMpegWriter.isAvailable(), + reason='Requires FFMpeg')), + pytest.param( + 'imagemagick', marks=pytest.mark.skipif( + not animation.ImageMagickWriter.isAvailable(), + reason='Requires ImageMagick')), +]) +@pytest.mark.parametrize('html, want', [ + ('none', None), + ('html5', '