diff --git a/envs/kitoverlay/bin/lsm2bin b/envs/kitoverlay/bin/lsm2bin new file mode 100644 index 0000000000000000000000000000000000000000..f1e7064dbf77f47ca587906eb958cf9c9ac50251 --- /dev/null +++ b/envs/kitoverlay/bin/lsm2bin @@ -0,0 +1,8 @@ +#!/isaac-sim/kit/python/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.lsm2bin import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/envs/kitoverlay/bin/tiff2fsspec b/envs/kitoverlay/bin/tiff2fsspec new file mode 100644 index 0000000000000000000000000000000000000000..6b10b1a70526f68386ad4921f600ac6bbd3aa907 --- /dev/null +++ b/envs/kitoverlay/bin/tiff2fsspec @@ -0,0 +1,8 @@ +#!/isaac-sim/kit/python/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.tiff2fsspec import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/envs/kitoverlay/bin/tiffcomment b/envs/kitoverlay/bin/tiffcomment new file mode 100644 index 0000000000000000000000000000000000000000..410887db8054ad86b883992d1a4c51523275a4a1 --- /dev/null +++ b/envs/kitoverlay/bin/tiffcomment @@ -0,0 +1,8 @@ +#!/isaac-sim/kit/python/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.tiffcomment import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/envs/kitoverlay/bin/tifffile b/envs/kitoverlay/bin/tifffile new file mode 100644 index 0000000000000000000000000000000000000000..1194d04fb3f5ddc72b31af655ae3319c9887ad07 --- /dev/null +++ b/envs/kitoverlay/bin/tifffile @@ -0,0 +1,8 @@ +#!/isaac-sim/kit/python/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/INSTALLER b/envs/kitoverlay/lazy_loader-0.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/METADATA b/envs/kitoverlay/lazy_loader-0.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3b7286076a70900e6bcd98eed147e8032452c9c9 --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/METADATA @@ -0,0 +1,179 @@ +Metadata-Version: 2.4 +Name: lazy-loader +Version: 0.5 +Summary: Makes it easy to load subpackages and functions on demand. +Author: Scientific Python Developers +License-Expression: BSD-3-Clause +Project-URL: Home, https://scientific-python.org/specs/spec-0001/ +Project-URL: Source, https://github.com/scientific-python/lazy-loader +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE.md +Requires-Dist: packaging +Provides-Extra: test +Requires-Dist: pytest>=8.0; extra == "test" +Requires-Dist: pytest-cov>=5.0; extra == "test" +Requires-Dist: coverage[toml]>=7.2; extra == "test" +Provides-Extra: lint +Requires-Dist: pre-commit==4.3.0; extra == "lint" +Provides-Extra: dev +Requires-Dist: changelist==0.5; extra == "dev" +Requires-Dist: spin==0.15; extra == "dev" +Dynamic: license-file + +[![PyPI](https://img.shields.io/pypi/v/lazy-loader)](https://pypi.org/project/lazy-loader/) +[![Test status](https://github.com/scientific-python/lazy-loader/workflows/test/badge.svg?branch=main)](https://github.com/scientific-python/lazy-loader/actions?query=workflow%3A%22test%22) +[![Test coverage](https://codecov.io/gh/scientific-python/lazy-loader/branch/main/graph/badge.svg)](https://app.codecov.io/gh/scientific-python/lazy-loader/branch/main) + +`lazy-loader` makes it easy to load subpackages and functions on demand. + +## Motivation + +1. Allow subpackages to be made visible to users without incurring import costs. +2. Allow external libraries to be imported only when used, improving import times. + +For a more detailed discussion, see [the SPEC](https://scientific-python.org/specs/spec-0001/). + +## Installation + +``` +pip install -U lazy-loader +``` + +We recommend using `lazy-loader` with Python >= 3.11. +If using Python 3.11, please upgrade to 3.11.9 or later. +If using Python 3.12, please upgrade to 3.12.3 or later. +These versions [avoid](https://github.com/python/cpython/pull/114781) a [known race condition](https://github.com/python/cpython/issues/114763). + +## Usage + +### Lazily load subpackages + +Consider the `__init__.py` from [scikit-image](https://scikit-image.org): + +```python +subpackages = [ + ..., + 'filters', + ... +] + +import lazy_loader as lazy +__getattr__, __dir__, _ = lazy.attach(__name__, subpackages) +``` + +You can now do: + +```python +import skimage as ski +ski.filters.gaussian(...) +``` + +The `filters` subpackages will only be loaded once accessed. + +### Lazily load subpackages and functions + +Consider `skimage/filters/__init__.py`: + +```python +from ..util import lazy + +__getattr__, __dir__, __all__ = lazy.attach( + __name__, + submodules=['rank'], + submod_attrs={ + '_gaussian': ['gaussian', 'difference_of_gaussians'], + 'edges': ['sobel', 'scharr', 'prewitt', 'roberts', + 'laplace', 'farid'] + } +) +``` + +The above is equivalent to: + +```python +from . import rank +from ._gaussian import gaussian, difference_of_gaussians +from .edges import (sobel, scharr, prewitt, roberts, + laplace, farid) +``` + +Except that all subpackages (such as `rank`) and functions (such as `sobel`) are loaded upon access. + +### Type checkers + +Static type checkers and IDEs cannot infer type information from +lazily loaded imports. As a workaround you can load [type +stubs](https://mypy.readthedocs.io/en/stable/stubs.html) (`.pyi` +files) with `lazy.attach_stub`: + +```python +import lazy_loader as lazy +__getattr__, __dir__, _ = lazy.attach_stub(__name__, "subpackages.pyi") +``` + +Note that, since imports are now defined in `.pyi` files, those +are not only necessary for type checking but also at runtime. + +The SPEC [describes this workaround in more +detail](https://scientific-python.org/specs/spec-0001/#type-checkers). + +### Early failure + +With lazy loading, missing imports no longer fail upon loading the +library. During development and testing, you can set the `EAGER_IMPORT` +environment variable to "1" or "true" to disable lazy loading ("0" or "" re-enables lazy loading). + +### External libraries + +The `lazy.attach` function discussed above is used to set up package +internal imports. + +Use `lazy.load` to lazily import external libraries: + +```python +sp = lazy.load('scipy') # `sp` will only be loaded when accessed +sp.linalg.norm(...) +``` + +_Note that lazily importing *sub*packages, +i.e. `load('scipy.linalg')` will cause the package containing the +subpackage to be imported immediately; thus, this usage is +discouraged._ + +You can ask `lazy.load` to raise import errors as soon as it is called: + +```python +linalg = lazy.load('scipy.linalg', error_on_import=True) +``` + +#### Optional requirements + +One use for lazy loading is for loading optional dependencies, with +`ImportErrors` only arising when optional functionality is accessed. If optional +functionality depends on a specific version, a version requirement can +be set: + +```python +np = lazy.load("numpy", require="numpy >=1.24") +``` + +In this case, if `numpy` is installed, but the version is less than 1.24, +the `np` module returned will raise an error on attribute access. Using +this feature is not all-or-nothing: One module may rely on one version of +numpy, while another module may not set any requirement. + +_Note that the requirement must use the package [distribution name][] instead +of the module [import name][]. For example, the `pyyaml` distribution provides +the `yaml` module for import._ + +[distribution name]: https://packaging.python.org/en/latest/glossary/#term-Distribution-Package +[import name]: https://packaging.python.org/en/latest/glossary/#term-Import-Package diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/RECORD b/envs/kitoverlay/lazy_loader-0.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..816777b0a3f1cf4dab93c2891fd85e8d8eef97be --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/RECORD @@ -0,0 +1,9 @@ +lazy_loader-0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +lazy_loader-0.5.dist-info/METADATA,sha256=q2XIYmSTfYrAgNX8iV25J_8vlkoHy5L5F2jbFV_Aw3w,5919 +lazy_loader-0.5.dist-info/RECORD,, +lazy_loader-0.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lazy_loader-0.5.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91 +lazy_loader-0.5.dist-info/licenses/LICENSE.md,sha256=eXtpN6T5doNu-7uzrjM9eGbdw-s8sVKXKyvjSNNSk3I,1539 +lazy_loader-0.5.dist-info/top_level.txt,sha256=NYVH9nn-v-w-FAbrgorNRM8g_GoewNbzC_1tptomQTQ,12 +lazy_loader/__init__.py,sha256=kBfn54D_53QrjNJYgsIsk6y5rDU_M3K43Mdqz4Mqzyk,10801 +lazy_loader/__pycache__/__init__.cpython-311.pyc,, diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/REQUESTED b/envs/kitoverlay/lazy_loader-0.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/WHEEL b/envs/kitoverlay/lazy_loader-0.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ef5583317a5e59140e3f1c85c2db91aec0961e8 --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/licenses/LICENSE.md b/envs/kitoverlay/lazy_loader-0.5.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..1008371325090268ee97059d9657ecdf41c3bba5 --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/licenses/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022--2023, Scientific Python project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/envs/kitoverlay/lazy_loader-0.5.dist-info/top_level.txt b/envs/kitoverlay/lazy_loader-0.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..acdf8943eeb3ebb279dd1e024ab7b9d3b084325e --- /dev/null +++ b/envs/kitoverlay/lazy_loader-0.5.dist-info/top_level.txt @@ -0,0 +1 @@ +lazy_loader diff --git a/envs/kitoverlay/skimage/color/__init__.py b/envs/kitoverlay/skimage/color/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00bf7a4652f420ff7f59fafa7cbe4a65b2c1cbd4 --- /dev/null +++ b/envs/kitoverlay/skimage/color/__init__.py @@ -0,0 +1,5 @@ +"""Color space conversion.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/color/__init__.pyi b/envs/kitoverlay/skimage/color/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9f330f3dc49975fea588a9c4f7883c837d3d655c --- /dev/null +++ b/envs/kitoverlay/skimage/color/__init__.pyi @@ -0,0 +1,135 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'convert_colorspace', + 'xyz_tristimulus_values', + 'rgba2rgb', + 'rgb2hsv', + 'hsv2rgb', + 'rgb2xyz', + 'xyz2rgb', + 'rgb2rgbcie', + 'rgbcie2rgb', + 'rgb2gray', + 'gray2rgb', + 'gray2rgba', + 'xyz2lab', + 'lab2xyz', + 'lab2rgb', + 'rgb2lab', + 'rgb2hed', + 'hed2rgb', + 'lab2lch', + 'lch2lab', + 'rgb2yuv', + 'yuv2rgb', + 'rgb2yiq', + 'yiq2rgb', + 'rgb2ypbpr', + 'ypbpr2rgb', + 'rgb2ycbcr', + 'ycbcr2rgb', + 'rgb2ydbdr', + 'ydbdr2rgb', + 'separate_stains', + 'combine_stains', + 'rgb_from_hed', + 'hed_from_rgb', + 'rgb_from_hdx', + 'hdx_from_rgb', + 'rgb_from_fgx', + 'fgx_from_rgb', + 'rgb_from_bex', + 'bex_from_rgb', + 'rgb_from_rbd', + 'rbd_from_rgb', + 'rgb_from_gdx', + 'gdx_from_rgb', + 'rgb_from_hax', + 'hax_from_rgb', + 'rgb_from_bro', + 'bro_from_rgb', + 'rgb_from_bpx', + 'bpx_from_rgb', + 'rgb_from_ahx', + 'ahx_from_rgb', + 'rgb_from_hpx', + 'hpx_from_rgb', + 'color_dict', + 'label2rgb', + 'deltaE_cie76', + 'deltaE_ciede94', + 'deltaE_ciede2000', + 'deltaE_cmc', +] + +from .colorconv import ( + convert_colorspace, + xyz_tristimulus_values, + rgba2rgb, + rgb2hsv, + hsv2rgb, + rgb2xyz, + xyz2rgb, + rgb2rgbcie, + rgbcie2rgb, + rgb2gray, + gray2rgb, + gray2rgba, + xyz2lab, + lab2xyz, + lab2rgb, + rgb2lab, + xyz2luv, + luv2xyz, + luv2rgb, + rgb2luv, + rgb2hed, + hed2rgb, + lab2lch, + lch2lab, + rgb2yuv, + yuv2rgb, + rgb2yiq, + yiq2rgb, + rgb2ypbpr, + ypbpr2rgb, + rgb2ycbcr, + ycbcr2rgb, + rgb2ydbdr, + ydbdr2rgb, + separate_stains, + combine_stains, + rgb_from_hed, + hed_from_rgb, + rgb_from_hdx, + hdx_from_rgb, + rgb_from_fgx, + fgx_from_rgb, + rgb_from_bex, + bex_from_rgb, + rgb_from_rbd, + rbd_from_rgb, + rgb_from_gdx, + gdx_from_rgb, + rgb_from_hax, + hax_from_rgb, + rgb_from_bro, + bro_from_rgb, + rgb_from_bpx, + bpx_from_rgb, + rgb_from_ahx, + ahx_from_rgb, + rgb_from_hpx, + hpx_from_rgb, +) + +from .colorlabel import color_dict, label2rgb +from .delta_e import ( + deltaE_cie76, + deltaE_ciede94, + deltaE_ciede2000, + deltaE_cmc, +) diff --git a/envs/kitoverlay/skimage/color/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb8f4393715ca80de88a7d22f0811c9c813b0a59 Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/__pycache__/adapt_rgb.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/adapt_rgb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2ec1f6aa39dab0d6b105e0ef372f016b90ec66a Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/adapt_rgb.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/__pycache__/colorconv.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/colorconv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e46f547897b43eb893cd6da6158e1eab7a5aa7e3 Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/colorconv.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/__pycache__/colorlabel.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/colorlabel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc725723df738bfad3377f858fd05cf279bc9485 Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/colorlabel.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/__pycache__/delta_e.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/delta_e.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23468017b4f24e5396b607d9a4c31462c682fa9c Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/delta_e.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/__pycache__/rgb_colors.cpython-311.pyc b/envs/kitoverlay/skimage/color/__pycache__/rgb_colors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b37d0a7d8f339dbce3ba7d6a9e297b319a0fea3 Binary files /dev/null and b/envs/kitoverlay/skimage/color/__pycache__/rgb_colors.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/color/adapt_rgb.py b/envs/kitoverlay/skimage/color/adapt_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..5d7a553b3f605c91182547f13dbfd9cbdcaa5cb2 --- /dev/null +++ b/envs/kitoverlay/skimage/color/adapt_rgb.py @@ -0,0 +1,81 @@ +import functools + +import numpy as np + +from .. import color +from ..util.dtype import _convert + + +__all__ = ['adapt_rgb', 'hsv_value', 'each_channel'] + + +def is_rgb_like(image, channel_axis=-1): + """Return True if the image *looks* like it's RGB. + + This function should not be public because it is only intended to be used + for functions that don't accept volumes as input, since checking an image's + shape is fragile. + """ + return (image.ndim == 3) and (image.shape[channel_axis] in (3, 4)) + + +def adapt_rgb(apply_to_rgb): + """Return decorator that adapts to RGB images to a gray-scale filter. + + This function is only intended to be used for functions that don't accept + volumes as input, since checking an image's shape is fragile. + + Parameters + ---------- + apply_to_rgb : function + Function that returns a filtered image from an image-filter and RGB + image. This will only be called if the image is RGB-like. + """ + + def decorator(image_filter): + @functools.wraps(image_filter) + def image_filter_adapted(image, *args, **kwargs): + if is_rgb_like(image): + return apply_to_rgb(image_filter, image, *args, **kwargs) + else: + return image_filter(image, *args, **kwargs) + + return image_filter_adapted + + return decorator + + +def hsv_value(image_filter, image, *args, **kwargs): + """Return color image by applying `image_filter` on HSV-value of `image`. + + Note that this function is intended for use with `adapt_rgb`. + + Parameters + ---------- + image_filter : function + Function that filters a gray-scale image. + image : array + Input image. Note that RGBA images are treated as RGB. + """ + # Slice the first three channels so that we remove any alpha channels. + hsv = color.rgb2hsv(image[:, :, :3]) + value = hsv[:, :, 2].copy() + value = image_filter(value, *args, **kwargs) + hsv[:, :, 2] = _convert(value, hsv.dtype) + return color.hsv2rgb(hsv) + + +def each_channel(image_filter, image, *args, **kwargs): + """Return color image by applying `image_filter` on channels of `image`. + + Note that this function is intended for use with `adapt_rgb`. + + Parameters + ---------- + image_filter : function + Function that filters a gray-scale image. + image : array + Input image. + """ + c_new = [image_filter(c, *args, **kwargs) for c in np.moveaxis(image, -1, 0)] + return np.stack(c_new, axis=-1) diff --git a/envs/kitoverlay/skimage/color/colorconv.py b/envs/kitoverlay/skimage/color/colorconv.py new file mode 100644 index 0000000000000000000000000000000000000000..58e5642a37b84bdfca8294de188694af393417fe --- /dev/null +++ b/envs/kitoverlay/skimage/color/colorconv.py @@ -0,0 +1,2314 @@ +"""Functions for converting between color spaces. + +The "central" color space in this module is RGB, more specifically the linear +sRGB color space using D65 as a white-point [1]_. This represents a +standard monitor (w/o gamma correction). For a good FAQ on color spaces see +[2]_. + +The API consists of functions to convert to and from RGB as defined above, as +well as a generic function to convert to and from any supported color space +(which is done through RGB in most cases). + + +Supported color spaces +---------------------- +* RGB : Red Green Blue. + Here the sRGB standard [1]_. +* HSV : Hue, Saturation, Value. + Uniquely defined when related to sRGB [3]_. +* RGB CIE : Red Green Blue. + The original RGB CIE standard from 1931 [4]_. Primary colors are 700 nm + (red), 546.1 nm (blue) and 435.8 nm (green). +* XYZ CIE : XYZ + Derived from the RGB CIE color space. Chosen such that + ``x == y == z == 1/3`` at the whitepoint, and all color matching + functions are greater than zero everywhere. +* LAB CIE : Lightness, a, b + Colorspace derived from XYZ CIE that is intended to be more + perceptually uniform +* LUV CIE : Lightness, u, v + Colorspace derived from XYZ CIE that is intended to be more + perceptually uniform +* LCH CIE : Lightness, Chroma, Hue + Defined in terms of LAB CIE. C and H are the polar representation of + a and b. The polar angle C is defined to be on ``(0, 2*pi)`` + +:author: Nicolas Pinto (rgb2hsv) +:author: Ralf Gommers (hsv2rgb) +:author: Travis Oliphant (XYZ and RGB CIE functions) +:author: Matt Terry (lab2lch) +:author: Alex Izvorski (yuv2rgb, rgb2yuv and related) + +:license: modified BSD + +References +---------- +.. [1] Official specification of sRGB, IEC 61966-2-1:1999. +.. [2] http://www.poynton.com/ColorFAQ.html +.. [3] https://en.wikipedia.org/wiki/HSL_and_HSV +.. [4] https://en.wikipedia.org/wiki/CIE_1931_color_space +""" + +from warnings import warn + +import numpy as np +from scipy import linalg + + +from .._shared.utils import ( + _supported_float_type, + channel_as_last_axis, + identity, + reshape_nd, + slice_at_axis, +) +from ..util import dtype, dtype_limits + +# TODO: when minimum numpy dependency is 1.25 use: +# np..exceptions.AxisError instead of AxisError +# and remove this try-except +try: + from numpy import AxisError +except ImportError: + from numpy.exceptions import AxisError + + +def convert_colorspace(arr, fromspace, tospace, *, channel_axis=-1): + """Convert an image array to a new color space. + + Valid color spaces are: + 'RGB', 'HSV', 'RGB CIE', 'XYZ', 'YUV', 'YIQ', 'YPbPr', 'YCbCr', 'YDbDr' + + Parameters + ---------- + arr : (..., C=3, ...) array_like + The image to convert. By default, the final dimension denotes + channels. + fromspace : str + The color space to convert from. Can be specified in lower case. + tospace : str + The color space to convert to. Can be specified in lower case. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The converted image. Same dimensions as input. + + Raises + ------ + ValueError + If fromspace is not a valid color space + ValueError + If tospace is not a valid color space + + Notes + ----- + Conversion is performed through the "central" RGB color space, + i.e. conversion from XYZ to HSV is implemented as ``XYZ -> RGB -> HSV`` + instead of directly. + + Examples + -------- + >>> from skimage import data + >>> img = data.astronaut() + >>> img_hsv = convert_colorspace(img, 'RGB', 'HSV') + """ + fromdict = { + 'rgb': identity, + 'hsv': hsv2rgb, + 'rgb cie': rgbcie2rgb, + 'xyz': xyz2rgb, + 'yuv': yuv2rgb, + 'yiq': yiq2rgb, + 'ypbpr': ypbpr2rgb, + 'ycbcr': ycbcr2rgb, + 'ydbdr': ydbdr2rgb, + } + todict = { + 'rgb': identity, + 'hsv': rgb2hsv, + 'rgb cie': rgb2rgbcie, + 'xyz': rgb2xyz, + 'yuv': rgb2yuv, + 'yiq': rgb2yiq, + 'ypbpr': rgb2ypbpr, + 'ycbcr': rgb2ycbcr, + 'ydbdr': rgb2ydbdr, + } + + fromspace = fromspace.lower() + tospace = tospace.lower() + if fromspace not in fromdict: + msg = f'`fromspace` has to be one of {fromdict.keys()}' + raise ValueError(msg) + if tospace not in todict: + msg = f'`tospace` has to be one of {todict.keys()}' + raise ValueError(msg) + + return todict[tospace]( + fromdict[fromspace](arr, channel_axis=channel_axis), channel_axis=channel_axis + ) + + +def _prepare_colorarray(arr, force_copy=False, *, channel_axis=-1): + """Check the shape of the array and convert it to + floating point representation. + """ + arr = np.asanyarray(arr) + + if arr.shape[channel_axis] != 3: + msg = ( + f'the input array must have size 3 along `channel_axis`, ' + f'got {arr.shape}' + ) + raise ValueError(msg) + + float_dtype = _supported_float_type(arr.dtype) + if float_dtype == np.float32: + _func = dtype.img_as_float32 + else: + _func = dtype.img_as_float64 + return _func(arr, force_copy=force_copy) + + +def _validate_channel_axis(channel_axis, ndim): + if not isinstance(channel_axis, int): + raise TypeError("channel_axis must be an integer") + if channel_axis < -ndim or channel_axis >= ndim: + raise AxisError("channel_axis exceeds array dimensions") + + +def rgba2rgb(rgba, background=(1, 1, 1), *, channel_axis=-1): + """RGBA to RGB conversion using alpha blending [1]_. + + Parameters + ---------- + rgba : (..., C=4, ...) array_like + The image in RGBA format. By default, the final dimension denotes + channels. + background : array_like + The color of the background to blend the image with (3 floats + between 0 to 1 - the RGB value of the background). + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgba` is not at least 2D with shape (..., 4, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending + + Examples + -------- + >>> from skimage import color + >>> from skimage import data + >>> img_rgba = data.logo() + >>> img_rgb = color.rgba2rgb(img_rgba) + """ + arr = np.asanyarray(rgba) + _validate_channel_axis(channel_axis, arr.ndim) + channel_axis = channel_axis % arr.ndim + + if arr.shape[channel_axis] != 4: + msg = ( + f'the input array must have size 4 along `channel_axis`, ' + f'got {arr.shape}' + ) + raise ValueError(msg) + + float_dtype = _supported_float_type(arr.dtype) + if float_dtype == np.float32: + arr = dtype.img_as_float32(arr) + else: + arr = dtype.img_as_float64(arr) + + background = np.ravel(background).astype(arr.dtype) + if len(background) != 3: + raise ValueError( + 'background must be an array-like containing 3 RGB ' + f'values. Got {len(background)} items' + ) + if np.any(background < 0) or np.any(background > 1): + raise ValueError('background RGB values must be floats between ' '0 and 1.') + # reshape background for broadcasting along non-channel axes + background = reshape_nd(background, arr.ndim, channel_axis) + + alpha = arr[slice_at_axis(slice(3, 4), axis=channel_axis)] + channels = arr[slice_at_axis(slice(3), axis=channel_axis)] + out = np.clip((1 - alpha) * background + alpha * channels, a_min=0, a_max=1) + return out + + +@channel_as_last_axis() +def rgb2hsv(rgb, *, channel_axis=-1): + """RGB to HSV color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in HSV format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Conversion between RGB and HSV color spaces results in some loss of + precision, due to integer arithmetic and rounding [1]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/HSL_and_HSV + + Examples + -------- + >>> from skimage import color + >>> from skimage import data + >>> img = data.astronaut() + >>> img_hsv = color.rgb2hsv(img) + """ + input_is_one_pixel = rgb.ndim == 1 + if input_is_one_pixel: + rgb = rgb[np.newaxis, ...] + + arr = _prepare_colorarray(rgb, channel_axis=-1) + out = np.empty_like(arr) + + # -- V channel + out_v = arr.max(-1) + + # -- S channel + delta = np.ptp(arr, axis=-1) + # Ignore warning for zero divided by zero + old_settings = np.seterr(invalid='ignore') + out_s = delta / out_v + out_s[delta == 0.0] = 0.0 + + # -- H channel + # red is max + idx = arr[..., 0] == out_v + out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx] + + # green is max + idx = arr[..., 1] == out_v + out[idx, 0] = 2.0 + (arr[idx, 2] - arr[idx, 0]) / delta[idx] + + # blue is max + idx = arr[..., 2] == out_v + out[idx, 0] = 4.0 + (arr[idx, 0] - arr[idx, 1]) / delta[idx] + out_h = (out[..., 0] / 6.0) % 1.0 + out_h[delta == 0.0] = 0.0 + + np.seterr(**old_settings) + + # -- output + out[..., 0] = out_h + out[..., 1] = out_s + out[..., 2] = out_v + + # # remove NaN + out[np.isnan(out)] = 0 + + if input_is_one_pixel: + out = np.squeeze(out, axis=0) + + return out + + +@channel_as_last_axis() +def hsv2rgb(hsv, *, channel_axis=-1): + """HSV to RGB color space conversion. + + Parameters + ---------- + hsv : (..., C=3, ...) array_like + The image in HSV format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `hsv` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Conversion between RGB and HSV color spaces results in some loss of + precision, due to integer arithmetic and rounding [1]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/HSL_and_HSV + + Examples + -------- + >>> from skimage import data + >>> img = data.astronaut() + >>> img_hsv = rgb2hsv(img) + >>> img_rgb = hsv2rgb(img_hsv) + """ + arr = _prepare_colorarray(hsv, channel_axis=-1) + + hi = np.floor(arr[..., 0] * 6) + f = arr[..., 0] * 6 - hi + p = arr[..., 2] * (1 - arr[..., 1]) + q = arr[..., 2] * (1 - f * arr[..., 1]) + t = arr[..., 2] * (1 - (1 - f) * arr[..., 1]) + v = arr[..., 2] + + hi = np.stack([hi, hi, hi], axis=-1).astype(np.uint8) % 6 + out = np.choose( + hi, + np.stack( + [ + np.stack((v, t, p), axis=-1), + np.stack((q, v, p), axis=-1), + np.stack((p, v, t), axis=-1), + np.stack((p, q, v), axis=-1), + np.stack((t, p, v), axis=-1), + np.stack((v, p, q), axis=-1), + ] + ), + ) + + return out + + +# --------------------------------------------------------------- +# Primaries for the coordinate systems +# --------------------------------------------------------------- +cie_primaries = np.array([700, 546.1, 435.8]) +sb_primaries = np.array([1.0 / 155, 1.0 / 190, 1.0 / 225]) * 1e5 + +# --------------------------------------------------------------- +# Matrices that define conversion between different color spaces +# --------------------------------------------------------------- + +# From sRGB specification +xyz_from_rgb = np.array( + [ + [0.412453, 0.357580, 0.180423], + [0.212671, 0.715160, 0.072169], + [0.019334, 0.119193, 0.950227], + ] +) + +rgb_from_xyz = linalg.inv(xyz_from_rgb) + +# From https://en.wikipedia.org/wiki/CIE_1931_color_space +# Note: Travis's code did not have the divide by 0.17697 +xyz_from_rgbcie = ( + np.array([[0.49, 0.31, 0.20], [0.17697, 0.81240, 0.01063], [0.00, 0.01, 0.99]]) + / 0.17697 +) + +rgbcie_from_xyz = linalg.inv(xyz_from_rgbcie) + +# construct matrices to and from rgb: +rgbcie_from_rgb = rgbcie_from_xyz @ xyz_from_rgb +rgb_from_rgbcie = rgb_from_xyz @ xyz_from_rgbcie + + +gray_from_rgb = np.array([[0.2125, 0.7154, 0.0721], [0, 0, 0], [0, 0, 0]]) + +yuv_from_rgb = np.array( + [ + [0.299, 0.587, 0.114], + [-0.14714119, -0.28886916, 0.43601035], + [0.61497538, -0.51496512, -0.10001026], + ] +) + +rgb_from_yuv = linalg.inv(yuv_from_rgb) + +yiq_from_rgb = np.array( + [ + [0.299, 0.587, 0.114], + [0.59590059, -0.27455667, -0.32134392], + [0.21153661, -0.52273617, 0.31119955], + ] +) + +rgb_from_yiq = linalg.inv(yiq_from_rgb) + +ypbpr_from_rgb = np.array( + [[0.299, 0.587, 0.114], [-0.168736, -0.331264, 0.5], [0.5, -0.418688, -0.081312]] +) + +rgb_from_ypbpr = linalg.inv(ypbpr_from_rgb) + +ycbcr_from_rgb = np.array( + [[65.481, 128.553, 24.966], [-37.797, -74.203, 112.0], [112.0, -93.786, -18.214]] +) + +rgb_from_ycbcr = linalg.inv(ycbcr_from_rgb) + +ydbdr_from_rgb = np.array( + [[0.299, 0.587, 0.114], [-0.45, -0.883, 1.333], [-1.333, 1.116, 0.217]] +) + +rgb_from_ydbdr = linalg.inv(ydbdr_from_rgb) + + +# CIE LAB constants for Observer=2A, Illuminant=D65 +# NOTE: this is actually the XYZ values for the illuminant above. +lab_ref_white = np.array([0.95047, 1.0, 1.08883]) + +# CIE XYZ tristimulus values of the illuminants, scaled to [0, 1]. For each illuminant I +# we have: +# +# illuminant[I]['2'] corresponds to the CIE XYZ tristimulus values for the 2 degree +# field of view. +# +# illuminant[I]['10'] corresponds to the CIE XYZ tristimulus values for the 10 degree +# field of view. +# +# illuminant[I]['R'] corresponds to the CIE XYZ tristimulus values for R illuminants +# in grDevices::convertColor +# +# The CIE XYZ tristimulus values are calculated from [1], using the formula: +# +# X = x * ( Y / y ) +# Y = Y +# Z = ( 1 - x - y ) * ( Y / y ) +# +# where Y = 1. The only exception is the illuminant "D65" with aperture angle +# 2, whose coordinates are copied from 'lab_ref_white' for +# backward-compatibility reasons. +# +# References +# ---------- +# .. [1] https://en.wikipedia.org/wiki/Standard_illuminant + +_illuminants = { + "A": { + '2': (1.098466069456375, 1, 0.3558228003436005), + '10': (1.111420406956693, 1, 0.3519978321919493), + 'R': (1.098466069456375, 1, 0.3558228003436005), + }, + "B": { + '2': (0.9909274480248003, 1, 0.8531327322886154), + '10': (0.9917777147717607, 1, 0.8434930535866175), + 'R': (0.9909274480248003, 1, 0.8531327322886154), + }, + "C": { + '2': (0.980705971659919, 1, 1.1822494939271255), + '10': (0.9728569189782166, 1, 1.1614480488951577), + 'R': (0.980705971659919, 1, 1.1822494939271255), + }, + "D50": { + '2': (0.9642119944211994, 1, 0.8251882845188288), + '10': (0.9672062750333777, 1, 0.8142801513128616), + 'R': (0.9639501491621826, 1, 0.8241280285499208), + }, + "D55": { + '2': (0.956797052643698, 1, 0.9214805860173273), + '10': (0.9579665682254781, 1, 0.9092525159847462), + 'R': (0.9565317453467969, 1, 0.9202554587037198), + }, + "D65": { + '2': (0.95047, 1.0, 1.08883), # This was: `lab_ref_white` + '10': (0.94809667673716, 1, 1.0730513595166162), + 'R': (0.9532057125493769, 1, 1.0853843816469158), + }, + "D75": { + '2': (0.9497220898840717, 1, 1.226393520724154), + '10': (0.9441713925645873, 1, 1.2064272211720228), + 'R': (0.9497220898840717, 1, 1.226393520724154), + }, + "E": {'2': (1.0, 1.0, 1.0), '10': (1.0, 1.0, 1.0), 'R': (1.0, 1.0, 1.0)}, +} + + +def xyz_tristimulus_values(*, illuminant, observer, dtype=float): + """Get the CIE XYZ tristimulus values. + + Given an illuminant and observer, this function returns the CIE XYZ tristimulus + values [2]_ scaled such that :math:`Y = 1`. + + Parameters + ---------- + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"} + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"} + One of: 2-degree observer, 10-degree observer, or 'R' observer as in + R function ``grDevices::convertColor`` [3]_. + dtype : dtype, optional + Output data type. + + Returns + ------- + values : array + Array with 3 elements :math:`X, Y, Z` containing the CIE XYZ tristimulus values + of the given illuminant. + + Raises + ------ + ValueError + If either the illuminant or the observer angle are not supported or + unknown. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Standard_illuminant#White_points_of_standard_illuminants + .. [2] https://en.wikipedia.org/wiki/CIE_1931_color_space#Meaning_of_X,_Y_and_Z + .. [3] https://www.rdocumentation.org/packages/grDevices/versions/3.6.2/topics/convertColor + + Notes + ----- + The CIE XYZ tristimulus values are calculated from :math:`x, y` [1]_, using the + formula + + .. math:: X = x / y + + .. math:: Y = 1 + + .. math:: Z = (1 - x - y) / y + + The only exception is the illuminant "D65" with aperture angle 2° for + backward-compatibility reasons. + + Examples + -------- + Get the CIE XYZ tristimulus values for a "D65" illuminant for a 10 degree field of + view + + >>> xyz_tristimulus_values(illuminant="D65", observer="10") + array([0.94809668, 1. , 1.07305136]) + """ + illuminant = illuminant.upper() + observer = observer.upper() + try: + return np.asarray(_illuminants[illuminant][observer], dtype=dtype) + except KeyError: + raise ValueError( + f'Unknown illuminant/observer combination ' + f'(`{illuminant}`, `{observer}`)' + ) + + +# Haematoxylin-Eosin-DAB colorspace +# From original Ruifrok's paper: A. C. Ruifrok and D. A. Johnston, +# "Quantification of histochemical staining by color deconvolution," +# Analytical and quantitative cytology and histology / the International +# Academy of Cytology [and] American Society of Cytology, vol. 23, no. 4, +# pp. 291-9, Aug. 2001. +rgb_from_hed = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11], [0.27, 0.57, 0.78]]) +hed_from_rgb = linalg.inv(rgb_from_hed) + +# Following matrices are adapted form the Java code written by G.Landini. +# The original code is available at: +# https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html + +# Hematoxylin + DAB +rgb_from_hdx = np.array([[0.650, 0.704, 0.286], [0.268, 0.570, 0.776], [0.0, 0.0, 0.0]]) +rgb_from_hdx[2, :] = np.cross(rgb_from_hdx[0, :], rgb_from_hdx[1, :]) +hdx_from_rgb = linalg.inv(rgb_from_hdx) + +# Feulgen + Light Green +rgb_from_fgx = np.array( + [ + [0.46420921, 0.83008335, 0.30827187], + [0.94705542, 0.25373821, 0.19650764], + [0.0, 0.0, 0.0], + ] +) +rgb_from_fgx[2, :] = np.cross(rgb_from_fgx[0, :], rgb_from_fgx[1, :]) +fgx_from_rgb = linalg.inv(rgb_from_fgx) + +# Giemsa: Methyl Blue + Eosin +rgb_from_bex = np.array( + [ + [0.834750233, 0.513556283, 0.196330403], + [0.092789, 0.954111, 0.283111], + [0.0, 0.0, 0.0], + ] +) +rgb_from_bex[2, :] = np.cross(rgb_from_bex[0, :], rgb_from_bex[1, :]) +bex_from_rgb = linalg.inv(rgb_from_bex) + +# FastRed + FastBlue + DAB +rgb_from_rbd = np.array( + [ + [0.21393921, 0.85112669, 0.47794022], + [0.74890292, 0.60624161, 0.26731082], + [0.268, 0.570, 0.776], + ] +) +rbd_from_rgb = linalg.inv(rgb_from_rbd) + +# Methyl Green + DAB +rgb_from_gdx = np.array( + [[0.98003, 0.144316, 0.133146], [0.268, 0.570, 0.776], [0.0, 0.0, 0.0]] +) +rgb_from_gdx[2, :] = np.cross(rgb_from_gdx[0, :], rgb_from_gdx[1, :]) +gdx_from_rgb = linalg.inv(rgb_from_gdx) + +# Hematoxylin + AEC +rgb_from_hax = np.array( + [[0.650, 0.704, 0.286], [0.2743, 0.6796, 0.6803], [0.0, 0.0, 0.0]] +) +rgb_from_hax[2, :] = np.cross(rgb_from_hax[0, :], rgb_from_hax[1, :]) +hax_from_rgb = linalg.inv(rgb_from_hax) + +# Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G +rgb_from_bro = np.array( + [ + [0.853033, 0.508733, 0.112656], + [0.09289875, 0.8662008, 0.49098468], + [0.10732849, 0.36765403, 0.9237484], + ] +) +bro_from_rgb = linalg.inv(rgb_from_bro) + +# Methyl Blue + Ponceau Fuchsin +rgb_from_bpx = np.array( + [ + [0.7995107, 0.5913521, 0.10528667], + [0.09997159, 0.73738605, 0.6680326], + [0.0, 0.0, 0.0], + ] +) +rgb_from_bpx[2, :] = np.cross(rgb_from_bpx[0, :], rgb_from_bpx[1, :]) +bpx_from_rgb = linalg.inv(rgb_from_bpx) + +# Alcian Blue + Hematoxylin +rgb_from_ahx = np.array( + [[0.874622, 0.457711, 0.158256], [0.552556, 0.7544, 0.353744], [0.0, 0.0, 0.0]] +) +rgb_from_ahx[2, :] = np.cross(rgb_from_ahx[0, :], rgb_from_ahx[1, :]) +ahx_from_rgb = linalg.inv(rgb_from_ahx) + +# Hematoxylin + PAS +rgb_from_hpx = np.array( + [[0.644211, 0.716556, 0.266844], [0.175411, 0.972178, 0.154589], [0.0, 0.0, 0.0]] +) +rgb_from_hpx[2, :] = np.cross(rgb_from_hpx[0, :], rgb_from_hpx[1, :]) +hpx_from_rgb = linalg.inv(rgb_from_hpx) + +# ------------------------------------------------------------- +# The conversion functions that make use of the matrices above +# ------------------------------------------------------------- + + +def _convert(matrix, arr): + """Do the color space conversion. + + Parameters + ---------- + matrix : array_like + The 3x3 matrix to use. + arr : (..., C=3, ...) array_like + The input array. By default, the final dimension denotes + channels. + + Returns + ------- + out : (..., C=3, ...) ndarray + The converted array. Same dimensions as input. + """ + arr = _prepare_colorarray(arr) + + return arr @ matrix.T.astype(arr.dtype) + + +@channel_as_last_axis() +def xyz2rgb(xyz, *, channel_axis=-1): + """XYZ to RGB color space conversion. + + Parameters + ---------- + xyz : (..., C=3, ...) array_like + The image in XYZ format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `xyz` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + The CIE XYZ color space is derived from the CIE RGB color space. Note + however that this function converts to sRGB. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2xyz, xyz2rgb + >>> img = data.astronaut() + >>> img_xyz = rgb2xyz(img) + >>> img_rgb = xyz2rgb(img_xyz) + """ + # Follow the algorithm from http://www.easyrgb.com/index.php + # except we don't multiply/divide by 100 in the conversion + arr = _convert(rgb_from_xyz, xyz) + mask = arr > 0.0031308 + arr[mask] = 1.055 * np.power(arr[mask], 1 / 2.4) - 0.055 + arr[~mask] *= 12.92 + np.clip(arr, 0, 1, out=arr) + return arr + + +@channel_as_last_axis() +def rgb2xyz(rgb, *, channel_axis=-1): + """RGB to XYZ color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in XYZ format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + The CIE XYZ color space is derived from the CIE RGB color space. Note + however that this function converts from sRGB. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space + + Examples + -------- + >>> from skimage import data + >>> img = data.astronaut() + >>> img_xyz = rgb2xyz(img) + """ + # Follow the algorithm from http://www.easyrgb.com/index.php + # except we don't multiply/divide by 100 in the conversion + arr = _prepare_colorarray(rgb, channel_axis=-1).copy() + mask = arr > 0.04045 + arr[mask] = np.power((arr[mask] + 0.055) / 1.055, 2.4) + arr[~mask] /= 12.92 + return arr @ xyz_from_rgb.T.astype(arr.dtype) + + +@channel_as_last_axis() +def rgb2rgbcie(rgb, *, channel_axis=-1): + """RGB to RGB CIE color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB CIE format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2rgbcie + >>> img = data.astronaut() + >>> img_rgbcie = rgb2rgbcie(img) + """ + return _convert(rgbcie_from_rgb, rgb) + + +@channel_as_last_axis() +def rgbcie2rgb(rgbcie, *, channel_axis=-1): + """RGB CIE to RGB color space conversion. + + Parameters + ---------- + rgbcie : (..., C=3, ...) array_like + The image in RGB CIE format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgbcie` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2rgbcie, rgbcie2rgb + >>> img = data.astronaut() + >>> img_rgbcie = rgb2rgbcie(img) + >>> img_rgb = rgbcie2rgb(img_rgbcie) + """ + return _convert(rgb_from_rgbcie, rgbcie) + + +@channel_as_last_axis(multichannel_output=False) +def rgb2gray(rgb, *, channel_axis=-1): + """Compute luminance of an RGB image. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + + Returns + ------- + out : ndarray + The luminance image - an array which is the same size as the input + array, but with the channel dimension removed. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + The weights used in this conversion are calibrated for contemporary + CRT phosphors:: + + Y = 0.2125 R + 0.7154 G + 0.0721 B + + If there is an alpha channel present, it is ignored. + + References + ---------- + .. [1] http://poynton.ca/PDFs/ColorFAQ.pdf + + Examples + -------- + >>> from skimage.color import rgb2gray + >>> from skimage import data + >>> img = data.astronaut() + >>> img_gray = rgb2gray(img) + """ + rgb = _prepare_colorarray(rgb) + coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=rgb.dtype) + return rgb @ coeffs + + +def gray2rgba(image, alpha=None, *, channel_axis=-1): + """Create a RGBA representation of a gray-level image. + + Parameters + ---------- + image : array_like + Input image. + alpha : array_like, optional + Alpha channel of the output image. It may be a scalar or an + array that can be broadcast to ``image``. If not specified it is + set to the maximum limit corresponding to the ``image`` dtype. + channel_axis : int, optional + This parameter indicates which axis of the output array will correspond + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + rgba : ndarray + RGBA image. A new dimension of length 4 is added to input + image shape. + """ + arr = np.asarray(image) + if alpha is None: + _, alpha = dtype_limits(arr, clip_negative=False) + with np.errstate(over="ignore", under="ignore"): + alpha_arr = np.asarray(alpha).astype(arr.dtype) + if not np.array_equal(alpha_arr, alpha): + warn( + f'alpha cannot be safely cast to image dtype {arr.dtype.name}', stacklevel=2 + ) + try: + alpha_arr = np.broadcast_to(alpha_arr, arr.shape) + except ValueError as e: + raise ValueError("alpha.shape must match image.shape") from e + rgba = np.stack((arr,) * 3 + (alpha_arr,), axis=channel_axis) + return rgba + + +def gray2rgb(image, *, channel_axis=-1): + """Create an RGB representation of a gray-level image. + + Parameters + ---------- + image : array_like + Input image. + channel_axis : int, optional + This parameter indicates which axis of the output array will correspond + to channels. + + Returns + ------- + rgb : (..., C=3, ...) ndarray + RGB image. A new dimension of length 3 is added to input image. + + Notes + ----- + If the input is a 1-dimensional image of shape ``(M,)``, the output + will be shape ``(M, C=3)``. + """ + return np.stack(3 * (image,), axis=channel_axis) + + +@channel_as_last_axis() +def xyz2lab(xyz, illuminant="D65", observer="2", *, channel_axis=-1): + """XYZ to CIE-LAB color space conversion. + + Parameters + ---------- + xyz : (..., C=3, ...) array_like + The image in XYZ format. By default, the final dimension denotes + channels. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + One of: 2-degree observer, 10-degree observer, or 'R' observer as in + R function grDevices::convertColor. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in CIE-LAB format. Same dimensions as input. + + Raises + ------ + ValueError + If `xyz` is not at least 2-D with shape (..., C=3, ...). + ValueError + If either the illuminant or the observer angle is unsupported or + unknown. + + Notes + ----- + By default Observer="2", Illuminant="D65". CIE XYZ tristimulus values + x_ref=95.047, y_ref=100., z_ref=108.883. See function + :func:`~.xyz_tristimulus_values` for a list of supported illuminants. + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELAB_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2xyz, xyz2lab + >>> img = data.astronaut() + >>> img_xyz = rgb2xyz(img) + >>> img_lab = xyz2lab(img_xyz) + """ + arr = _prepare_colorarray(xyz, channel_axis=-1) + + xyz_ref_white = xyz_tristimulus_values( + illuminant=illuminant, observer=observer, dtype=arr.dtype + ) + + # scale by CIE XYZ tristimulus values of the reference white point + arr = arr / xyz_ref_white + + # Nonlinear distortion and linear transformation + mask = arr > 0.008856 + arr[mask] = np.cbrt(arr[mask]) + arr[~mask] = 7.787 * arr[~mask] + 16.0 / 116.0 + + x, y, z = arr[..., 0], arr[..., 1], arr[..., 2] + + # Vector scaling + L = (116.0 * y) - 16.0 + a = 500.0 * (x - y) + b = 200.0 * (y - z) + + return np.concatenate([x[..., np.newaxis] for x in [L, a, b]], axis=-1) + + +@channel_as_last_axis() +def lab2xyz(lab, illuminant="D65", observer="2", *, channel_axis=-1): + """Convert image in CIE-LAB to XYZ color space. + + Parameters + ---------- + lab : (..., C=3, ...) array_like + The input image in CIE-LAB color space. + Unless `channel_axis` is set, the final dimension denotes the CIE-LAB + channels. + The L* values range from 0 to 100; + the a* and b* values range from -128 to 127. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + The aperture angle of the observer. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in XYZ color space, of same shape as input. + + Raises + ------ + ValueError + If `lab` is not at least 2-D with shape (..., C=3, ...). + ValueError + If either the illuminant or the observer angle are not supported or + unknown. + UserWarning + If any of the pixels are invalid (Z < 0). + + Notes + ----- + The CIE XYZ tristimulus values are x_ref = 95.047, y_ref = 100., and + z_ref = 108.883. See function :func:`~.xyz_tristimulus_values` for a list of + supported illuminants. + + See Also + -------- + xyz2lab + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELAB_color_space + """ + xyz, n_invalid = _lab2xyz(lab, illuminant, observer) + if n_invalid != 0: + warn( + "Conversion from CIE-LAB to XYZ color space resulted in " + f"{n_invalid} negative Z values that have been clipped to zero", + stacklevel=3, + ) + return xyz + + +def _lab2xyz(lab, illuminant, observer): + """Convert CIE-LAB to XYZ color space. + + Internal function for :func:`~.lab2xyz` and others. In addition to the + converted image, return the number of invalid pixels in the Z channel for + correct warning propagation. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in XYZ format. Same dimensions as input. + n_invalid : int + Number of invalid pixels in the Z channel after conversion. + """ + arr = _prepare_colorarray(lab, channel_axis=-1).copy() + + L, a, b = arr[..., 0], arr[..., 1], arr[..., 2] + y = (L + 16.0) / 116.0 + x = (a / 500.0) + y + z = y - (b / 200.0) + + invalid = np.atleast_1d(z < 0).nonzero() + n_invalid = invalid[0].size + if n_invalid != 0: + # Warning should be emitted by caller + if z.ndim > 0: + z[invalid] = 0 + else: + z = 0 + + out = np.stack([x, y, z], axis=-1) + + mask = out > 0.2068966 + out[mask] = np.power(out[mask], 3.0) + out[~mask] = (out[~mask] - 16.0 / 116.0) / 7.787 + + # rescale to the reference white (illuminant) + xyz_ref_white = xyz_tristimulus_values(illuminant=illuminant, observer=observer) + out *= xyz_ref_white + return out, n_invalid + + +@channel_as_last_axis() +def rgb2lab(rgb, illuminant="D65", observer="2", *, channel_axis=-1): + """Conversion from the sRGB color space (IEC 61966-2-1:1999) + to the CIE Lab colorspace under the given illuminant and observer. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + The aperture angle of the observer. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in Lab format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + RGB is a device-dependent color space so, if you use this function, be + sure that the image you are analyzing has been mapped to the sRGB color + space. + + This function uses rgb2xyz and xyz2lab. + By default Observer="2", Illuminant="D65". CIE XYZ tristimulus values + x_ref=95.047, y_ref=100., z_ref=108.883. See function + :func:`~.xyz_tristimulus_values` for a list of supported illuminants. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Standard_illuminant + """ + return xyz2lab(rgb2xyz(rgb), illuminant, observer) + + +@channel_as_last_axis() +def lab2rgb(lab, illuminant="D65", observer="2", *, channel_axis=-1): + """Convert image in CIE-LAB to sRGB color space. + + Parameters + ---------- + lab : (..., C=3, ...) array_like + The input image in CIE-LAB color space. + Unless `channel_axis` is set, the final dimension denotes the CIE-LAB + channels. + The L* values range from 0 to 100; + the a* and b* values range from -128 to 127. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + The aperture angle of the observer. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in sRGB color space, of same shape as input. + + Raises + ------ + ValueError + If `lab` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + This function uses :func:`~.lab2xyz` and :func:`~.xyz2rgb`. + The CIE XYZ tristimulus values are x_ref = 95.047, y_ref = 100., and + z_ref = 108.883. See function :func:`~.xyz_tristimulus_values` for a list of + supported illuminants. + + See Also + -------- + rgb2lab + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Standard_illuminant + .. [2] https://en.wikipedia.org/wiki/CIELAB_color_space + """ + xyz, n_invalid = _lab2xyz(lab, illuminant, observer) + if n_invalid != 0: + warn( + "Conversion from CIE-LAB, via XYZ to sRGB color space resulted in " + f"{n_invalid} negative Z values that have been clipped to zero", + stacklevel=3, + ) + return xyz2rgb(xyz) + + +@channel_as_last_axis() +def xyz2luv(xyz, illuminant="D65", observer="2", *, channel_axis=-1): + """XYZ to CIE-Luv color space conversion. + + Parameters + ---------- + xyz : (..., C=3, ...) array_like + The image in XYZ format. By default, the final dimension denotes + channels. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + The aperture angle of the observer. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in CIE-Luv format. Same dimensions as input. + + Raises + ------ + ValueError + If `xyz` is not at least 2-D with shape (..., C=3, ...). + ValueError + If either the illuminant or the observer angle are not supported or + unknown. + + Notes + ----- + By default XYZ conversion weights use observer=2A. Reference whitepoint + for D65 Illuminant, with XYZ tristimulus values of ``(95.047, 100., + 108.883)``. See function :func:`~.xyz_tristimulus_values` for a list of supported + illuminants. + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELUV + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2xyz, xyz2luv + >>> img = data.astronaut() + >>> img_xyz = rgb2xyz(img) + >>> img_luv = xyz2luv(img_xyz) + """ + input_is_one_pixel = xyz.ndim == 1 + if input_is_one_pixel: + xyz = xyz[np.newaxis, ...] + + arr = _prepare_colorarray(xyz, channel_axis=-1) + + # extract channels + x, y, z = arr[..., 0], arr[..., 1], arr[..., 2] + + eps = np.finfo(arr.dtype).eps + + # compute y_r and L + xyz_ref_white = xyz_tristimulus_values( + illuminant=illuminant, observer=observer, dtype=arr.dtype + ) + L = y / xyz_ref_white[1] + mask = L > 0.008856 + L[mask] = 116.0 * np.cbrt(L[mask]) - 16.0 + L[~mask] = 903.3 * L[~mask] + + uv_weights = np.array([1, 15, 3], dtype=arr.dtype) + u0 = 4 * xyz_ref_white[0] / (uv_weights @ xyz_ref_white) + v0 = 9 * xyz_ref_white[1] / (uv_weights @ xyz_ref_white) + + # u' and v' helper functions + def fu(X, Y, Z): + return (4.0 * X) / (X + 15.0 * Y + 3.0 * Z + eps) + + def fv(X, Y, Z): + return (9.0 * Y) / (X + 15.0 * Y + 3.0 * Z + eps) + + # compute u and v using helper functions + u = 13.0 * L * (fu(x, y, z) - u0) + v = 13.0 * L * (fv(x, y, z) - v0) + + out = np.stack([L, u, v], axis=-1) + + if input_is_one_pixel: + out = np.squeeze(out, axis=0) + + return out + + +@channel_as_last_axis() +def luv2xyz(luv, illuminant="D65", observer="2", *, channel_axis=-1): + """CIE-Luv to XYZ color space conversion. + + Parameters + ---------- + luv : (..., C=3, ...) array_like + The image in CIE-Luv format. By default, the final dimension denotes + channels. + illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional + The name of the illuminant (the function is NOT case sensitive). + observer : {"2", "10", "R"}, optional + The aperture angle of the observer. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in XYZ format. Same dimensions as input. + + Raises + ------ + ValueError + If `luv` is not at least 2-D with shape (..., C=3, ...). + ValueError + If either the illuminant or the observer angle are not supported or + unknown. + + Notes + ----- + XYZ conversion weights use observer=2A. Reference whitepoint for D65 + Illuminant, with XYZ tristimulus values of ``(95.047, 100., 108.883)``. See + function :func:`~.xyz_tristimulus_values` for a list of supported illuminants. + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELUV + """ + arr = _prepare_colorarray(luv, channel_axis=-1).copy() + + L, u, v = arr[..., 0], arr[..., 1], arr[..., 2] + + eps = np.finfo(arr.dtype).eps + + # compute y + y = L.copy() + mask = y > 7.999625 + y[mask] = np.power((y[mask] + 16.0) / 116.0, 3.0) + y[~mask] = y[~mask] / 903.3 + xyz_ref_white = xyz_tristimulus_values( + illuminant=illuminant, observer=observer, dtype=arr.dtype + ) + y *= xyz_ref_white[1] + + # reference white x,z + uv_weights = np.array([1, 15, 3], dtype=arr.dtype) + u0 = 4 * xyz_ref_white[0] / (uv_weights @ xyz_ref_white) + v0 = 9 * xyz_ref_white[1] / (uv_weights @ xyz_ref_white) + + # compute intermediate values + a = u0 + u / (13.0 * L + eps) + b = v0 + v / (13.0 * L + eps) + c = 3 * y * (5 * b - 3) + + # compute x and z + z = ((a - 4) * c - 15 * a * b * y) / (12 * b) + x = -(c / b + 3.0 * z) + + return np.concatenate([q[..., np.newaxis] for q in [x, y, z]], axis=-1) + + +@channel_as_last_axis() +def rgb2luv(rgb, *, channel_axis=-1): + """RGB to CIE-Luv color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in CIE Luv format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + This function uses rgb2xyz and xyz2luv. + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELUV + """ + return xyz2luv(rgb2xyz(rgb)) + + +@channel_as_last_axis() +def luv2rgb(luv, *, channel_axis=-1): + """Luv to RGB color space conversion. + + Parameters + ---------- + luv : (..., C=3, ...) array_like + The image in CIE Luv format. By default, the final dimension denotes + channels. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `luv` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + This function uses luv2xyz and xyz2rgb. + """ + return xyz2rgb(luv2xyz(luv)) + + +@channel_as_last_axis() +def rgb2hed(rgb, *, channel_axis=-1): + """RGB to Haematoxylin-Eosin-DAB (HED) color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in HED format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] A. C. Ruifrok and D. A. Johnston, "Quantification of histochemical + staining by color deconvolution.," Analytical and quantitative + cytology and histology / the International Academy of Cytology [and] + American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001. + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2hed + >>> ihc = data.immunohistochemistry() + >>> ihc_hed = rgb2hed(ihc) + """ + return separate_stains(rgb, hed_from_rgb) + + +@channel_as_last_axis() +def hed2rgb(hed, *, channel_axis=-1): + """Haematoxylin-Eosin-DAB (HED) to RGB color space conversion. + + Parameters + ---------- + hed : (..., C=3, ...) array_like + The image in the HED color space. By default, the final dimension + denotes channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB. Same dimensions as input. + + Raises + ------ + ValueError + If `hed` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] A. C. Ruifrok and D. A. Johnston, "Quantification of histochemical + staining by color deconvolution.," Analytical and quantitative + cytology and histology / the International Academy of Cytology [and] + American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001. + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2hed, hed2rgb + >>> ihc = data.immunohistochemistry() + >>> ihc_hed = rgb2hed(ihc) + >>> ihc_rgb = hed2rgb(ihc_hed) + """ + return combine_stains(hed, rgb_from_hed) + + +@channel_as_last_axis() +def separate_stains(rgb, conv_matrix, *, channel_axis=-1): + """RGB to stain color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + conv_matrix : ndarray + The stain separation matrix as described by G. Landini [1]_. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in stain color space. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Stain separation matrices available in the ``color`` module and their + respective colorspace: + + * ``hed_from_rgb``: Hematoxylin + Eosin + DAB + * ``hdx_from_rgb``: Hematoxylin + DAB + * ``fgx_from_rgb``: Feulgen + Light Green + * ``bex_from_rgb``: Giemsa stain : Methyl Blue + Eosin + * ``rbd_from_rgb``: FastRed + FastBlue + DAB + * ``gdx_from_rgb``: Methyl Green + DAB + * ``hax_from_rgb``: Hematoxylin + AEC + * ``bro_from_rgb``: Blue matrix Anilline Blue + Red matrix Azocarmine\ + + Orange matrix Orange-G + * ``bpx_from_rgb``: Methyl Blue + Ponceau Fuchsin + * ``ahx_from_rgb``: Alcian Blue + Hematoxylin + * ``hpx_from_rgb``: Hematoxylin + PAS + + This implementation borrows some ideas from DIPlib [2]_, e.g. the + compensation using a small value to avoid log artifacts when + calculating the Beer-Lambert law. + + References + ---------- + .. [1] https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html + .. [2] https://github.com/DIPlib/diplib/ + .. [3] A. C. Ruifrok and D. A. Johnston, “Quantification of histochemical + staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol. + 23, no. 4, pp. 291–299, Aug. 2001. + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import separate_stains, hdx_from_rgb + >>> ihc = data.immunohistochemistry() + >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb) + """ + rgb = _prepare_colorarray(rgb, force_copy=True, channel_axis=-1) + np.maximum(rgb, 1e-6, out=rgb) # avoiding log artifacts + log_adjust = np.log(1e-6) # used to compensate the sum above + + stains = (np.log(rgb) / log_adjust) @ conv_matrix + + np.maximum(stains, 0, out=stains) + + return stains + + +@channel_as_last_axis() +def combine_stains(stains, conv_matrix, *, channel_axis=-1): + """Stain to RGB color space conversion. + + Parameters + ---------- + stains : (..., C=3, ...) array_like + The image in stain color space. By default, the final dimension denotes + channels. + conv_matrix : ndarray + The stain separation matrix as described by G. Landini [1]_. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `stains` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Stain combination matrices available in the ``color`` module and their + respective colorspace: + + * ``rgb_from_hed``: Hematoxylin + Eosin + DAB + * ``rgb_from_hdx``: Hematoxylin + DAB + * ``rgb_from_fgx``: Feulgen + Light Green + * ``rgb_from_bex``: Giemsa stain : Methyl Blue + Eosin + * ``rgb_from_rbd``: FastRed + FastBlue + DAB + * ``rgb_from_gdx``: Methyl Green + DAB + * ``rgb_from_hax``: Hematoxylin + AEC + * ``rgb_from_bro``: Blue matrix Anilline Blue + Red matrix Azocarmine\ + + Orange matrix Orange-G + * ``rgb_from_bpx``: Methyl Blue + Ponceau Fuchsin + * ``rgb_from_ahx``: Alcian Blue + Hematoxylin + * ``rgb_from_hpx``: Hematoxylin + PAS + + References + ---------- + .. [1] https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html + .. [2] A. C. Ruifrok and D. A. Johnston, “Quantification of histochemical + staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol. + 23, no. 4, pp. 291–299, Aug. 2001. + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import (separate_stains, combine_stains, + ... hdx_from_rgb, rgb_from_hdx) + >>> ihc = data.immunohistochemistry() + >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb) + >>> ihc_rgb = combine_stains(ihc_hdx, rgb_from_hdx) + """ + stains = _prepare_colorarray(stains, channel_axis=-1) + + # log_adjust here is used to compensate the sum within separate_stains(). + log_adjust = -np.log(1e-6) + log_rgb = -(stains * log_adjust) @ conv_matrix + rgb = np.exp(log_rgb) + + return np.clip(rgb, a_min=0, a_max=1) + + +@channel_as_last_axis() +def lab2lch(lab, *, channel_axis=-1): + """Convert image in CIE-LAB to CIE-LCh color space. + + CIE-LCh is the cylindrical representation of the CIE-LAB (Cartesian) color + space. + + Parameters + ---------- + lab : (..., C=3, ...) array_like + The input image in CIE-LAB color space. + Unless `channel_axis` is set, the final dimension denotes the CIE-LAB + channels. + The L* values range from 0 to 100; + the a* and b* values range from -128 to 127. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in CIE-LCh color space, of same shape as input. + + Raises + ------ + ValueError + If `lab` does not have at least 3 channels (i.e., L*, a*, and b*). + + Notes + ----- + The h channel (i.e., hue) is expressed as an angle in range ``(0, 2*pi)``. + + See Also + -------- + lch2lab + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/CIELAB_color_space + .. [3] https://en.wikipedia.org/wiki/HCL_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2lab, lab2lch + >>> img = data.astronaut() + >>> img_lab = rgb2lab(img) + >>> img_lch = lab2lch(img_lab) + """ + lch = _prepare_lab_array(lab) + + a, b = lch[..., 1], lch[..., 2] + lch[..., 1], lch[..., 2] = _cart2polar_2pi(a, b) + return lch + + +def _cart2polar_2pi(x, y): + """convert cartesian coordinates to polar (uses non-standard theta range!) + + NON-STANDARD RANGE! Maps to ``(0, 2*pi)`` rather than usual ``(-pi, +pi)`` + """ + r, t = np.hypot(x, y), np.arctan2(y, x) + t += np.where(t < 0.0, 2 * np.pi, 0) + return r, t + + +@channel_as_last_axis() +def lch2lab(lch, *, channel_axis=-1): + """Convert image in CIE-LCh to CIE-LAB color space. + + CIE-LCh is the cylindrical representation of the CIE-LAB (Cartesian) color + space. + + Parameters + ---------- + lch : (..., C=3, ...) array_like + The input image in CIE-LCh color space. + Unless `channel_axis` is set, the final dimension denotes the CIE-LAB + channels. + The L* values range from 0 to 100; + the C values range from 0 to 100; + the h values range from 0 to ``2*pi``. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in CIE-LAB format, of same shape as input. + + Raises + ------ + ValueError + If `lch` does not have at least 3 channels (i.e., L*, C, and h). + + Notes + ----- + The h channel (i.e., hue) is expressed as an angle in range ``(0, 2*pi)``. + + See Also + -------- + lab2lch + + References + ---------- + .. [1] http://www.easyrgb.com/en/math.php + .. [2] https://en.wikipedia.org/wiki/HCL_color_space + .. [3] https://en.wikipedia.org/wiki/CIELAB_color_space + + Examples + -------- + >>> from skimage import data + >>> from skimage.color import rgb2lab, lch2lab, lab2lch + >>> img = data.astronaut() + >>> img_lab = rgb2lab(img) + >>> img_lch = lab2lch(img_lab) + >>> img_lab2 = lch2lab(img_lch) + """ + lch = _prepare_lab_array(lch) + + c, h = lch[..., 1], lch[..., 2] + lch[..., 1], lch[..., 2] = c * np.cos(h), c * np.sin(h) + return lch + + +def _prepare_lab_array(arr, force_copy=True): + """Ensure input for lab2lch and lch2lab is well-formed. + + Input array must be in floating point and have at least 3 elements in the + last dimension. Returns a new array by default. + """ + arr = np.asarray(arr) + shape = arr.shape + if shape[-1] < 3: + raise ValueError('Input image has less than 3 channels.') + float_dtype = _supported_float_type(arr.dtype) + if float_dtype == np.float32: + _func = dtype.img_as_float32 + else: + _func = dtype.img_as_float64 + return _func(arr, force_copy=force_copy) + + +@channel_as_last_axis() +def rgb2yuv(rgb, *, channel_axis=-1): + """RGB to YUV color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in YUV format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Y is between 0 and 1. Use YCbCr instead of YUV for the color space + commonly used by video codecs, where Y ranges from 16 to 235. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YUV + """ + return _convert(yuv_from_rgb, rgb) + + +@channel_as_last_axis() +def rgb2yiq(rgb, *, channel_axis=-1): + """RGB to YIQ color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in YIQ format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + """ + return _convert(yiq_from_rgb, rgb) + + +@channel_as_last_axis() +def rgb2ypbpr(rgb, *, channel_axis=-1): + """RGB to YPbPr color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in YPbPr format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YPbPr + """ + return _convert(ypbpr_from_rgb, rgb) + + +@channel_as_last_axis() +def rgb2ycbcr(rgb, *, channel_axis=-1): + """RGB to YCbCr color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in YCbCr format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Y is between 16 and 235. This is the color space commonly used by video + codecs; it is sometimes incorrectly called "YUV". + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YCbCr + """ + arr = _convert(ycbcr_from_rgb, rgb) + arr[..., 0] += 16 + arr[..., 1] += 128 + arr[..., 2] += 128 + return arr + + +@channel_as_last_axis() +def rgb2ydbdr(rgb, *, channel_axis=-1): + """RGB to YDbDr color space conversion. + + Parameters + ---------- + rgb : (..., C=3, ...) array_like + The image in RGB format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in YDbDr format. Same dimensions as input. + + Raises + ------ + ValueError + If `rgb` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + This is the color space commonly used by video codecs. It is also the + reversible color transform in JPEG2000. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YDbDr + """ + arr = _convert(ydbdr_from_rgb, rgb) + return arr + + +@channel_as_last_axis() +def yuv2rgb(yuv, *, channel_axis=-1): + """YUV to RGB color space conversion. + + Parameters + ---------- + yuv : (..., C=3, ...) array_like + The image in YUV format. By default, the final dimension denotes + channels. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `yuv` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YUV + """ + return _convert(rgb_from_yuv, yuv) + + +@channel_as_last_axis() +def yiq2rgb(yiq, *, channel_axis=-1): + """YIQ to RGB color space conversion. + + Parameters + ---------- + yiq : (..., C=3, ...) array_like + The image in YIQ format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `yiq` is not at least 2-D with shape (..., C=3, ...). + """ + return _convert(rgb_from_yiq, yiq) + + +@channel_as_last_axis() +def ypbpr2rgb(ypbpr, *, channel_axis=-1): + """YPbPr to RGB color space conversion. + + Parameters + ---------- + ypbpr : (..., C=3, ...) array_like + The image in YPbPr format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `ypbpr` is not at least 2-D with shape (..., C=3, ...). + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YPbPr + """ + return _convert(rgb_from_ypbpr, ypbpr) + + +@channel_as_last_axis() +def ycbcr2rgb(ycbcr, *, channel_axis=-1): + """YCbCr to RGB color space conversion. + + Parameters + ---------- + ycbcr : (..., C=3, ...) array_like + The image in YCbCr format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `ycbcr` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + Y is between 16 and 235. This is the color space commonly used by video + codecs; it is sometimes incorrectly called "YUV". + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YCbCr + """ + arr = ycbcr.copy() + arr[..., 0] -= 16 + arr[..., 1] -= 128 + arr[..., 2] -= 128 + return _convert(rgb_from_ycbcr, arr) + + +@channel_as_last_axis() +def ydbdr2rgb(ydbdr, *, channel_axis=-1): + """YDbDr to RGB color space conversion. + + Parameters + ---------- + ydbdr : (..., C=3, ...) array_like + The image in YDbDr format. By default, the final dimension denotes + channels. + channel_axis : int, optional + This parameter indicates which axis of the array corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (..., C=3, ...) ndarray + The image in RGB format. Same dimensions as input. + + Raises + ------ + ValueError + If `ydbdr` is not at least 2-D with shape (..., C=3, ...). + + Notes + ----- + This is the color space commonly used by video codecs, also called the + reversible color transform in JPEG2000. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/YDbDr + """ + return _convert(rgb_from_ydbdr, ydbdr) diff --git a/envs/kitoverlay/skimage/color/colorlabel.py b/envs/kitoverlay/skimage/color/colorlabel.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd887a974247e1abb230c2785c6d8718cd18832 --- /dev/null +++ b/envs/kitoverlay/skimage/color/colorlabel.py @@ -0,0 +1,299 @@ +import itertools + +import numpy as np + +from .._shared.utils import _supported_float_type, warn +from ..util import img_as_float +from . import rgb_colors +from .colorconv import gray2rgb, rgb2hsv, hsv2rgb + + +__all__ = ['color_dict', 'label2rgb', 'DEFAULT_COLORS'] + + +DEFAULT_COLORS = ( + 'red', + 'blue', + 'yellow', + 'magenta', + 'green', + 'indigo', + 'darkorange', + 'cyan', + 'pink', + 'yellowgreen', +) + + +color_dict = {k: v for k, v in rgb_colors.__dict__.items() if isinstance(v, tuple)} + + +def _rgb_vector(color): + """Return RGB color as (1, 3) array. + + This RGB array gets multiplied by masked regions of an RGB image, which are + partially flattened by masking (i.e. dimensions 2D + RGB -> 1D + RGB). + + Parameters + ---------- + color : str or array + Color name in ``skimage.color.color_dict`` or RGB float values between [0, 1]. + """ + if isinstance(color, str): + color = color_dict[color] + # Slice to handle RGBA colors. + return np.array(color[:3]) + + +def _match_label_with_color(label, colors, bg_label, bg_color): + """Return `unique_labels` and `color_cycle` for label array and color list. + + Colors are cycled for normal labels, but the background color should only + be used for the background. + """ + # Temporarily set background color; it will be removed later. + if bg_color is None: + bg_color = (0, 0, 0) + bg_color = _rgb_vector(bg_color) + + # map labels to their ranks among all labels from small to large + unique_labels, mapped_labels = np.unique(label, return_inverse=True) + # unique_inverse is no longer flat in NumPy 2.0 + mapped_labels = mapped_labels.reshape(-1) + + # get rank of bg_label + bg_label_rank_list = mapped_labels[label.flat == bg_label] + + # The rank of each label is the index of the color it is matched to in + # color cycle. bg_label should always be mapped to the first color, so + # its rank must be 0. Other labels should be ranked from small to large + # from 1. + if len(bg_label_rank_list) > 0: + bg_label_rank = bg_label_rank_list[0] + mapped_labels[mapped_labels < bg_label_rank] += 1 + mapped_labels[label.flat == bg_label] = 0 + else: + mapped_labels += 1 + + # Modify labels and color cycle so background color is used only once. + color_cycle = itertools.cycle(colors) + color_cycle = itertools.chain([bg_color], color_cycle) + + return mapped_labels, color_cycle + + +def label2rgb( + label, + image=None, + colors=None, + alpha=0.3, + bg_label=0, + bg_color=(0, 0, 0), + image_alpha=1, + kind='overlay', + *, + saturation=0, + channel_axis=-1, +): + """Return an RGB image where color-coded labels are painted over the image. + + Parameters + ---------- + label : ndarray + Integer array of labels with the same shape as `image`. + image : ndarray, optional + Image used as underlay for labels. It should have the same shape as + `labels`, optionally with an additional RGB (channels) axis. If `image` + is an RGB image, it is converted to grayscale before coloring. + colors : list, optional + List of colors. If the number of labels exceeds the number of colors, + then the colors are cycled. + alpha : float [0, 1], optional + Opacity of colorized labels. Ignored if image is `None`. + bg_label : int, optional + Label that's treated as the background. If `bg_label` is specified, + `bg_color` is `None`, and `kind` is `overlay`, + background is not painted by any colors. + bg_color : str or array, optional + Background color. Must be a name in ``skimage.color.color_dict`` or RGB float + values between [0, 1]. + image_alpha : float [0, 1], optional + Opacity of the image. + kind : string, one of {'overlay', 'avg'} + The kind of color image desired. 'overlay' cycles over defined colors + and overlays the colored labels over the original image. 'avg' replaces + each labeled segment with its average color, for a stained-class or + pastel painting appearance. + saturation : float [0, 1], optional + Parameter to control the saturation applied to the original image + between fully saturated (original RGB, `saturation=1`) and fully + unsaturated (grayscale, `saturation=0`). Only applies when + `kind='overlay'`. + channel_axis : int, optional + This parameter indicates which axis of the output array will correspond + to channels. If `image` is provided, this must also match the axis of + `image` that corresponds to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + result : ndarray of float, same shape as `image` + The result of blending a cycling colormap (`colors`) for each distinct + value in `label` with the image, at a certain alpha value. + """ + if image is not None: + image = np.moveaxis(image, source=channel_axis, destination=-1) + if kind == 'overlay': + rgb = _label2rgb_overlay( + label, image, colors, alpha, bg_label, bg_color, image_alpha, saturation + ) + elif kind == 'avg': + rgb = _label2rgb_avg(label, image, bg_label, bg_color) + else: + raise ValueError("`kind` must be either 'overlay' or 'avg'.") + return np.moveaxis(rgb, source=-1, destination=channel_axis) + + +def _label2rgb_overlay( + label, + image=None, + colors=None, + alpha=0.3, + bg_label=-1, + bg_color=None, + image_alpha=1, + saturation=0, +): + """Return an RGB image where color-coded labels are painted over the image. + + Parameters + ---------- + label : ndarray + Integer array of labels with the same shape as `image`. + image : ndarray, optional + Image used as underlay for labels. It should have the same shape as + `labels`, optionally with an additional RGB (channels) axis. If `image` + is an RGB image, it is converted to grayscale before coloring. + colors : list, optional + List of colors. If the number of labels exceeds the number of colors, + then the colors are cycled. + alpha : float [0, 1], optional + Opacity of colorized labels. Ignored if image is `None`. + bg_label : int, optional + Label that's treated as the background. If `bg_label` is specified and + `bg_color` is `None`, background is not painted by any colors. + bg_color : str or array, optional + Background color. Must be a name in ``skimage.color.color_dict`` or RGB float + values between [0, 1]. + image_alpha : float [0, 1], optional + Opacity of the image. + saturation : float [0, 1], optional + Parameter to control the saturation applied to the original image + between fully saturated (original RGB, `saturation=1`) and fully + unsaturated (grayscale, `saturation=0`). + + Returns + ------- + result : ndarray of float, same shape as `image` + The result of blending a cycling colormap (`colors`) for each distinct + value in `label` with the image, at a certain alpha value. + """ + if not 0 <= saturation <= 1: + warn(f'saturation must be in range [0, 1], got {saturation}') + + if colors is None: + colors = DEFAULT_COLORS + colors = [_rgb_vector(c) for c in colors] + + if image is None: + image = np.zeros(label.shape + (3,), dtype=np.float64) + # Opacity doesn't make sense if no image exists. + alpha = 1 + else: + if image.shape[: label.ndim] != label.shape or image.ndim > label.ndim + 1: + raise ValueError("`image` and `label` must be the same shape") + + if image.ndim == label.ndim + 1 and image.shape[-1] != 3: + raise ValueError("`image` must be RGB (image.shape[-1] must be 3).") + + if image.min() < 0: + warn("Negative intensities in `image` are not supported") + + float_dtype = _supported_float_type(image.dtype) + image = img_as_float(image).astype(float_dtype, copy=False) + if image.ndim > label.ndim: + hsv = rgb2hsv(image) + hsv[..., 1] *= saturation + image = hsv2rgb(hsv) + elif image.ndim == label.ndim: + image = gray2rgb(image) + image = image * image_alpha + (1 - image_alpha) + + # Ensure that all labels are non-negative so we can index into + # `label_to_color` correctly. + offset = min(label.min(), bg_label) + if offset != 0: + label = label - offset # Make sure you don't modify the input array. + bg_label -= offset + + new_type = np.min_scalar_type(int(label.max())) + if new_type == bool: + new_type = np.uint8 + label = label.astype(new_type) + + mapped_labels_flat, color_cycle = _match_label_with_color( + label, colors, bg_label, bg_color + ) + + if len(mapped_labels_flat) == 0: + return image + + dense_labels = range(np.max(mapped_labels_flat) + 1) + + label_to_color = np.stack([c for i, c in zip(dense_labels, color_cycle)]) + + mapped_labels = label + mapped_labels.flat = mapped_labels_flat + result = label_to_color[mapped_labels] * alpha + image * (1 - alpha) + + # Remove background label if its color was not specified. + remove_background = 0 in mapped_labels_flat and bg_color is None + if remove_background: + result[label == bg_label] = image[label == bg_label] + + return result + + +def _label2rgb_avg(label_field, image, bg_label=0, bg_color=(0, 0, 0)): + """Visualise each segment in `label_field` with its mean color in `image`. + + Parameters + ---------- + label_field : ndarray of int + A segmentation of an image. + image : array, shape ``label_field.shape + (3,)`` + A color image of the same spatial shape as `label_field`. + bg_label : int, optional + A value in `label_field` to be treated as background. + bg_color : 3-tuple of int, optional + The color for the background label + + Returns + ------- + out : ndarray, same shape and type as `image` + The output visualization. + """ + out = np.zeros(label_field.shape + (3,), dtype=image.dtype) + labels = np.unique(label_field) + bg = labels == bg_label + if bg.any(): + labels = labels[labels != bg_label] + mask = (label_field == bg_label).nonzero() + out[mask] = bg_color + for label in labels: + mask = (label_field == label).nonzero() + color = image[mask].mean(axis=0) + out[mask] = color + return out diff --git a/envs/kitoverlay/skimage/color/delta_e.py b/envs/kitoverlay/skimage/color/delta_e.py new file mode 100644 index 0000000000000000000000000000000000000000..b422dcd730f432f6fe276f9fbe1579456adf68db --- /dev/null +++ b/envs/kitoverlay/skimage/color/delta_e.py @@ -0,0 +1,393 @@ +""" +Functions for calculating the "distance" between colors. + +Implicit in these definitions of "distance" is the notion of "Just Noticeable +Distance" (JND). This represents the distance between colors where a human can +perceive different colors. Humans are more sensitive to certain colors than +others, which different deltaE metrics correct for with varying degrees of +sophistication. + +The literature often mentions 1 as the minimum distance for visual +differentiation, but more recent studies (Mahy 1994) peg JND at 2.3 + +The delta-E notation comes from the German word for "Sensation" (Empfindung). + +References +---------- +.. [1] https://en.wikipedia.org/wiki/Color_difference + +""" + +import numpy as np + +from .._shared.utils import _supported_float_type +from .colorconv import lab2lch, _cart2polar_2pi + + +def _float_inputs(lab1, lab2, allow_float32=True): + lab1 = np.asarray(lab1) + lab2 = np.asarray(lab2) + if allow_float32: + float_dtype = _supported_float_type((lab1.dtype, lab2.dtype)) + else: + float_dtype = np.float64 + lab1 = lab1.astype(float_dtype, copy=False) + lab2 = lab2.astype(float_dtype, copy=False) + return lab1, lab2 + + +def deltaE_cie76(lab1, lab2, channel_axis=-1): + """Euclidean distance between two points in Lab color space + + Parameters + ---------- + lab1 : array_like + reference color (Lab colorspace) + lab2 : array_like + comparison color (Lab colorspace) + channel_axis : int, optional + This parameter indicates which axis of the arrays corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + dE : array_like + distance between colors `lab1` and `lab2` + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Color_difference + .. [2] A. R. Robertson, "The CIE 1976 color-difference formulae," + Color Res. Appl. 2, 7-11 (1977). + """ + lab1, lab2 = _float_inputs(lab1, lab2, allow_float32=True) + L1, a1, b1 = np.moveaxis(lab1, source=channel_axis, destination=0)[:3] + L2, a2, b2 = np.moveaxis(lab2, source=channel_axis, destination=0)[:3] + return np.sqrt((L2 - L1) ** 2 + (a2 - a1) ** 2 + (b2 - b1) ** 2) + + +def deltaE_ciede94( + lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015, *, channel_axis=-1 +): + """Color difference according to CIEDE 94 standard + + Accommodates perceptual non-uniformities through the use of application + specific scale factors (`kH`, `kC`, `kL`, `k1`, and `k2`). + + Parameters + ---------- + lab1 : array_like + reference color (Lab colorspace) + lab2 : array_like + comparison color (Lab colorspace) + kH : float, optional + Hue scale + kC : float, optional + Chroma scale + kL : float, optional + Lightness scale + k1 : float, optional + first scale parameter + k2 : float, optional + second scale parameter + channel_axis : int, optional + This parameter indicates which axis of the arrays corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + dE : array_like + color difference between `lab1` and `lab2` + + Notes + ----- + deltaE_ciede94 is not symmetric with respect to lab1 and lab2. CIEDE94 + defines the scales for the lightness, hue, and chroma in terms of the first + color. Consequently, the first color should be regarded as the "reference" + color. + + `kL`, `k1`, `k2` depend on the application and default to the values + suggested for graphic arts + + ========== ============== ========== + Parameter Graphic Arts Textiles + ========== ============== ========== + `kL` 1.000 2.000 + `k1` 0.045 0.048 + `k2` 0.015 0.014 + ========== ============== ========== + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Color_difference + .. [2] http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html + """ + lab1, lab2 = _float_inputs(lab1, lab2, allow_float32=True) + lab1 = np.moveaxis(lab1, source=channel_axis, destination=0) + lab2 = np.moveaxis(lab2, source=channel_axis, destination=0) + + L1, C1 = lab2lch(lab1, channel_axis=0)[:2] + L2, C2 = lab2lch(lab2, channel_axis=0)[:2] + + dL = L1 - L2 + dC = C1 - C2 + dH2 = get_dH2(lab1, lab2, channel_axis=0) + + SL = 1 + SC = 1 + k1 * C1 + SH = 1 + k2 * C1 + + dE2 = (dL / (kL * SL)) ** 2 + dE2 += (dC / (kC * SC)) ** 2 + dE2 += dH2 / (kH * SH) ** 2 + return np.sqrt(np.maximum(dE2, 0)) + + +def deltaE_ciede2000(lab1, lab2, kL=1, kC=1, kH=1, *, channel_axis=-1): + """Color difference as given by the CIEDE 2000 standard. + + CIEDE 2000 is a major revision of CIDE94. The perceptual calibration is + largely based on experience with automotive paint on smooth surfaces. + + Parameters + ---------- + lab1 : array_like + reference color (Lab colorspace) + lab2 : array_like + comparison color (Lab colorspace) + kL : float (range), optional + lightness scale factor, 1 for "acceptably close"; 2 for "imperceptible" + see deltaE_cmc + kC : float (range), optional + chroma scale factor, usually 1 + kH : float (range), optional + hue scale factor, usually 1 + channel_axis : int, optional + This parameter indicates which axis of the arrays corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + deltaE : array_like + The distance between `lab1` and `lab2` + + Notes + ----- + CIEDE 2000 assumes parametric weighting factors for the lightness, chroma, + and hue (`kL`, `kC`, `kH` respectively). These default to 1. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Color_difference + .. [2] http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf + :DOI:`10.1364/AO.33.008069` + .. [3] M. Melgosa, J. Quesada, and E. Hita, "Uniformity of some recent + color metrics tested with an accurate color-difference tolerance + dataset," Appl. Opt. 33, 8069-8077 (1994). + """ + lab1, lab2 = _float_inputs(lab1, lab2, allow_float32=True) + + channel_axis = channel_axis % lab1.ndim + unroll = False + if lab1.ndim == 1 and lab2.ndim == 1: + unroll = True + if lab1.ndim == 1: + lab1 = lab1[None, :] + if lab2.ndim == 1: + lab2 = lab2[None, :] + channel_axis += 1 + L1, a1, b1 = np.moveaxis(lab1, source=channel_axis, destination=0)[:3] + L2, a2, b2 = np.moveaxis(lab2, source=channel_axis, destination=0)[:3] + + # distort `a` based on average chroma + # then convert to lch coordinates from distorted `a` + # all subsequence calculations are in the new coordinates + # (often denoted "prime" in the literature) + Cbar = 0.5 * (np.hypot(a1, b1) + np.hypot(a2, b2)) + c7 = Cbar**7 + G = 0.5 * (1 - np.sqrt(c7 / (c7 + 25**7))) + scale = 1 + G + C1, h1 = _cart2polar_2pi(a1 * scale, b1) + C2, h2 = _cart2polar_2pi(a2 * scale, b2) + # recall that c, h are polar coordinates. c==r, h==theta + + # cide2000 has four terms to delta_e: + # 1) Luminance term + # 2) Hue term + # 3) Chroma term + # 4) hue Rotation term + + # lightness term + Lbar = 0.5 * (L1 + L2) + tmp = (Lbar - 50) ** 2 + SL = 1 + 0.015 * tmp / np.sqrt(20 + tmp) + L_term = (L2 - L1) / (kL * SL) + + # chroma term + Cbar = 0.5 * (C1 + C2) # new coordinates + SC = 1 + 0.045 * Cbar + C_term = (C2 - C1) / (kC * SC) + + # hue term + h_diff = h2 - h1 + h_sum = h1 + h2 + CC = C1 * C2 + + dH = h_diff.copy() + dH[h_diff > np.pi] -= 2 * np.pi + dH[h_diff < -np.pi] += 2 * np.pi + dH[CC == 0.0] = 0.0 # if r == 0, dtheta == 0 + dH_term = 2 * np.sqrt(CC) * np.sin(dH / 2) + + Hbar = h_sum.copy() + mask = np.logical_and(CC != 0.0, np.abs(h_diff) > np.pi) + Hbar[mask * (h_sum < 2 * np.pi)] += 2 * np.pi + Hbar[mask * (h_sum >= 2 * np.pi)] -= 2 * np.pi + Hbar[CC == 0.0] *= 2 + Hbar *= 0.5 + + T = ( + 1 + - 0.17 * np.cos(Hbar - np.deg2rad(30)) + + 0.24 * np.cos(2 * Hbar) + + 0.32 * np.cos(3 * Hbar + np.deg2rad(6)) + - 0.20 * np.cos(4 * Hbar - np.deg2rad(63)) + ) + SH = 1 + 0.015 * Cbar * T + + H_term = dH_term / (kH * SH) + + # hue rotation + c7 = Cbar**7 + Rc = 2 * np.sqrt(c7 / (c7 + 25**7)) + dtheta = np.deg2rad(30) * np.exp(-(((np.rad2deg(Hbar) - 275) / 25) ** 2)) + R_term = -np.sin(2 * dtheta) * Rc * C_term * H_term + + # put it all together + dE2 = L_term**2 + dE2 += C_term**2 + dE2 += H_term**2 + dE2 += R_term + ans = np.sqrt(np.maximum(dE2, 0)) + if unroll: + ans = ans[0] + return ans + + +def deltaE_cmc(lab1, lab2, kL=1, kC=1, *, channel_axis=-1): + """Color difference from the CMC l:c standard. + + This color difference was developed by the Colour Measurement Committee + (CMC) of the Society of Dyers and Colourists (United Kingdom). It is + intended for use in the textile industry. + + The scale factors `kL`, `kC` set the weight given to differences in + lightness and chroma relative to differences in hue. The usual values are + ``kL=2``, ``kC=1`` for "acceptability" and ``kL=1``, ``kC=1`` for + "imperceptibility". Colors with ``dE > 1`` are "different" for the given + scale factors. + + Parameters + ---------- + lab1 : array_like + reference color (Lab colorspace) + lab2 : array_like + comparison color (Lab colorspace) + channel_axis : int, optional + This parameter indicates which axis of the arrays corresponds to + channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + dE : array_like + distance between colors `lab1` and `lab2` + + Notes + ----- + deltaE_cmc the defines the scales for the lightness, hue, and chroma + in terms of the first color. Consequently + ``deltaE_cmc(lab1, lab2) != deltaE_cmc(lab2, lab1)`` + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Color_difference + .. [2] http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html + .. [3] F. J. J. Clarke, R. McDonald, and B. Rigg, "Modification to the + JPC79 colour-difference formula," J. Soc. Dyers Colour. 100, 128-132 + (1984). + """ + lab1, lab2 = _float_inputs(lab1, lab2, allow_float32=True) + lab1 = np.moveaxis(lab1, source=channel_axis, destination=0) + lab2 = np.moveaxis(lab2, source=channel_axis, destination=0) + L1, C1, h1 = lab2lch(lab1, channel_axis=0)[:3] + L2, C2, h2 = lab2lch(lab2, channel_axis=0)[:3] + + dC = C1 - C2 + dL = L1 - L2 + dH2 = get_dH2(lab1, lab2, channel_axis=0) + + T = np.where( + np.logical_and(np.rad2deg(h1) >= 164, np.rad2deg(h1) <= 345), + 0.56 + 0.2 * np.abs(np.cos(h1 + np.deg2rad(168))), + 0.36 + 0.4 * np.abs(np.cos(h1 + np.deg2rad(35))), + ) + c1_4 = C1**4 + F = np.sqrt(c1_4 / (c1_4 + 1900)) + + SL = np.where(L1 < 16, 0.511, 0.040975 * L1 / (1.0 + 0.01765 * L1)) + SC = 0.638 + 0.0638 * C1 / (1.0 + 0.0131 * C1) + SH = SC * (F * T + 1 - F) + + dE2 = (dL / (kL * SL)) ** 2 + dE2 += (dC / (kC * SC)) ** 2 + dE2 += dH2 / (SH**2) + + return np.sqrt(np.maximum(dE2, 0)) + + +def get_dH2(lab1, lab2, *, channel_axis=-1): + """squared hue difference term occurring in deltaE_cmc and deltaE_ciede94 + + Despite its name, "dH" is not a simple difference of hue values. We avoid + working directly with the hue value, since differencing angles is + troublesome. The hue term is usually written as: + c1 = sqrt(a1**2 + b1**2) + c2 = sqrt(a2**2 + b2**2) + term = (a1-a2)**2 + (b1-b2)**2 - (c1-c2)**2 + dH = sqrt(term) + + However, this has poor roundoff properties when a or b is dominant. + Instead, ab is a vector with elements a and b. The same dH term can be + re-written as: + |ab1-ab2|**2 - (|ab1| - |ab2|)**2 + and then simplified to: + 2*|ab1|*|ab2| - 2*dot(ab1, ab2) + """ + # This function needs double precision internally for accuracy + input_is_float_32 = _supported_float_type((lab1.dtype, lab2.dtype)) == np.float32 + lab1, lab2 = _float_inputs(lab1, lab2, allow_float32=False) + + a1, b1 = np.moveaxis(lab1, source=channel_axis, destination=0)[1:3] + a2, b2 = np.moveaxis(lab2, source=channel_axis, destination=0)[1:3] + + # magnitude of (a, b) is the chroma + C1 = np.hypot(a1, b1) + C2 = np.hypot(a2, b2) + + term = (C1 * C2) - (a1 * a2 + b1 * b2) + out = 2 * term + if input_is_float_32: + out = out.astype(np.float32) + return out diff --git a/envs/kitoverlay/skimage/color/rgb_colors.py b/envs/kitoverlay/skimage/color/rgb_colors.py new file mode 100644 index 0000000000000000000000000000000000000000..23046105029b96ee8b418b9cc83815761ada31ce --- /dev/null +++ b/envs/kitoverlay/skimage/color/rgb_colors.py @@ -0,0 +1,146 @@ +aliceblue = (0.941, 0.973, 1) +antiquewhite = (0.98, 0.922, 0.843) +aqua = (0, 1, 1) +aquamarine = (0.498, 1, 0.831) +azure = (0.941, 1, 1) +beige = (0.961, 0.961, 0.863) +bisque = (1, 0.894, 0.769) +black = (0, 0, 0) +blanchedalmond = (1, 0.922, 0.804) +blue = (0, 0, 1) +blueviolet = (0.541, 0.169, 0.886) +brown = (0.647, 0.165, 0.165) +burlywood = (0.871, 0.722, 0.529) +cadetblue = (0.373, 0.62, 0.627) +chartreuse = (0.498, 1, 0) +chocolate = (0.824, 0.412, 0.118) +coral = (1, 0.498, 0.314) +cornflowerblue = (0.392, 0.584, 0.929) +cornsilk = (1, 0.973, 0.863) +crimson = (0.863, 0.0784, 0.235) +cyan = (0, 1, 1) +darkblue = (0, 0, 0.545) +darkcyan = (0, 0.545, 0.545) +darkgoldenrod = (0.722, 0.525, 0.0431) +darkgray = (0.663, 0.663, 0.663) +darkgreen = (0, 0.392, 0) +darkgrey = (0.663, 0.663, 0.663) +darkkhaki = (0.741, 0.718, 0.42) +darkmagenta = (0.545, 0, 0.545) +darkolivegreen = (0.333, 0.42, 0.184) +darkorange = (1, 0.549, 0) +darkorchid = (0.6, 0.196, 0.8) +darkred = (0.545, 0, 0) +darksalmon = (0.914, 0.588, 0.478) +darkseagreen = (0.561, 0.737, 0.561) +darkslateblue = (0.282, 0.239, 0.545) +darkslategray = (0.184, 0.31, 0.31) +darkslategrey = (0.184, 0.31, 0.31) +darkturquoise = (0, 0.808, 0.82) +darkviolet = (0.58, 0, 0.827) +deeppink = (1, 0.0784, 0.576) +deepskyblue = (0, 0.749, 1) +dimgray = (0.412, 0.412, 0.412) +dimgrey = (0.412, 0.412, 0.412) +dodgerblue = (0.118, 0.565, 1) +firebrick = (0.698, 0.133, 0.133) +floralwhite = (1, 0.98, 0.941) +forestgreen = (0.133, 0.545, 0.133) +fuchsia = (1, 0, 1) +gainsboro = (0.863, 0.863, 0.863) +ghostwhite = (0.973, 0.973, 1) +gold = (1, 0.843, 0) +goldenrod = (0.855, 0.647, 0.125) +gray = (0.502, 0.502, 0.502) +green = (0, 0.502, 0) +greenyellow = (0.678, 1, 0.184) +grey = (0.502, 0.502, 0.502) +honeydew = (0.941, 1, 0.941) +hotpink = (1, 0.412, 0.706) +indianred = (0.804, 0.361, 0.361) +indigo = (0.294, 0, 0.51) +ivory = (1, 1, 0.941) +khaki = (0.941, 0.902, 0.549) +lavender = (0.902, 0.902, 0.98) +lavenderblush = (1, 0.941, 0.961) +lawngreen = (0.486, 0.988, 0) +lemonchiffon = (1, 0.98, 0.804) +lightblue = (0.678, 0.847, 0.902) +lightcoral = (0.941, 0.502, 0.502) +lightcyan = (0.878, 1, 1) +lightgoldenrodyellow = (0.98, 0.98, 0.824) +lightgray = (0.827, 0.827, 0.827) +lightgreen = (0.565, 0.933, 0.565) +lightgrey = (0.827, 0.827, 0.827) +lightpink = (1, 0.714, 0.757) +lightsalmon = (1, 0.627, 0.478) +lightseagreen = (0.125, 0.698, 0.667) +lightskyblue = (0.529, 0.808, 0.98) +lightslategray = (0.467, 0.533, 0.6) +lightslategrey = (0.467, 0.533, 0.6) +lightsteelblue = (0.69, 0.769, 0.871) +lightyellow = (1, 1, 0.878) +lime = (0, 1, 0) +limegreen = (0.196, 0.804, 0.196) +linen = (0.98, 0.941, 0.902) +magenta = (1, 0, 1) +maroon = (0.502, 0, 0) +mediumaquamarine = (0.4, 0.804, 0.667) +mediumblue = (0, 0, 0.804) +mediumorchid = (0.729, 0.333, 0.827) +mediumpurple = (0.576, 0.439, 0.859) +mediumseagreen = (0.235, 0.702, 0.443) +mediumslateblue = (0.482, 0.408, 0.933) +mediumspringgreen = (0, 0.98, 0.604) +mediumturquoise = (0.282, 0.82, 0.8) +mediumvioletred = (0.78, 0.0824, 0.522) +midnightblue = (0.098, 0.098, 0.439) +mintcream = (0.961, 1, 0.98) +mistyrose = (1, 0.894, 0.882) +moccasin = (1, 0.894, 0.71) +navajowhite = (1, 0.871, 0.678) +navy = (0, 0, 0.502) +oldlace = (0.992, 0.961, 0.902) +olive = (0.502, 0.502, 0) +olivedrab = (0.42, 0.557, 0.137) +orange = (1, 0.647, 0) +orangered = (1, 0.271, 0) +orchid = (0.855, 0.439, 0.839) +palegoldenrod = (0.933, 0.91, 0.667) +palegreen = (0.596, 0.984, 0.596) +palevioletred = (0.686, 0.933, 0.933) +papayawhip = (1, 0.937, 0.835) +peachpuff = (1, 0.855, 0.725) +peru = (0.804, 0.522, 0.247) +pink = (1, 0.753, 0.796) +plum = (0.867, 0.627, 0.867) +powderblue = (0.69, 0.878, 0.902) +purple = (0.502, 0, 0.502) +red = (1, 0, 0) +rosybrown = (0.737, 0.561, 0.561) +royalblue = (0.255, 0.412, 0.882) +saddlebrown = (0.545, 0.271, 0.0745) +salmon = (0.98, 0.502, 0.447) +sandybrown = (0.98, 0.643, 0.376) +seagreen = (0.18, 0.545, 0.341) +seashell = (1, 0.961, 0.933) +sienna = (0.627, 0.322, 0.176) +silver = (0.753, 0.753, 0.753) +skyblue = (0.529, 0.808, 0.922) +slateblue = (0.416, 0.353, 0.804) +slategray = (0.439, 0.502, 0.565) +slategrey = (0.439, 0.502, 0.565) +snow = (1, 0.98, 0.98) +springgreen = (0, 1, 0.498) +steelblue = (0.275, 0.51, 0.706) +tan = (0.824, 0.706, 0.549) +teal = (0, 0.502, 0.502) +thistle = (0.847, 0.749, 0.847) +tomato = (1, 0.388, 0.278) +turquoise = (0.251, 0.878, 0.816) +violet = (0.933, 0.51, 0.933) +wheat = (0.961, 0.871, 0.702) +white = (1, 1, 1) +whitesmoke = (0.961, 0.961, 0.961) +yellow = (1, 1, 0) +yellowgreen = (0.604, 0.804, 0.196) diff --git a/envs/kitoverlay/skimage/exposure/__init__.py b/envs/kitoverlay/skimage/exposure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45d6ef21e0a88162e58b739a84cb8f6cef2e951a --- /dev/null +++ b/envs/kitoverlay/skimage/exposure/__init__.py @@ -0,0 +1,5 @@ +"""Image intensity adjustment, e.g., histogram equalization, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/exposure/__init__.pyi b/envs/kitoverlay/skimage/exposure/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f058561dc86fb51afc5f444d0af35fde9f8d1d69 --- /dev/null +++ b/envs/kitoverlay/skimage/exposure/__init__.pyi @@ -0,0 +1,29 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'histogram', + 'equalize_hist', + 'equalize_adapthist', + 'rescale_intensity', + 'cumulative_distribution', + 'adjust_gamma', + 'adjust_sigmoid', + 'adjust_log', + 'is_low_contrast', + 'match_histograms', +] + +from ._adapthist import equalize_adapthist +from .histogram_matching import match_histograms +from .exposure import ( + histogram, + equalize_hist, + rescale_intensity, + cumulative_distribution, + adjust_gamma, + adjust_sigmoid, + adjust_log, + is_low_contrast, +) diff --git a/envs/kitoverlay/skimage/exposure/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/exposure/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7612f37389363a90595dc09cffd3263e654c975c Binary files /dev/null and b/envs/kitoverlay/skimage/exposure/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/exposure/__pycache__/_adapthist.cpython-311.pyc b/envs/kitoverlay/skimage/exposure/__pycache__/_adapthist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145cfddc4d2ab4e248243497a7bd27cc2e564cb8 Binary files /dev/null and b/envs/kitoverlay/skimage/exposure/__pycache__/_adapthist.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/exposure/__pycache__/exposure.cpython-311.pyc b/envs/kitoverlay/skimage/exposure/__pycache__/exposure.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29a32778e3b7240d2bf7d01429200b8799884434 Binary files /dev/null and b/envs/kitoverlay/skimage/exposure/__pycache__/exposure.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/exposure/__pycache__/histogram_matching.cpython-311.pyc b/envs/kitoverlay/skimage/exposure/__pycache__/histogram_matching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ee708c68cef8703eb7d36822a42d55146f51821 Binary files /dev/null and b/envs/kitoverlay/skimage/exposure/__pycache__/histogram_matching.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/exposure/_adapthist.py b/envs/kitoverlay/skimage/exposure/_adapthist.py new file mode 100644 index 0000000000000000000000000000000000000000..5404e32c42b2165075113991e89abd468d810cfd --- /dev/null +++ b/envs/kitoverlay/skimage/exposure/_adapthist.py @@ -0,0 +1,317 @@ +""" +Adapted from "Contrast Limited Adaptive Histogram Equalization" by Karel +Zuiderveld, Graphics Gems IV, Academic Press, 1994. + +http://tog.acm.org/resources/GraphicsGems/ + +Relicensed with permission of the author under the Modified BSD license. +""" + +import math +import numbers + +import numpy as np + +from .._shared.utils import _supported_float_type +from ..color.adapt_rgb import adapt_rgb, hsv_value +from .exposure import rescale_intensity +from ..util import img_as_uint + +NR_OF_GRAY = 2**14 # number of grayscale levels to use in CLAHE algorithm + + +@adapt_rgb(hsv_value) +def equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256): + """Contrast Limited Adaptive Histogram Equalization (CLAHE). + + An algorithm for local contrast enhancement, that uses histograms computed + over different tile regions of the image. Local details can therefore be + enhanced even in regions that are darker or lighter than most of the image. + + Parameters + ---------- + image : (M[, ...][, C]) ndarray + Input image. + kernel_size : int or array_like, optional + Defines the shape of contextual regions used in the algorithm. If + iterable is passed, it must have the same number of elements as + ``image.ndim`` (without color channel). If integer, it is broadcasted + to each `image` dimension. By default, ``kernel_size`` is 1/8 of + ``image`` height by 1/8 of its width. + clip_limit : float, optional + Clipping limit, normalized between 0 and 1 (higher values give more + contrast). + nbins : int, optional + Number of gray bins for histogram ("data range"). + + Returns + ------- + out : (M[, ...][, C]) ndarray + Equalized image with float64 dtype. + + See Also + -------- + equalize_hist, rescale_intensity + + Notes + ----- + * For color images, the following steps are performed: + - The image is converted to HSV color space + - The CLAHE algorithm is run on the V (Value) channel + - The image is converted back to RGB space and returned + * For RGBA images, the original alpha channel is removed. + + .. versionchanged:: 0.17 + The values returned by this function are slightly shifted upwards + because of an internal change in rounding behavior. + + References + ---------- + .. [1] http://tog.acm.org/resources/GraphicsGems/ + .. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE + """ + + float_dtype = _supported_float_type(image.dtype) + image = img_as_uint(image) + image = np.round(rescale_intensity(image, out_range=(0, NR_OF_GRAY - 1))).astype( + np.min_scalar_type(NR_OF_GRAY) + ) + + if kernel_size is None: + kernel_size = tuple([max(s // 8, 1) for s in image.shape]) + elif isinstance(kernel_size, numbers.Number): + kernel_size = (kernel_size,) * image.ndim + elif len(kernel_size) != image.ndim: + raise ValueError(f'Incorrect value of `kernel_size`: {kernel_size}') + + kernel_size = [int(k) for k in kernel_size] + + image = _clahe(image, kernel_size, clip_limit, nbins) + image = image.astype(float_dtype, copy=False) + return rescale_intensity(image) + + +def _clahe(image, kernel_size, clip_limit, nbins): + """Contrast Limited Adaptive Histogram Equalization. + + Parameters + ---------- + image : (M[, ...]) ndarray + Input image. + kernel_size : int or N-tuple of int + Defines the shape of contextual regions used in the algorithm. + clip_limit : float + Normalized clipping limit between 0 and 1 (higher values give more + contrast). + nbins : int + Number of gray bins for histogram ("data range"). + + Returns + ------- + out : (M[, ...]) ndarray + Equalized image. + + The number of "effective" graylevels in the output image is set by `nbins`; + selecting a small value (e.g. 128) speeds up processing and still produces + an output image of good quality. A clip limit of 0 or larger than or equal + to 1 results in standard (non-contrast limited) AHE. + """ + ndim = image.ndim + dtype = image.dtype + + # pad the image such that the shape in each dimension + # - is a multiple of the kernel_size and + # - is preceded by half a kernel size + pad_start_per_dim = [k // 2 for k in kernel_size] + + pad_end_per_dim = [ + (k - s % k) % k + int(np.ceil(k / 2.0)) + for k, s in zip(kernel_size, image.shape) + ] + + image = np.pad( + image, + [[p_i, p_f] for p_i, p_f in zip(pad_start_per_dim, pad_end_per_dim)], + mode='reflect', + ) + + # determine gray value bins + bin_size = 1 + NR_OF_GRAY // nbins + lut = np.arange(NR_OF_GRAY, dtype=np.min_scalar_type(NR_OF_GRAY)) + lut //= bin_size + + image = lut[image] + + # calculate graylevel mappings for each contextual region + # rearrange image into flattened contextual regions + ns_hist = [int(s / k) - 1 for s, k in zip(image.shape, kernel_size)] + hist_blocks_shape = np.array([ns_hist, kernel_size]).T.flatten() + hist_blocks_axis_order = np.array( + [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)] + ).flatten() + hist_slices = [slice(k // 2, k // 2 + n * k) for k, n in zip(kernel_size, ns_hist)] + hist_blocks = image[tuple(hist_slices)].reshape(hist_blocks_shape) + hist_blocks = np.transpose(hist_blocks, axes=hist_blocks_axis_order) + hist_block_assembled_shape = hist_blocks.shape + hist_blocks = hist_blocks.reshape((math.prod(ns_hist), -1)) + + # Calculate actual clip limit + kernel_elements = math.prod(kernel_size) + if clip_limit > 0.0: + clim = int(np.clip(clip_limit * kernel_elements, 1, None)) + else: + # largest possible value, i.e., do not clip (AHE) + clim = kernel_elements + + hist = np.apply_along_axis(np.bincount, -1, hist_blocks, minlength=nbins) + hist = np.apply_along_axis(clip_histogram, -1, hist, clip_limit=clim) + hist = map_histogram(hist, 0, NR_OF_GRAY - 1, kernel_elements) + hist = hist.reshape(hist_block_assembled_shape[:ndim] + (-1,)) + + # duplicate leading mappings in each dim + map_array = np.pad(hist, [[1, 1] for _ in range(ndim)] + [[0, 0]], mode='edge') + + # Perform multilinear interpolation of graylevel mappings + # using the convention described here: + # https://en.wikipedia.org/w/index.php?title=Adaptive_histogram_ + # equalization&oldid=936814673#Efficient_computation_by_interpolation + + # rearrange image into blocks for vectorized processing + ns_proc = [int(s / k) for s, k in zip(image.shape, kernel_size)] + blocks_shape = np.array([ns_proc, kernel_size]).T.flatten() + blocks_axis_order = np.array( + [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)] + ).flatten() + blocks = image.reshape(blocks_shape) + blocks = np.transpose(blocks, axes=blocks_axis_order) + blocks_flattened_shape = blocks.shape + blocks = np.reshape(blocks, (math.prod(ns_proc), math.prod(blocks.shape[ndim:]))) + + # calculate interpolation coefficients + coeffs = np.meshgrid( + *tuple([np.arange(k) / k for k in kernel_size[::-1]]), indexing='ij' + ) + coeffs = [np.transpose(c).flatten() for c in coeffs] + inv_coeffs = [1 - c for dim, c in enumerate(coeffs)] + + # sum over contributions of neighboring contextual + # regions in each direction + result = np.zeros(blocks.shape, dtype=np.float32) + for iedge, edge in enumerate(np.ndindex(*([2] * ndim))): + edge_maps = map_array[tuple([slice(e, e + n) for e, n in zip(edge, ns_proc)])] + edge_maps = edge_maps.reshape((math.prod(ns_proc), -1)) + + # apply map + edge_mapped = np.take_along_axis(edge_maps, blocks, axis=-1) + + # interpolate + edge_coeffs = np.prod( + [[inv_coeffs, coeffs][e][d] for d, e in enumerate(edge[::-1])], 0 + ) + + result += (edge_mapped * edge_coeffs).astype(result.dtype) + + result = result.astype(dtype) + + # rebuild result image from blocks + result = result.reshape(blocks_flattened_shape) + blocks_axis_rebuild_order = np.array( + [np.arange(0, ndim), np.arange(ndim, ndim * 2)] + ).T.flatten() + result = np.transpose(result, axes=blocks_axis_rebuild_order) + result = result.reshape(image.shape) + + # undo padding + unpad_slices = tuple( + [ + slice(p_i, s - p_f) + for p_i, p_f, s in zip(pad_start_per_dim, pad_end_per_dim, image.shape) + ] + ) + result = result[unpad_slices] + + return result + + +def clip_histogram(hist, clip_limit): + """Perform clipping of the histogram and redistribution of bins. + + The histogram is clipped and the number of excess pixels is counted. + Afterwards the excess pixels are equally redistributed across the + whole histogram (providing the bin count is smaller than the cliplimit). + + Parameters + ---------- + hist : ndarray + Histogram array. + clip_limit : int + Maximum allowed bin count. + + Returns + ------- + hist : ndarray + Clipped histogram. + """ + # calculate total number of excess pixels + excess_mask = hist > clip_limit + excess = hist[excess_mask] + n_excess = excess.sum() - excess.size * clip_limit + hist[excess_mask] = clip_limit + + # Second part: clip histogram and redistribute excess pixels in each bin + bin_incr = n_excess // hist.size # average binincrement + upper = clip_limit - bin_incr # Bins larger than upper set to cliplimit + + low_mask = hist < upper + n_excess -= hist[low_mask].size * bin_incr + hist[low_mask] += bin_incr + + mid_mask = np.logical_and(hist >= upper, hist < clip_limit) + mid = hist[mid_mask] + n_excess += mid.sum() - mid.size * clip_limit + hist[mid_mask] = clip_limit + + while n_excess > 0: # Redistribute remaining excess + prev_n_excess = n_excess + for index in range(hist.size): + under_mask = hist < clip_limit + step_size = max(1, np.count_nonzero(under_mask) // n_excess) + under_mask = under_mask[index::step_size] + hist[index::step_size][under_mask] += 1 + n_excess -= np.count_nonzero(under_mask) + if n_excess <= 0: + break + if prev_n_excess == n_excess: + break + + return hist + + +def map_histogram(hist, min_val, max_val, n_pixels): + """Calculate the equalized lookup table (mapping). + + It does so by cumulating the input histogram. + Histogram bins are assumed to be represented by the last array dimension. + + Parameters + ---------- + hist : ndarray + Clipped histogram. + min_val : int + Minimum value for mapping. + max_val : int + Maximum value for mapping. + n_pixels : int + Number of pixels in the region. + + Returns + ------- + out : ndarray + Mapped intensity LUT. + """ + out = np.cumsum(hist, axis=-1).astype(float) + out *= (max_val - min_val) / n_pixels + out += min_val + np.clip(out, a_min=None, a_max=max_val, out=out) + + return out.astype(int) diff --git a/envs/kitoverlay/skimage/exposure/exposure.py b/envs/kitoverlay/skimage/exposure/exposure.py new file mode 100644 index 0000000000000000000000000000000000000000..c154af050219d10523b50b27dfb3a8ea8115b755 --- /dev/null +++ b/envs/kitoverlay/skimage/exposure/exposure.py @@ -0,0 +1,851 @@ +import numpy as np + +from ..util.dtype import dtype_range, dtype_limits +from .._shared import utils + + +__all__ = [ + 'histogram', + 'cumulative_distribution', + 'equalize_hist', + 'rescale_intensity', + 'adjust_gamma', + 'adjust_log', + 'adjust_sigmoid', +] + + +DTYPE_RANGE = dtype_range.copy() +DTYPE_RANGE.update((d.__name__, limits) for d, limits in dtype_range.items()) +DTYPE_RANGE.update( + { + 'uint10': (0, 2**10 - 1), + 'uint12': (0, 2**12 - 1), + 'uint14': (0, 2**14 - 1), + 'bool': dtype_range[bool], + 'float': dtype_range[np.float64], + } +) + + +def _offset_array(arr, low_boundary, high_boundary): + """Offset the array to get the lowest value at 0 if negative.""" + if low_boundary < 0: + offset = low_boundary + dyn_range = high_boundary - low_boundary + # get smallest dtype that can hold both minimum and offset maximum + offset_dtype = np.promote_types( + np.min_scalar_type(dyn_range), np.min_scalar_type(low_boundary) + ) + if arr.dtype != offset_dtype: + # prevent overflow errors when offsetting + arr = arr.astype(offset_dtype) + arr = arr - offset + return arr + + +def _bincount_histogram_centers(image, source_range): + """Compute bin centers for bincount-based histogram.""" + if source_range not in ['image', 'dtype']: + raise ValueError(f'Incorrect value for `source_range` argument: {source_range}') + if source_range == 'image': + image_min = int(image.min().astype(np.int64)) + image_max = int(image.max().astype(np.int64)) + elif source_range == 'dtype': + image_min, image_max = dtype_limits(image, clip_negative=False) + bin_centers = np.arange(image_min, image_max + 1) + return bin_centers + + +def _bincount_histogram(image, source_range, bin_centers=None): + """ + Efficient histogram calculation for an image of integers. + + This function is significantly more efficient than np.histogram but + works only on images of integers. It is based on np.bincount. + + Parameters + ---------- + image : array + Input image. + source_range : {'image', 'dtype'} + 'image' determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + + Returns + ------- + hist : array + The values of the histogram. + bin_centers : array + The values at the center of the bins. + """ + if bin_centers is None: + bin_centers = _bincount_histogram_centers(image, source_range) + image_min, image_max = bin_centers[0], bin_centers[-1] + image = _offset_array(image, image_min, image_max) + hist = np.bincount(image.ravel(), minlength=image_max - min(image_min, 0) + 1) + if source_range == 'image': + idx = max(image_min, 0) + hist = hist[idx:] + return hist, bin_centers + + +def _get_outer_edges(image, hist_range): + """Determine the outer bin edges to use for `numpy.histogram`. + + These are obtained from either the image or hist_range. + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + hist_range : 2-tuple of int or None + Range of values covered by the histogram bins. If None, the minimum + and maximum values of `image` are used. + + Returns + ------- + first_edge, last_edge : int + The range spanned by the histogram bins. + + Notes + ----- + This function is adapted from ``np.lib.histograms._get_outer_edges``. + """ + if hist_range is not None: + first_edge, last_edge = hist_range + if first_edge > last_edge: + raise ValueError("max must be larger than min in hist_range parameter.") + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f'supplied hist_range of [{first_edge}, {last_edge}] is ' f'not finite' + ) + elif image.size == 0: + # handle empty arrays. Can't determine hist_range, so use 0-1. + first_edge, last_edge = 0, 1 + else: + first_edge, last_edge = image.min(), image.max() + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f'autodetected hist_range of [{first_edge}, {last_edge}] is ' + f'not finite' + ) + + # expand empty hist_range to avoid divide by zero + if first_edge == last_edge: + first_edge = first_edge - 0.5 + last_edge = last_edge + 0.5 + + return first_edge, last_edge + + +def _get_bin_edges(image, nbins, hist_range): + """Computes histogram bins for use with `numpy.histogram`. + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + nbins : int + The number of bins. + hist_range : 2-tuple of int + Range of values covered by the histogram bins. + + Returns + ------- + bin_edges : ndarray + The histogram bin edges. + + Notes + ----- + This function is a simplified version of + ``np.lib.histograms._get_bin_edges`` that only supports uniform bins. + """ + first_edge, last_edge = _get_outer_edges(image, hist_range) + # numpy/gh-10322 means that type resolution rules are dependent on array + # shapes. To avoid this causing problems, we pick a type now and stick + # with it throughout. + bin_type = np.result_type(first_edge, last_edge, image) + if np.issubdtype(bin_type, np.integer): + bin_type = np.result_type(bin_type, float) + + # compute bin edges + bin_edges = np.linspace( + first_edge, last_edge, nbins + 1, endpoint=True, dtype=bin_type + ) + return bin_edges + + +def _get_numpy_hist_range(image, source_range): + if source_range == 'image': + hist_range = None + elif source_range == 'dtype': + hist_range = dtype_limits(image, clip_negative=False) + else: + raise ValueError(f'Incorrect value for `source_range` argument: {source_range}') + return hist_range + + +@utils.channel_as_last_axis(multichannel_output=False) +def histogram( + image, nbins=256, source_range='image', normalize=False, *, channel_axis=None +): + """Return histogram of image. + + Unlike `numpy.histogram`, this function returns the centers of bins and + does not rebin integer arrays. For integer arrays, each integer value has + its own bin, which improves speed and intensity-resolution. + + If `channel_axis` is not set, the histogram is computed on the flattened + image. For color or multichannel images, set ``channel_axis`` to use a + common binning for all channels. Alternatively, one may apply the function + separately on each channel to obtain a histogram for each color channel + with separate binning. + + Parameters + ---------- + image : array + Input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + source_range : {'image', 'dtype'}, optional + 'image' (default) determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + normalize : bool, optional + If True, normalize the histogram by the sum of its values. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + hist : array + The values of the histogram. When ``channel_axis`` is not None, hist + will be a 2D array where the first axis corresponds to channels. + bin_centers : array + The values at the center of the bins. + + See Also + -------- + cumulative_distribution + + Examples + -------- + >>> from skimage import data, exposure, img_as_float + >>> image = img_as_float(data.camera()) + >>> np.histogram(image, bins=2) + (array([ 93585, 168559]), array([0. , 0.5, 1. ])) + >>> exposure.histogram(image, nbins=2) + (array([ 93585, 168559]), array([0.25, 0.75])) + """ + sh = image.shape + if len(sh) == 3 and sh[-1] < 4 and channel_axis is None: + utils.warn( + 'This might be a color image. The histogram will be ' + 'computed on the flattened image. You can instead ' + 'apply this function to each color channel, or set ' + 'channel_axis.' + ) + + if channel_axis is not None: + channels = sh[-1] + hist = [] + + # compute bins based on the raveled array + if np.issubdtype(image.dtype, np.integer): + # here bins corresponds to the bin centers + bins = _bincount_histogram_centers(image, source_range) + else: + # determine the bin edges for np.histogram + hist_range = _get_numpy_hist_range(image, source_range) + bins = _get_bin_edges(image, nbins, hist_range) + + for chan in range(channels): + h, bc = _histogram(image[..., chan], bins, source_range, normalize) + hist.append(h) + # Convert to numpy arrays + bin_centers = np.asarray(bc) + hist = np.stack(hist, axis=0) + else: + hist, bin_centers = _histogram(image, nbins, source_range, normalize) + + return hist, bin_centers + + +def _histogram(image, bins, source_range, normalize): + """ + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + bins : int or ndarray + The number of histogram bins. For images with integer dtype, an array + containing the bin centers can also be provided. For images with + floating point dtype, this can be an array of bin_edges for use by + ``np.histogram``. + source_range : {'image', 'dtype'}, optional + 'image' (default) determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + normalize : bool, optional + If True, normalize the histogram by the sum of its values. + """ + + image = image.flatten() + # For integer types, histogramming with bincount is more efficient. + if np.issubdtype(image.dtype, np.integer): + bin_centers = bins if isinstance(bins, np.ndarray) else None + hist, bin_centers = _bincount_histogram(image, source_range, bin_centers) + else: + hist_range = _get_numpy_hist_range(image, source_range) + hist, bin_edges = np.histogram(image, bins=bins, range=hist_range) + bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.0 + + if normalize: + hist = hist / np.sum(hist) + return hist, bin_centers + + +def cumulative_distribution(image, nbins=256): + """Return cumulative distribution function (cdf) for the given image. + + Parameters + ---------- + image : array + Image array. + nbins : int, optional + Number of bins for image histogram. + + Returns + ------- + img_cdf : array + Values of cumulative distribution function. + bin_centers : array + Centers of bins. + + See Also + -------- + histogram + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Cumulative_distribution_function + + Examples + -------- + >>> from skimage import data, exposure, img_as_float + >>> image = img_as_float(data.camera()) + >>> hi = exposure.histogram(image) + >>> cdf = exposure.cumulative_distribution(image) + >>> all(cdf[0] == np.cumsum(hi[0])/float(image.size)) + True + """ + hist, bin_centers = histogram(image, nbins) + img_cdf = hist.cumsum() + img_cdf = img_cdf / float(img_cdf[-1]) + + # cast img_cdf to single precision for float32 or float16 inputs + cdf_dtype = utils._supported_float_type(image.dtype) + img_cdf = img_cdf.astype(cdf_dtype, copy=False) + + return img_cdf, bin_centers + + +def equalize_hist(image, nbins=256, mask=None): + """Return image after histogram equalization. + + Parameters + ---------- + image : array + Image array. + nbins : int, optional + Number of bins for image histogram. Note: this argument is + ignored for integer images, for which each integer is its own + bin. + mask : ndarray of bools or 0s and 1s, optional + Array of same shape as `image`. Only points at which mask == True + are used for the equalization, which is applied to the whole image. + + Returns + ------- + out : float array + Image array after histogram equalization. + + Notes + ----- + This function is adapted from [1]_ with the author's permission. + + References + ---------- + .. [1] http://www.janeriksolem.net/histogram-equalization-with-python-and.html + .. [2] https://en.wikipedia.org/wiki/Histogram_equalization + + """ + if mask is not None: + mask = np.array(mask, dtype=bool) + cdf, bin_centers = cumulative_distribution(image[mask], nbins) + else: + cdf, bin_centers = cumulative_distribution(image, nbins) + out = np.interp(image.flat, bin_centers, cdf) + out = out.reshape(image.shape) + # Unfortunately, np.interp currently always promotes to float64, so we + # have to cast back to single precision when float32 output is desired + return out.astype(utils._supported_float_type(image.dtype), copy=False) + + +def intensity_range(image, range_values='image', clip_negative=False): + """Return image intensity range (min, max) based on desired value type. + + Parameters + ---------- + image : array + Input image. + range_values : str or 2-tuple, optional + The image intensity range is configured by this parameter. + The possible values for this parameter are enumerated below. + + 'image' + Return image min/max as the range. + 'dtype' + Return min/max of the image's dtype as the range. + dtype-name + Return intensity range based on desired `dtype`. Must be valid key + in `DTYPE_RANGE`. Note: `image` is ignored for this range type. + 2-tuple + Return `range_values` as min/max intensities. Note that there's no + reason to use this function if you just want to specify the + intensity range explicitly. This option is included for functions + that use `intensity_range` to support all desired range types. + + clip_negative : bool, optional + If True, clip the negative range (i.e. return 0 for min intensity) + even if the image dtype allows negative values. + """ + if range_values == 'dtype': + range_values = image.dtype.type + + if range_values == 'image': + i_min = np.min(image) + i_max = np.max(image) + elif range_values in DTYPE_RANGE: + i_min, i_max = DTYPE_RANGE[range_values] + if clip_negative: + i_min = 0 + else: + i_min, i_max = range_values + return i_min, i_max + + +def _output_dtype(dtype_or_range, image_dtype): + """Determine the output dtype for rescale_intensity. + + The dtype is determined according to the following rules: + - if ``dtype_or_range`` is a dtype, that is the output dtype. + - if ``dtype_or_range`` is a dtype string, that is the dtype used, unless + it is not a NumPy data type (e.g. 'uint12' for 12-bit unsigned integers), + in which case the data type that can contain it will be used + (e.g. uint16 in this case). + - if ``dtype_or_range`` is a pair of values, the output data type will be + ``_supported_float_type(image_dtype)``. This preserves float32 output for + float32 inputs. + + Parameters + ---------- + dtype_or_range : type, string, or 2-tuple of int/float + The desired range for the output, expressed as either a NumPy dtype or + as a (min, max) pair of numbers. + image_dtype : np.dtype + The input image dtype. + + Returns + ------- + out_dtype : type + The data type appropriate for the desired output. + """ + if type(dtype_or_range) in [list, tuple, np.ndarray]: + # pair of values: always return float. + return utils._supported_float_type(image_dtype) + if type(dtype_or_range) == type: + # already a type: return it + return dtype_or_range + if dtype_or_range in DTYPE_RANGE: + # string key in DTYPE_RANGE dictionary + try: + # if it's a canonical numpy dtype, convert + return np.dtype(dtype_or_range).type + except TypeError: # uint10, uint12, uint14 + # otherwise, return uint16 + return np.uint16 + else: + raise ValueError( + 'Incorrect value for out_range, should be a valid image data ' + f'type or a pair of values, got {dtype_or_range}.' + ) + + +def rescale_intensity(image, in_range='image', out_range='dtype'): + """Return image after stretching or shrinking its intensity levels. + + The desired intensity range of the input and output, `in_range` and + `out_range` respectively, are used to stretch or shrink the intensity range + of the input image. See examples below. + + Parameters + ---------- + image : array + Image array. + in_range, out_range : str or 2-tuple, optional + Min and max intensity values of input and output image. + The possible values for this parameter are enumerated below. + + 'image' + Use image min/max as the intensity range. + 'dtype' + Use min/max of the image's dtype as the intensity range. + dtype-name + Use intensity range based on desired `dtype`. Must be valid key + in `DTYPE_RANGE`. + 2-tuple + Use `range_values` as explicit min/max intensities. + + Returns + ------- + out : array + Image array after rescaling its intensity. This image is the same dtype + as the input image. + + Notes + ----- + .. versionchanged:: 0.17 + The dtype of the output array has changed to match the input dtype, or + float if the output range is specified by a pair of values. + + See Also + -------- + equalize_hist + + Examples + -------- + By default, the min/max intensities of the input image are stretched to + the limits allowed by the image's dtype, since `in_range` defaults to + 'image' and `out_range` defaults to 'dtype': + + >>> image = np.array([51, 102, 153], dtype=np.uint8) + >>> rescale_intensity(image) + array([ 0, 127, 255], dtype=uint8) + + It's easy to accidentally convert an image dtype from uint8 to float: + + >>> 1.0 * image + array([ 51., 102., 153.]) + + Use `rescale_intensity` to rescale to the proper range for float dtypes: + + >>> image_float = 1.0 * image + >>> rescale_intensity(image_float) + array([0. , 0.5, 1. ]) + + To maintain the low contrast of the original, use the `in_range` parameter: + + >>> rescale_intensity(image_float, in_range=(0, 255)) + array([0.2, 0.4, 0.6]) + + If the min/max value of `in_range` is more/less than the min/max image + intensity, then the intensity levels are clipped: + + >>> rescale_intensity(image_float, in_range=(0, 102)) + array([0.5, 1. , 1. ]) + + If you have an image with signed integers but want to rescale the image to + just the positive range, use the `out_range` parameter. In that case, the + output dtype will be float: + + >>> image = np.array([-10, 0, 10], dtype=np.int8) + >>> rescale_intensity(image, out_range=(0, 127)) + array([ 0. , 63.5, 127. ]) + + To get the desired range with a specific dtype, use ``.astype()``: + + >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8) + array([ 0, 63, 127], dtype=int8) + + If the input image is constant, the output will be clipped directly to the + output range: + >>> image = np.array([130, 130, 130], dtype=np.int32) + >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32) + array([127, 127, 127], dtype=int32) + """ + if out_range in ['dtype', 'image']: + out_dtype = _output_dtype(image.dtype.type, image.dtype) + else: + out_dtype = _output_dtype(out_range, image.dtype) + + imin, imax = map(float, intensity_range(image, in_range)) + omin, omax = map( + float, intensity_range(image, out_range, clip_negative=(imin >= 0)) + ) + + if np.any(np.isnan([imin, imax, omin, omax])): + utils.warn( + "One or more intensity levels are NaN. Rescaling will broadcast " + "NaN to the full image. Provide intensity levels yourself to " + "avoid this. E.g. with np.nanmin(image), np.nanmax(image).", + stacklevel=2, + ) + + image = np.clip(image, imin, imax) + + if imin != imax: + image = (image - imin) / (imax - imin) + return (image * (omax - omin) + omin).astype(out_dtype) + else: + return np.clip(image, omin, omax).astype(out_dtype) + + +def _assert_non_negative(image): + if np.any(image < 0): + raise ValueError( + 'Image Correction methods work correctly only on ' + 'images with non-negative values. Use ' + 'skimage.exposure.rescale_intensity.' + ) + + +def _adjust_gamma_u8(image, gamma, gain): + """LUT based implementation of gamma adjustment.""" + lut = 255 * gain * (np.linspace(0, 1, 256) ** gamma) + lut = np.minimum(np.rint(lut), 255).astype('uint8') + return lut[image] + + +def adjust_gamma(image, gamma=1, gain=1): + """Perform gamma correction on the input image. + + Gamma correction is a power-law transform [1]_. This function + transforms the input `image` pixel-wise according to the power law + ``image**gamma`` after scaling each pixel to the range 0 to 1. Then + it is rescaled to its original range and muliplied by `gain`. + + Parameters + ---------- + image : ndarray + Input image. + gamma : float, optional + Non negative real number. Default value is 1. + gain : float, optional + The constant multiplier. Default value is 1. + + Returns + ------- + out : ndarray + Gamma corrected output image. + + See Also + -------- + adjust_log + + Notes + ----- + For gamma greater than 1, the histogram will shift towards left and + the output image will be darker than the input image. + + For gamma less than 1, the histogram will shift towards right and + the output image will be brighter than the input image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gamma_correction + + Examples + -------- + >>> import skimage as ski + >>> image = ski.util.img_as_float(ski.data.moon()) + >>> gamma_corrected = ski.exposure.adjust_gamma(image, 2) + >>> # Output is darker for gamma > 1 + >>> image.mean() > gamma_corrected.mean() + True + """ + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number.") + + dtype = image.dtype.type + + if dtype is np.uint8: + out = _adjust_gamma_u8(image, gamma, gain) + else: + _assert_non_negative(image) + + limits = dtype_limits(image, clip_negative=True) + scale = float(limits[1] - limits[0]) + + out = (((image / scale) ** gamma) * scale * gain).astype(dtype) + + return out + + +def adjust_log(image, gain=1, inv=False): + """Performs Logarithmic correction on the input image. + + This function transforms the input image pixelwise according to the + equation ``O = gain*log(1 + I)`` after scaling each pixel to the range + 0 to 1. For inverse logarithmic correction, the equation is + ``O = gain*(2**I - 1)``. + + Parameters + ---------- + image : ndarray + Input image. + gain : float, optional + The constant multiplier. Default value is 1. + inv : float, optional + If True, it performs inverse logarithmic correction, + else correction will be logarithmic. Defaults to False. + + Returns + ------- + out : ndarray + Logarithm corrected output image. + + See Also + -------- + adjust_gamma + + References + ---------- + .. [1] http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf + + """ + _assert_non_negative(image) + dtype = image.dtype.type + scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0]) + + if inv: + out = (2 ** (image / scale) - 1) * scale * gain + return dtype(out) + + out = np.log2(1 + image / scale) * scale * gain + return out.astype(dtype) + + +def adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False): + """Performs Sigmoid Correction on the input image. + + Also known as Contrast Adjustment. + This function transforms the input image pixelwise according to the + equation ``O = 1/(1 + exp*(gain*(cutoff - I)))`` after scaling each pixel + to the range 0 to 1. + + Parameters + ---------- + image : ndarray + Input image. + cutoff : float, optional + Cutoff of the sigmoid function that shifts the characteristic curve + in horizontal direction. Default value is 0.5. + gain : float, optional + The constant multiplier in exponential's power of sigmoid function. + Default value is 10. + inv : bool, optional + If True, returns the negative sigmoid correction. Defaults to False. + + Returns + ------- + out : ndarray + Sigmoid corrected output image. + + See Also + -------- + adjust_gamma + + References + ---------- + .. [1] Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast + Enhancement Functions", + http://markfairchild.org/PDFs/PAP07.pdf + + """ + _assert_non_negative(image) + dtype = image.dtype.type + scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0]) + + if inv: + out = (1 - 1 / (1 + np.exp(gain * (cutoff - image / scale)))) * scale + return dtype(out) + + out = (1 / (1 + np.exp(gain * (cutoff - image / scale)))) * scale + return out.astype(dtype) + + +def is_low_contrast( + image, + fraction_threshold=0.05, + lower_percentile=1, + upper_percentile=99, + method='linear', +): + """Determine if an image is low contrast. + + Parameters + ---------- + image : array-like + The image under test. + fraction_threshold : float, optional + The low contrast fraction threshold. An image is considered low- + contrast when its range of brightness spans less than this + fraction of its data type's full range. [1]_ + lower_percentile : float, optional + Disregard values below this percentile when computing image contrast. + upper_percentile : float, optional + Disregard values above this percentile when computing image contrast. + method : str, optional + The contrast determination method. Right now the only available + option is "linear". + + Returns + ------- + out : bool + True when the image is determined to be low contrast. + + Notes + ----- + For boolean images, this function returns False only if all values are + the same (the method, threshold, and percentile arguments are ignored). + + References + ---------- + .. [1] https://scikit-image.org/docs/dev/user_guide/data_types.html + + Examples + -------- + >>> image = np.linspace(0, 0.04, 100) + >>> is_low_contrast(image) + True + >>> image[-1] = 1 + >>> is_low_contrast(image) + True + >>> is_low_contrast(image, upper_percentile=100) + False + """ + image = np.asanyarray(image) + + if image.dtype == bool: + return not ((image.max() == 1) and (image.min() == 0)) + + if image.ndim == 3: + from ..color import rgb2gray, rgba2rgb # avoid circular import + + if image.shape[2] == 4: + image = rgba2rgb(image) + if image.shape[2] == 3: + image = rgb2gray(image) + + dlimits = dtype_limits(image, clip_negative=False) + limits = np.percentile(image, [lower_percentile, upper_percentile]) + ratio = (limits[1] - limits[0]) / (dlimits[1] - dlimits[0]) + + return ratio < fraction_threshold diff --git a/envs/kitoverlay/skimage/exposure/histogram_matching.py b/envs/kitoverlay/skimage/exposure/histogram_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..1c475d91a6a84cf20ffbc2f22f095563de56511a --- /dev/null +++ b/envs/kitoverlay/skimage/exposure/histogram_matching.py @@ -0,0 +1,93 @@ +import numpy as np + +from .._shared import utils + + +def _match_cumulative_cdf(source, template): + """ + Return modified source array so that the cumulative density function of + its values matches the cumulative density function of the template. + """ + if source.dtype.kind == 'u': + src_lookup = source.reshape(-1) + src_counts = np.bincount(src_lookup) + tmpl_counts = np.bincount(template.reshape(-1)) + + # omit values where the count was 0 + tmpl_values = np.nonzero(tmpl_counts)[0] + tmpl_counts = tmpl_counts[tmpl_values] + else: + src_values, src_lookup, src_counts = np.unique( + source.reshape(-1), return_inverse=True, return_counts=True + ) + tmpl_values, tmpl_counts = np.unique(template.reshape(-1), return_counts=True) + + # calculate normalized quantiles for each array + src_quantiles = np.cumsum(src_counts) / source.size + tmpl_quantiles = np.cumsum(tmpl_counts) / template.size + + interp_a_values = np.interp(src_quantiles, tmpl_quantiles, tmpl_values) + return interp_a_values[src_lookup].reshape(source.shape) + + +@utils.channel_as_last_axis(channel_arg_positions=(0, 1)) +def match_histograms(image, reference, *, channel_axis=None): + """Adjust an image so that its cumulative histogram matches that of another. + + The adjustment is applied separately for each channel. + + Parameters + ---------- + image : ndarray + Input image. Can be gray-scale or in color. + reference : ndarray + Image to match histogram of. Must have the same number of channels as + image. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + matched : ndarray + Transformed input image. + + Raises + ------ + ValueError + Thrown when the number of channels in the input image and the reference + differ. + + References + ---------- + .. [1] http://paulbourke.net/miscellaneous/equalisation/ + + """ + if image.ndim != reference.ndim: + raise ValueError( + 'Image and reference must have the same number ' 'of channels.' + ) + + if channel_axis is not None: + if image.shape[-1] != reference.shape[-1]: + raise ValueError( + 'Number of channels in the input image and ' + 'reference image must match!' + ) + + matched = np.empty(image.shape, dtype=image.dtype) + for channel in range(image.shape[-1]): + matched_channel = _match_cumulative_cdf( + image[..., channel], reference[..., channel] + ) + matched[..., channel] = matched_channel + else: + # _match_cumulative_cdf will always return float64 due to np.interp + matched = _match_cumulative_cdf(image, reference) + + if matched.dtype.kind == 'f': + # output a float32 result when the input is float16 or float32 + out_dtype = utils._supported_float_type(image.dtype) + matched = matched.astype(out_dtype, copy=False) + return matched diff --git a/envs/kitoverlay/skimage/filters/__init__.py b/envs/kitoverlay/skimage/filters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2777d8f618ffbd6bb478157bd61f4a7d655db251 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/__init__.py @@ -0,0 +1,5 @@ +"""Sharpening, edge finding, rank filters, thresholding, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/filters/__init__.pyi b/envs/kitoverlay/skimage/filters/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5c39465fa80f70b0c76a935cfd03678c9beeb64d --- /dev/null +++ b/envs/kitoverlay/skimage/filters/__init__.pyi @@ -0,0 +1,109 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + "LPIFilter2D", + "apply_hysteresis_threshold", + "butterworth", + "correlate_sparse", + "difference_of_gaussians", + "farid", + "farid_h", + "farid_v", + "filter_inverse", + "filter_forward", + "frangi", + "gabor", + "gabor_kernel", + "gaussian", + "hessian", + "laplace", + "median", + "meijering", + "prewitt", + "prewitt_h", + "prewitt_v", + "rank", + "rank_order", + "roberts", + "roberts_neg_diag", + "roberts_pos_diag", + "sato", + "scharr", + "scharr_h", + "scharr_v", + "sobel", + "sobel_h", + "sobel_v", + "threshold_isodata", + "threshold_li", + "threshold_local", + "threshold_mean", + "threshold_minimum", + "threshold_multiotsu", + "threshold_niblack", + "threshold_otsu", + "threshold_sauvola", + "threshold_triangle", + "threshold_yen", + "try_all_threshold", + "unsharp_mask", + "wiener", + "window", +] + +from . import rank +from ._fft_based import butterworth +from ._gabor import gabor, gabor_kernel +from ._gaussian import difference_of_gaussians, gaussian +from ._median import median +from ._rank_order import rank_order +from ._sparse import correlate_sparse +from ._unsharp_mask import unsharp_mask +from ._window import window +from .edges import ( + farid, + farid_h, + farid_v, + laplace, + prewitt, + prewitt_h, + prewitt_v, + roberts, + roberts_neg_diag, + roberts_pos_diag, + scharr, + scharr_h, + scharr_v, + sobel, + sobel_h, + sobel_v, +) +from .lpi_filter import ( + LPIFilter2D, + filter_inverse, + filter_forward, + wiener, +) +from .ridges import ( + frangi, + hessian, + meijering, + sato, +) +from .thresholding import ( + apply_hysteresis_threshold, + threshold_isodata, + threshold_li, + threshold_local, + threshold_mean, + threshold_minimum, + threshold_multiotsu, + threshold_niblack, + threshold_otsu, + threshold_sauvola, + threshold_triangle, + threshold_yen, + try_all_threshold, +) diff --git a/envs/kitoverlay/skimage/filters/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cc2543cb0e9a445ce60788a2ff6c9f13e29ded3 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_fft_based.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_fft_based.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d28fb0ae4db96767d498e689efda5c295d6966c Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_fft_based.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_gabor.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_gabor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e60c9e56d54906ce5e7354f3fc4f5ce24c808d96 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_gabor.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_gaussian.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_gaussian.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b74602be64760a7dea2619d1cdd9094a9f5fad2 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_gaussian.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_median.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_median.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..126dd98702ba59766a1a7649eefb3943d279fbec Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_median.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_rank_order.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_rank_order.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b868b0c84e468dcf91478e4ba2cf9445661f1b0 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_rank_order.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_sparse.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_sparse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6905119f1e46c85484c8650fab58181228372dae Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_sparse.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_unsharp_mask.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_unsharp_mask.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..138dab50d1b40c222c9cb6d954eba21aa11bdb3c Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_unsharp_mask.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/_window.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/_window.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba6d0e2d166c257cce22d06a1ec5cce3c3b24c4 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/_window.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/edges.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/edges.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afe3c77869bcc59dc05b539c16ee35e8ea82e0ee Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/edges.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/lpi_filter.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/lpi_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d73807b3f744a904ffe161e31cdb5980b4f0a8ce Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/lpi_filter.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/ridges.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/ridges.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fef9614c89ddc9edab097033a9792cdd1ffcd991 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/ridges.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/__pycache__/thresholding.cpython-311.pyc b/envs/kitoverlay/skimage/filters/__pycache__/thresholding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4551a0288e485f91aa058dbd0782ee73f122bb7 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/__pycache__/thresholding.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/_fft_based.py b/envs/kitoverlay/skimage/filters/_fft_based.py new file mode 100644 index 0000000000000000000000000000000000000000..12af9a44283f6121cb8c3967e005e8a64689d221 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_fft_based.py @@ -0,0 +1,189 @@ +import functools + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type + + +def _get_nd_butterworth_filter( + shape, factor, order, high_pass, real, dtype=np.float64, squared_butterworth=True +): + """Create a N-dimensional Butterworth mask for an FFT + + Parameters + ---------- + shape : tuple of int + Shape of the n-dimensional FFT and mask. + factor : float + Fraction of mask dimensions where the cutoff should be. + order : float + Controls the slope in the cutoff region. + high_pass : bool + Whether the filter is high pass (low frequencies attenuated) or + low pass (high frequencies are attenuated). + real : bool + Whether the FFT is of a real (True) or complex (False) image + squared_butterworth : bool, optional + When True, the square of the Butterworth filter is used. + + Returns + ------- + wfilt : ndarray + The FFT mask. + + """ + ranges = [] + for i, d in enumerate(shape): + # start and stop ensures center of mask aligns with center of FFT + axis = np.arange(-(d - 1) // 2, (d - 1) // 2 + 1) / (d * factor) + ranges.append(fft.ifftshift(axis**2)) + # for real image FFT, halve the last axis + if real: + limit = d // 2 + 1 + ranges[-1] = ranges[-1][:limit] + # q2 = squared Euclidean distance grid + q2 = functools.reduce(np.add, np.meshgrid(*ranges, indexing="ij", sparse=True)) + q2 = q2.astype(dtype) + q2 = np.power(q2, order) + wfilt = 1 / (1 + q2) + if high_pass: + wfilt *= q2 + if not squared_butterworth: + np.sqrt(wfilt, out=wfilt) + return wfilt + + +def butterworth( + image, + cutoff_frequency_ratio=0.005, + high_pass=True, + order=2.0, + channel_axis=None, + *, + squared_butterworth=True, + npad=0, +): + """Apply a Butterworth filter to enhance high or low frequency features. + + This filter is defined in the Fourier domain. + + Parameters + ---------- + image : (M[, N[, ..., P]][, C]) ndarray + Input image. + cutoff_frequency_ratio : float, optional + Determines the position of the cut-off relative to the shape of the + FFT. Receives a value between [0, 0.5]. + high_pass : bool, optional + Whether to perform a high pass filter. If False, a low pass filter is + performed. + order : float, optional + Order of the filter which affects the slope near the cut-off. Higher + order means steeper slope in frequency space. + channel_axis : int, optional + If there is a channel dimension, provide the index here. If None + (default) then all axes are assumed to be spatial dimensions. + squared_butterworth : bool, optional + When True, the square of a Butterworth filter is used. See notes below + for more details. + npad : int, optional + Pad each edge of the image by `npad` pixels using `numpy.pad`'s + ``mode='edge'`` extension. + + Returns + ------- + result : ndarray + The Butterworth-filtered image. + + Notes + ----- + A band-pass filter can be achieved by combining a high-pass and low-pass + filter. The user can increase `npad` if boundary artifacts are apparent. + + The "Butterworth filter" used in image processing textbooks (e.g. [1]_, + [2]_) is often the square of the traditional Butterworth filters as + described by [3]_, [4]_. The squared version will be used here if + `squared_butterworth` is set to ``True``. The lowpass, squared Butterworth + filter is given by the following expression for the lowpass case: + + .. math:: + H_{low}(f) = \\frac{1}{1 + \\left(\\frac{f}{c f_s}\\right)^{2n}} + + with the highpass case given by + + .. math:: + H_{hi}(f) = 1 - H_{low}(f) + + where :math:`f=\\sqrt{\\sum_{d=0}^{\\mathrm{ndim}} f_{d}^{2}}` is the + absolute value of the spatial frequency, :math:`f_s` is the sampling + frequency, :math:`c` the ``cutoff_frequency_ratio``, and :math:`n` is the + filter `order` [1]_. When ``squared_butterworth=False``, the square root of + the above expressions are used instead. + + Note that ``cutoff_frequency_ratio`` is defined in terms of the sampling + frequency, :math:`f_s`. The FFT spectrum covers the Nyquist range + (:math:`[-f_s/2, f_s/2]`) so ``cutoff_frequency_ratio`` should have a value + between 0 and 0.5. The frequency response (gain) at the cutoff is 0.5 when + ``squared_butterworth`` is true and :math:`1/\\sqrt{2}` when it is false. + + Examples + -------- + Apply a high-pass and low-pass Butterworth filter to a grayscale and + color image respectively: + + >>> from skimage.data import camera, astronaut + >>> from skimage.filters import butterworth + >>> high_pass = butterworth(camera(), 0.07, True, 8) + >>> low_pass = butterworth(astronaut(), 0.01, False, 4, channel_axis=-1) + + References + ---------- + .. [1] Russ, John C., et al. The Image Processing Handbook, 3rd. Ed. + 1999, CRC Press, LLC. + .. [2] Birchfield, Stan. Image Processing and Analysis. 2018. Cengage + Learning. + .. [3] Butterworth, Stephen. "On the theory of filter amplifiers." + Wireless Engineer 7.6 (1930): 536-541. + .. [4] https://en.wikipedia.org/wiki/Butterworth_filter + + """ + if npad < 0: + raise ValueError("npad must be >= 0") + elif npad > 0: + center_slice = tuple(slice(npad, s + npad) for s in image.shape) + image = np.pad(image, npad, mode='edge') + fft_shape = ( + image.shape if channel_axis is None else np.delete(image.shape, channel_axis) + ) + is_real = np.isrealobj(image) + float_dtype = _supported_float_type(image.dtype, allow_complex=True) + if cutoff_frequency_ratio < 0 or cutoff_frequency_ratio > 0.5: + raise ValueError("cutoff_frequency_ratio should be in the range [0, 0.5]") + wfilt = _get_nd_butterworth_filter( + fft_shape, + cutoff_frequency_ratio, + order, + high_pass, + is_real, + float_dtype, + squared_butterworth, + ) + axes = np.arange(image.ndim) + if channel_axis is not None: + axes = np.delete(axes, channel_axis) + abs_channel = channel_axis % image.ndim + post = image.ndim - abs_channel - 1 + sl = (slice(None),) * abs_channel + (np.newaxis,) + (slice(None),) * post + wfilt = wfilt[sl] + if is_real: + butterfilt = fft.irfftn( + wfilt * fft.rfftn(image, axes=axes), s=fft_shape, axes=axes + ) + else: + butterfilt = fft.ifftn( + wfilt * fft.fftn(image, axes=axes), s=fft_shape, axes=axes + ) + if npad > 0: + butterfilt = butterfilt[center_slice] + return butterfilt diff --git a/envs/kitoverlay/skimage/filters/_gabor.py b/envs/kitoverlay/skimage/filters/_gabor.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e035b7fc2c8fd29f7a2d33efb92d92274b5cd7 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_gabor.py @@ -0,0 +1,220 @@ +import math + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type, check_nD + +__all__ = ['gabor_kernel', 'gabor'] + + +def _sigma_prefactor(bandwidth): + b = bandwidth + # See http://www.cs.rug.nl/~imaging/simplecell.html + return 1.0 / np.pi * math.sqrt(math.log(2) / 2.0) * (2.0**b + 1) / (2.0**b - 1) + + +def gabor_kernel( + frequency, + theta=0, + bandwidth=1, + sigma_x=None, + sigma_y=None, + n_stds=3, + offset=0, + dtype=np.complex128, +): + """Return complex 2D Gabor filter kernel. + + Gabor kernel is a Gaussian kernel modulated by a complex harmonic function. + Harmonic function consists of an imaginary sine function and a real + cosine function. Spatial frequency is inversely proportional to the + wavelength of the harmonic and to the standard deviation of a Gaussian + kernel. The bandwidth is also inversely proportional to the standard + deviation. + + Parameters + ---------- + frequency : float + Spatial frequency of the harmonic function. Specified in pixels. + theta : float, optional + Orientation in radians. If 0, the harmonic is in the x-direction. + bandwidth : float, optional + The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x`` + and ``sigma_y`` will decrease with increasing frequency. This value is + ignored if ``sigma_x`` and ``sigma_y`` are set by the user. + sigma_x, sigma_y : float, optional + Standard deviation in x- and y-directions. These directions apply to + the kernel *before* rotation. If `theta = pi/2`, then the kernel is + rotated 90 degrees so that ``sigma_x`` controls the *vertical* + direction. + n_stds : scalar, optional + The linear size of the kernel is n_stds (3 by default) standard + deviations + offset : float, optional + Phase offset of harmonic function in radians. + dtype : {np.complex64, np.complex128} + Specifies if the filter is single or double precision complex. + + Returns + ------- + g : complex array + Complex filter kernel. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gabor_filter + .. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf + + Examples + -------- + >>> from skimage.filters import gabor_kernel + >>> from matplotlib import pyplot as plt # doctest: +SKIP + + >>> gk = gabor_kernel(frequency=0.2) + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(gk.real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + >>> # more ripples (equivalent to increasing the size of the + >>> # Gaussian spread) + >>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1) + >>> fig, ax = plt.suplots() # doctest: +SKIP + >>> ax.imshow(gk.real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + if sigma_x is None: + sigma_x = _sigma_prefactor(bandwidth) / frequency + if sigma_y is None: + sigma_y = _sigma_prefactor(bandwidth) / frequency + + if np.dtype(dtype).kind != 'c': + raise ValueError("dtype must be complex") + + ct = math.cos(theta) + st = math.sin(theta) + x0 = math.ceil(max(abs(n_stds * sigma_x * ct), abs(n_stds * sigma_y * st), 1)) + y0 = math.ceil(max(abs(n_stds * sigma_y * ct), abs(n_stds * sigma_x * st), 1)) + y, x = np.meshgrid( + np.arange(-y0, y0 + 1), np.arange(-x0, x0 + 1), indexing='ij', sparse=True + ) + rotx = x * ct + y * st + roty = -x * st + y * ct + + g = np.empty(roty.shape, dtype=dtype) + np.exp( + -0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2) + + 1j * (2 * np.pi * frequency * rotx + offset), + out=g, + ) + g *= 1 / (2 * np.pi * sigma_x * sigma_y) + + return g + + +def gabor( + image, + frequency, + theta=0, + bandwidth=1, + sigma_x=None, + sigma_y=None, + n_stds=3, + offset=0, + mode='reflect', + cval=0, +): + """Return real and imaginary responses to Gabor filter. + + The real and imaginary parts of the Gabor filter kernel are applied to the + image and the response is returned as a pair of arrays. + + Gabor filter is a linear filter with a Gaussian kernel which is modulated + by a sinusoidal plane wave. Frequency and orientation representations of + the Gabor filter are similar to those of the human visual system. + Gabor filter banks are commonly used in computer vision and image + processing. They are especially suitable for edge detection and texture + classification. + + Parameters + ---------- + image : 2-D array + Input image. + frequency : float + Spatial frequency of the harmonic function. Specified in pixels. + theta : float, optional + Orientation in radians. If 0, the harmonic is in the x-direction. + bandwidth : float, optional + The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x`` + and ``sigma_y`` will decrease with increasing frequency. This value is + ignored if ``sigma_x`` and ``sigma_y`` are set by the user. + sigma_x, sigma_y : float, optional + Standard deviation in x- and y-directions. These directions apply to + the kernel *before* rotation. If `theta = pi/2`, then the kernel is + rotated 90 degrees so that ``sigma_x`` controls the *vertical* + direction. + n_stds : scalar, optional + The linear size of the kernel is n_stds (3 by default) standard + deviations. + offset : float, optional + Phase offset of harmonic function in radians. + mode : {'constant', 'nearest', 'reflect', 'mirror', 'wrap'}, optional + Mode used to convolve image with a kernel, passed to `ndi.convolve` + cval : scalar, optional + Value to fill past edges of input if ``mode`` of convolution is + 'constant'. The parameter is passed to `ndi.convolve`. + + Returns + ------- + real, imag : arrays + Filtered images using the real and imaginary parts of the Gabor filter + kernel. Images are of the same dimensions as the input one. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gabor_filter + .. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf + + Examples + -------- + >>> from skimage.filters import gabor + >>> from skimage import data + >>> from matplotlib import pyplot as plt # doctest: +SKIP + + >>> image = data.coins() + >>> # detecting edges in a coin image + >>> filt_real, filt_imag = gabor(image, frequency=0.6) + >>> fix, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(filt_real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + >>> # less sensitivity to finer details with the lower frequency kernel + >>> filt_real, filt_imag = gabor(image, frequency=0.1) + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(filt_real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + check_nD(image, 2) + # do not cast integer types to float! + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + kernel_dtype = np.promote_types(image.dtype, np.complex64) + else: + kernel_dtype = np.complex128 + + g = gabor_kernel( + frequency, + theta, + bandwidth, + sigma_x, + sigma_y, + n_stds, + offset, + dtype=kernel_dtype, + ) + + filtered_real = ndi.convolve(image, np.real(g), mode=mode, cval=cval) + filtered_imag = ndi.convolve(image, np.imag(g), mode=mode, cval=cval) + + return filtered_real, filtered_imag diff --git a/envs/kitoverlay/skimage/filters/_gaussian.py b/envs/kitoverlay/skimage/filters/_gaussian.py new file mode 100644 index 0000000000000000000000000000000000000000..193b77dc67e611b23e3d5c33ab30bad19fa527e9 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_gaussian.py @@ -0,0 +1,168 @@ +import numpy as np + +from .._shared.filters import gaussian +from ..util import img_as_float + +__all__ = ['gaussian', 'difference_of_gaussians'] + + +def difference_of_gaussians( + image, + low_sigma, + high_sigma=None, + *, + mode='nearest', + cval=0, + channel_axis=None, + truncate=4.0, +): + """Find features between ``low_sigma`` and ``high_sigma`` in size. + + This function uses the Difference of Gaussians method for applying + band-pass filters to multi-dimensional arrays. The input array is + blurred with two Gaussian kernels of differing sigmas to produce two + intermediate, filtered images. The more-blurred image is then subtracted + from the less-blurred image. The final output image will therefore have + had high-frequency components attenuated by the smaller-sigma Gaussian, and + low frequency components will have been removed due to their presence in + the more-blurred intermediate. + + Parameters + ---------- + image : ndarray + Input array to filter. + low_sigma : scalar or sequence of scalars + Standard deviation(s) for the Gaussian kernel with the smaller sigmas + across all axes. The standard deviations are given for each axis as a + sequence, or as a single number, in which case the single number is + used as the standard deviation value for all axes. + high_sigma : scalar or sequence of scalars, optional (default is None) + Standard deviation(s) for the Gaussian kernel with the larger sigmas + across all axes. The standard deviations are given for each axis as a + sequence, or as a single number, in which case the single number is + used as the standard deviation value for all axes. If None is given + (default), sigmas for all axes are calculated as 1.6 * low_sigma. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The ``mode`` parameter determines how the array borders are + handled, where ``cval`` is the value when mode is equal to + 'constant'. Default is 'nearest'. + cval : scalar, optional + Value to fill past edges of input if ``mode`` is 'constant'. Default + is 0.0 + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + truncate : float, optional (default is 4.0) + Truncate the filter at this many standard deviations. + + Returns + ------- + filtered_image : ndarray + the filtered array. + + See also + -------- + skimage.feature.blob_dog + + Notes + ----- + This function will subtract an array filtered with a Gaussian kernel + with sigmas given by ``high_sigma`` from an array filtered with a + Gaussian kernel with sigmas provided by ``low_sigma``. The values for + ``high_sigma`` must always be greater than or equal to the corresponding + values in ``low_sigma``, or a ``ValueError`` will be raised. + + When ``high_sigma`` is none, the values for ``high_sigma`` will be + calculated as 1.6x the corresponding values in ``low_sigma``. This ratio + was originally proposed by Marr and Hildreth (1980) [1]_ and is commonly + used when approximating the inverted Laplacian of Gaussian, which is used + in edge and blob detection. + + Input image is converted according to the conventions of ``img_as_float``. + + Except for sigma values, all parameters are used for both filters. + + Examples + -------- + Apply a simple Difference of Gaussians filter to a color image: + + >>> from skimage.data import astronaut + >>> from skimage.filters import difference_of_gaussians + >>> filtered_image = difference_of_gaussians(astronaut(), 2, 10, + ... channel_axis=-1) + + Apply a Laplacian of Gaussian filter as approximated by the Difference + of Gaussians filter: + + >>> filtered_image = difference_of_gaussians(astronaut(), 2, + ... channel_axis=-1) + + Apply a Difference of Gaussians filter to a grayscale image using different + sigma values for each axis: + + >>> from skimage.data import camera + >>> filtered_image = difference_of_gaussians(camera(), (2,5), (3,20)) + + References + ---------- + .. [1] Marr, D. and Hildreth, E. Theory of Edge Detection. Proc. R. Soc. + Lond. Series B 207, 187-217 (1980). + https://doi.org/10.1098/rspb.1980.0020 + + """ + image = img_as_float(image) + low_sigma = np.array(low_sigma, dtype='float', ndmin=1) + if high_sigma is None: + high_sigma = low_sigma * 1.6 + else: + high_sigma = np.array(high_sigma, dtype='float', ndmin=1) + + if channel_axis is not None: + spatial_dims = image.ndim - 1 + else: + spatial_dims = image.ndim + + if len(low_sigma) != 1 and len(low_sigma) != spatial_dims: + raise ValueError( + 'low_sigma must have length equal to number of' + ' spatial dimensions of input' + ) + if len(high_sigma) != 1 and len(high_sigma) != spatial_dims: + raise ValueError( + 'high_sigma must have length equal to number of' + ' spatial dimensions of input' + ) + + low_sigma = low_sigma * np.ones(spatial_dims) + high_sigma = high_sigma * np.ones(spatial_dims) + + if any(high_sigma < low_sigma): + raise ValueError( + 'high_sigma must be equal to or larger than' 'low_sigma for all axes' + ) + + im1 = gaussian( + image, + sigma=low_sigma, + mode=mode, + cval=cval, + channel_axis=channel_axis, + truncate=truncate, + preserve_range=False, + ) + + im2 = gaussian( + image, + sigma=high_sigma, + mode=mode, + cval=cval, + channel_axis=channel_axis, + truncate=truncate, + preserve_range=False, + ) + + return im1 - im2 diff --git a/envs/kitoverlay/skimage/filters/_median.py b/envs/kitoverlay/skimage/filters/_median.py new file mode 100644 index 0000000000000000000000000000000000000000..9850b23f1427c003ec75e4398891ff9ce9d7bda7 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_median.py @@ -0,0 +1,82 @@ +from warnings import warn + +import numpy as np +from scipy import ndimage as ndi + +from .rank import generic + + +def median( + image, footprint=None, out=None, mode='nearest', cval=0.0, behavior='ndimage' +): + """Return local median of an image. + + Parameters + ---------- + image : array-like + Input image. + footprint : ndarray, optional + If ``behavior=='rank'``, ``footprint`` is a 2-D array of 1's and 0's. + If ``behavior=='ndimage'``, ``footprint`` is a N-D array of 1's and 0's + with the same number of dimension than ``image``. + If None, ``footprint`` will be a N-D array with 3 elements for each + dimension (e.g., vector, square, cube, etc.) + out : ndarray, (same dtype as image), optional + If None, a new array is allocated. + mode : {'reflect', 'constant', 'nearest', 'mirror','‘wrap'}, optional + The mode parameter determines how the array borders are handled, where + ``cval`` is the value when mode is equal to 'constant'. + Default is 'nearest'. + + .. versionadded:: 0.15 + ``mode`` is used when ``behavior='ndimage'``. + cval : scalar, optional + Value to fill past edges of input if mode is 'constant'. Default is 0.0 + + .. versionadded:: 0.15 + ``cval`` was added in 0.15 is used when ``behavior='ndimage'``. + behavior : {'ndimage', 'rank'}, optional + Either to use the old behavior (i.e., < 0.15) or the new behavior. + The old behavior will call the :func:`skimage.filters.rank.median`. + The new behavior will call the :func:`scipy.ndimage.median_filter`. + Default is 'ndimage'. + + .. versionadded:: 0.15 + ``behavior`` is introduced in 0.15 + .. versionchanged:: 0.16 + Default ``behavior`` has been changed from 'rank' to 'ndimage' + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + See also + -------- + skimage.filters.rank.median : Rank-based implementation of the median + filtering offering more flexibility with additional parameters but + dedicated for unsigned integer images. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk + >>> from skimage.filters import median + >>> img = data.camera() + >>> med = median(img, disk(5)) + + """ + if behavior == 'rank': + if mode != 'nearest' or not np.isclose(cval, 0.0): + warn( + "Change 'behavior' to 'ndimage' if you want to use the " + "parameters 'mode' or 'cval'. They will be discarded " + "otherwise.", + stacklevel=2, + ) + return generic.median(image, footprint=footprint, out=out) + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, image.ndim) + return ndi.median_filter( + image, footprint=footprint, output=out, mode=mode, cval=cval + ) diff --git a/envs/kitoverlay/skimage/filters/_rank_order.py b/envs/kitoverlay/skimage/filters/_rank_order.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4ba888a2454a1dbf854cf07a8c0b9e08c04f70 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_rank_order.py @@ -0,0 +1,57 @@ +""" +_rank_order.py - convert an image of any type to an image of ints whose +pixels have an identical rank order compared to the original image +""" + +import numpy as np + + +def rank_order(image): + """Return an image of the same shape where each pixel is the + index of the pixel value in the ascending order of the unique + values of ``image``, aka the rank-order value. + + Parameters + ---------- + image : ndarray + + Returns + ------- + labels : ndarray of unsigned integers, of shape image.shape + New array where each pixel has the rank-order value of the + corresponding pixel in ``image``. Pixel values are between 0 and + n - 1, where n is the number of distinct unique values in + ``image``. The dtype of this array will be determined by + ``np.min_scalar_type(image.size)``. + original_values : 1-D ndarray + Unique original values of ``image``. This will have the same dtype as + ``image``. + + Examples + -------- + >>> a = np.array([[1, 4, 5], [4, 4, 1], [5, 1, 1]]) + >>> a + array([[1, 4, 5], + [4, 4, 1], + [5, 1, 1]]) + >>> rank_order(a) + (array([[0, 1, 2], + [1, 1, 0], + [2, 0, 0]], dtype=uint8), array([1, 4, 5])) + >>> b = np.array([-1., 2.5, 3.1, 2.5]) + >>> rank_order(b) + (array([0, 1, 2, 1], dtype=uint8), array([-1. , 2.5, 3.1])) + """ + flat_image = image.reshape(-1) + unsigned_dtype = np.min_scalar_type(flat_image.size) + sort_order = flat_image.argsort().astype(unsigned_dtype, copy=False) + flat_image = flat_image[sort_order] + sort_rank = np.zeros_like(sort_order) + is_different = flat_image[:-1] != flat_image[1:] + np.cumsum(is_different, out=sort_rank[1:], dtype=sort_rank.dtype) + original_values = np.zeros((int(sort_rank[-1]) + 1,), image.dtype) + original_values[0] = flat_image[0] + original_values[1:] = flat_image[1:][is_different] + int_image = np.zeros_like(sort_order) + int_image[sort_order] = sort_rank + return (int_image.reshape(image.shape), original_values) diff --git a/envs/kitoverlay/skimage/filters/_sparse.py b/envs/kitoverlay/skimage/filters/_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..58db5efb3aa882f460c706b8e098ea49c3597987 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_sparse.py @@ -0,0 +1,139 @@ +import numpy as np + +from .._shared.utils import _supported_float_type, _to_np_mode + + +def _validate_window_size(axis_sizes): + """Ensure all sizes in ``axis_sizes`` are odd. + + Parameters + ---------- + axis_sizes : iterable of int + + Raises + ------ + ValueError + If any given axis size is even. + """ + for axis_size in axis_sizes: + if axis_size % 2 == 0: + msg = ( + f'Window size for `threshold_sauvola` or ' + f'`threshold_niblack` must not be even on any dimension. ' + f'Got {axis_sizes}' + ) + raise ValueError(msg) + + +def _get_view(padded, kernel_shape, idx, val): + """Get a view into `padded` that is offset by `idx` and scaled by `val`. + + If `padded` was created by padding the original image by `kernel_shape` as + in correlate_sparse, then the view created here will match the size of the + original image. + """ + sl_shift = tuple( + [ + slice(c, s - (w_ - 1 - c)) + for c, w_, s in zip(idx, kernel_shape, padded.shape) + ] + ) + v = padded[sl_shift] + if val == 1: + return v + return val * v + + +def _correlate_sparse(image, kernel_shape, kernel_indices, kernel_values): + """Perform correlation with a sparse kernel. + + Parameters + ---------- + image : ndarray + The (prepadded) image to be correlated. + kernel_shape : tuple of int + The shape of the sparse filter kernel. + kernel_indices : list of coordinate tuples + The indices of each non-zero kernel entry. + kernel_values : list of float + The kernel values at each location in kernel_indices. + + Returns + ------- + out : ndarray + The filtered image. + + Notes + ----- + This function only returns results for the 'valid' region of the + convolution, and thus `out` will be smaller than `image` by an amount + equal to the kernel size along each axis. + """ + idx, val = kernel_indices[0], kernel_values[0] + # implementation assumes this corner is first in kernel_indices_in_values + if tuple(idx) != (0,) * image.ndim: + raise RuntimeError("Unexpected initial index in kernel_indices") + # make a copy to avoid modifying the input image + out = _get_view(image, kernel_shape, idx, val).copy() + for idx, val in zip(kernel_indices[1:], kernel_values[1:]): + out += _get_view(image, kernel_shape, idx, val) + return out + + +def correlate_sparse(image, kernel, mode='reflect'): + """Compute valid cross-correlation of `padded_array` and `kernel`. + + This function is *fast* when `kernel` is large with many zeros. + + See ``scipy.ndimage.correlate`` for a description of cross-correlation. + + Parameters + ---------- + image : ndarray, dtype float, shape (M, N[, ...], P) + The input array. If mode is 'valid', this array should already be + padded, as a margin of the same shape as kernel will be stripped + off. + kernel : ndarray, dtype float, shape (Q, R[, ...], S) + The kernel to be correlated. Must have the same number of + dimensions as `padded_array`. For high performance, it should + be sparse (few nonzero entries). + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap', 'valid'}, optional + See `scipy.ndimage.correlate` for valid modes. + Additionally, mode 'valid' is accepted, in which case no padding is + applied and the result is the result for the smaller image for which + the kernel is entirely inside the original data. + + Returns + ------- + result : array of float, shape (M, N[, ...], P) + The result of cross-correlating `image` with `kernel`. If mode + 'valid' is used, the resulting shape is (M-Q+1, N-R+1[, ...], P-S+1). + """ + kernel = np.asarray(kernel) + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if mode == 'valid': + padded_image = image + else: + np_mode = _to_np_mode(mode) + _validate_window_size(kernel.shape) + padded_image = np.pad( + image, + [(w // 2, w // 2) for w in kernel.shape], + mode=np_mode, + ) + + # extract the kernel's non-zero indices and corresponding values + indices = np.nonzero(kernel) + values = list(kernel[indices].astype(float_dtype, copy=False)) + indices = list(zip(*indices)) + + # _correlate_sparse requires an index at (0,) * kernel.ndim to be present + corner_index = (0,) * kernel.ndim + if corner_index not in indices: + indices = [corner_index] + indices + values = [0.0] + values + + return _correlate_sparse(padded_image, kernel.shape, indices, values) diff --git a/envs/kitoverlay/skimage/filters/_unsharp_mask.py b/envs/kitoverlay/skimage/filters/_unsharp_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebf2f90f0aaa9587e487098baea538cdf4217e1 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_unsharp_mask.py @@ -0,0 +1,141 @@ +import numpy as np + +from ..util.dtype import img_as_float +from .._shared import utils +from .._shared.filters import gaussian + + +def _unsharp_mask_single_channel(image, radius, amount, vrange): + """Single channel implementation of the unsharp masking filter.""" + + blurred = gaussian(image, sigma=radius, mode='reflect') + + result = image + (image - blurred) * amount + if vrange is not None: + return np.clip(result, vrange[0], vrange[1], out=result) + return result + + +def unsharp_mask( + image, radius=1.0, amount=1.0, preserve_range=False, *, channel_axis=None +): + """Unsharp masking filter. + + The sharp details are identified as the difference between the original + image and its blurred version. These details are then scaled, and added + back to the original image. + + Parameters + ---------- + image : (M[, ...][, C]) ndarray + Input image. + radius : scalar or sequence of scalars, optional + If a scalar is given, then its value is used for all dimensions. + If sequence is given, then there must be exactly one radius + for each dimension except the last dimension for multichannel images. + Note that 0 radius means no blurring, and negative values are + not allowed. + amount : scalar, optional + The details will be amplified with this factor. The factor could be 0 + or negative. Typically, it is a small positive number, e.g. 1.0. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of ``img_as_float``. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + output : (M[, ...][, C]) ndarray of float + Image with unsharp mask applied. + + Notes + ----- + Unsharp masking is an image sharpening technique. It is a linear image + operation, and numerically stable, unlike deconvolution which is an + ill-posed problem. Because of this stability, it is often + preferred over deconvolution. + + The main idea is as follows: sharp details are identified as the + difference between the original image and its blurred version. + These details are added back to the original image after a scaling step: + + enhanced image = original + amount * (original - blurred) + + When applying this filter to several color layers independently, + color bleeding may occur. More visually pleasing result can be + achieved by processing only the brightness/lightness/intensity + channel in a suitable color space such as HSV, HSL, YUV, or YCbCr. + + Unsharp masking is described in most introductory digital image + processing books. This implementation is based on [1]_. + + Examples + -------- + >>> array = np.ones(shape=(5,5), dtype=np.uint8)*100 + >>> array[2,2] = 120 + >>> array + array([[100, 100, 100, 100, 100], + [100, 100, 100, 100, 100], + [100, 100, 120, 100, 100], + [100, 100, 100, 100, 100], + [100, 100, 100, 100, 100]], dtype=uint8) + >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) + array([[0.39, 0.39, 0.39, 0.39, 0.39], + [0.39, 0.39, 0.38, 0.39, 0.39], + [0.39, 0.38, 0.53, 0.38, 0.39], + [0.39, 0.39, 0.38, 0.39, 0.39], + [0.39, 0.39, 0.39, 0.39, 0.39]]) + + >>> array = np.ones(shape=(5,5), dtype=np.int8)*100 + >>> array[2,2] = 127 + >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) + array([[0.79, 0.79, 0.79, 0.79, 0.79], + [0.79, 0.78, 0.75, 0.78, 0.79], + [0.79, 0.75, 1. , 0.75, 0.79], + [0.79, 0.78, 0.75, 0.78, 0.79], + [0.79, 0.79, 0.79, 0.79, 0.79]]) + + >>> np.around(unsharp_mask(array, radius=0.5, amount=2, preserve_range=True), 2) + array([[100. , 100. , 99.99, 100. , 100. ], + [100. , 99.39, 95.48, 99.39, 100. ], + [ 99.99, 95.48, 147.59, 95.48, 99.99], + [100. , 99.39, 95.48, 99.39, 100. ], + [100. , 100. , 99.99, 100. , 100. ]]) + + + References + ---------- + .. [1] Maria Petrou, Costas Petrou + "Image Processing: The Fundamentals", (2010), ed ii., page 357, + ISBN 13: 9781119994398 :DOI:`10.1002/9781119994398` + .. [2] Wikipedia. Unsharp masking + https://en.wikipedia.org/wiki/Unsharp_masking + + """ + vrange = None # Range for valid values; used for clipping. + float_dtype = utils._supported_float_type(image.dtype) + if preserve_range: + fimg = image.astype(float_dtype, copy=False) + else: + fimg = img_as_float(image).astype(float_dtype, copy=False) + negative = np.any(fimg < 0) + if negative: + vrange = [-1.0, 1.0] + else: + vrange = [0.0, 1.0] + + if channel_axis is not None: + result = np.empty_like(fimg, dtype=float_dtype) + for channel in range(image.shape[channel_axis]): + sl = utils.slice_at_axis(channel, channel_axis) + result[sl] = _unsharp_mask_single_channel(fimg[sl], radius, amount, vrange) + return result + else: + return _unsharp_mask_single_channel(fimg, radius, amount, vrange) diff --git a/envs/kitoverlay/skimage/filters/_window.py b/envs/kitoverlay/skimage/filters/_window.py new file mode 100644 index 0000000000000000000000000000000000000000..edd60c81d0baf74e75f111188abdb36dfaa119e6 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/_window.py @@ -0,0 +1,131 @@ +import functools + +import numpy as np +from scipy.signal import get_window + +from .._shared.utils import safe_as_int +from ..transform import warp + + +def window(window_type, shape, warp_kwargs=None): + """Return an n-dimensional window of a given size and dimensionality. + + Parameters + ---------- + window_type : string, float, or tuple + The type of window to be created. Any window type supported by + ``scipy.signal.get_window`` is allowed here. See notes below for a + current list, or the SciPy documentation for the version of SciPy + on your machine. + shape : tuple of int or int + The shape of the window along each axis. If an integer is provided, + a 1D window is generated. + warp_kwargs : dict + Keyword arguments passed to `skimage.transform.warp` (e.g., + ``warp_kwargs={'order':3}`` to change interpolation method). + + Returns + ------- + nd_window : ndarray + A window of the specified ``shape``. ``dtype`` is ``np.float64``. + + Notes + ----- + This function is based on ``scipy.signal.get_window`` and thus can access + all of the window types available to that function + (e.g., ``"hann"``, ``"boxcar"``). Note that certain window types require + parameters that have to be supplied with the window name as a tuple + (e.g., ``("tukey", 0.8)``). If only a float is supplied, it is interpreted + as the beta parameter of the Kaiser window. + + See https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html + for more details. + + Note that this function generates a double precision array of the specified + ``shape`` and can thus generate very large arrays that consume a large + amount of available memory. + + The approach taken here to create nD windows is to first calculate the + Euclidean distance from the center of the intended nD window to each + position in the array. That distance is used to sample, with + interpolation, from a 1D window returned from ``scipy.signal.get_window``. + The method of interpolation can be changed with the ``order`` keyword + argument passed to `skimage.transform.warp`. + + Some coordinates in the output window will be outside of the original + signal; these will be filled in with zeros. + + Window types: + - boxcar + - triang + - blackman + - hamming + - hann + - bartlett + - flattop + - parzen + - bohman + - blackmanharris + - nuttall + - barthann + - kaiser (needs beta) + - gaussian (needs standard deviation) + - general_gaussian (needs power, width) + - slepian (needs width) + - dpss (needs normalized half-bandwidth) + - chebwin (needs attenuation) + - exponential (needs decay scale) + - tukey (needs taper fraction) + + Examples + -------- + Return a Hann window with shape (512, 512): + + >>> from skimage.filters import window + >>> w = window('hann', (512, 512)) + + Return a Kaiser window with beta parameter of 16 and shape (256, 256, 35): + + >>> w = window(16, (256, 256, 35)) + + Return a Tukey window with an alpha parameter of 0.8 and shape (100, 300): + + >>> w = window(('tukey', 0.8), (100, 300)) + + References + ---------- + .. [1] Two-dimensional window design, Wikipedia, + https://en.wikipedia.org/wiki/Two_dimensional_window_design + """ + + if np.isscalar(shape): + shape = (safe_as_int(shape),) + else: + shape = tuple(safe_as_int(shape)) + if any(s < 0 for s in shape): + raise ValueError("invalid shape") + + ndim = len(shape) + if ndim <= 0: + raise ValueError("Number of dimensions must be greater than zero") + + max_size = functools.reduce(max, shape) + w = get_window(window_type, max_size, fftbins=False) + w = np.reshape(w, (-1,) + (1,) * (ndim - 1)) + + # Create coords for warping following `ndimage.map_coordinates` convention. + L = [np.arange(s, dtype=np.float32) * (max_size / s) for s in shape] + + center = (max_size / 2) - 0.5 + dist = 0 + for g in np.meshgrid(*L, sparse=True, indexing='ij'): + g -= center + dist = dist + g * g + dist = np.sqrt(dist) + coords = np.zeros((ndim,) + dist.shape, dtype=np.float32) + coords[0] = dist + center + + if warp_kwargs is None: + warp_kwargs = {} + + return warp(w, coords, mode='constant', cval=0.0, **warp_kwargs) diff --git a/envs/kitoverlay/skimage/filters/edges.py b/envs/kitoverlay/skimage/filters/edges.py new file mode 100644 index 0000000000000000000000000000000000000000..d32c3939c5b99d4a718df6c3a35a4dcbf7d9ad50 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/edges.py @@ -0,0 +1,862 @@ +import numpy as np +from scipy import ndimage as ndi +from scipy.ndimage import binary_erosion, convolve + +from .._shared.utils import _supported_float_type, check_nD +from ..restoration.uft import laplacian +from ..util.dtype import img_as_float + +# n-dimensional filter weights +SOBEL_EDGE = np.array([1, 0, -1]) +SOBEL_SMOOTH = np.array([1, 2, 1]) / 4 +HSOBEL_WEIGHTS = SOBEL_EDGE.reshape((3, 1)) * SOBEL_SMOOTH.reshape((1, 3)) +VSOBEL_WEIGHTS = HSOBEL_WEIGHTS.T + +SCHARR_EDGE = np.array([1, 0, -1]) +SCHARR_SMOOTH = np.array([3, 10, 3]) / 16 +HSCHARR_WEIGHTS = SCHARR_EDGE.reshape((3, 1)) * SCHARR_SMOOTH.reshape((1, 3)) +VSCHARR_WEIGHTS = HSCHARR_WEIGHTS.T + +PREWITT_EDGE = np.array([1, 0, -1]) +PREWITT_SMOOTH = np.full((3,), 1 / 3) +HPREWITT_WEIGHTS = PREWITT_EDGE.reshape((3, 1)) * PREWITT_SMOOTH.reshape((1, 3)) +VPREWITT_WEIGHTS = HPREWITT_WEIGHTS.T + +# 2D-only filter weights +ROBERTS_PD_WEIGHTS = np.array([[1, 0], [0, -1]], dtype=np.float64) +ROBERTS_ND_WEIGHTS = np.array([[0, 1], [-1, 0]], dtype=np.float64) + +# These filter weights can be found in Farid & Simoncelli (2004), +# Table 1 (3rd and 4th row). Additional decimal places were computed +# using the code found at https://www.cs.dartmouth.edu/farid/ +farid_smooth = np.array( + [ + [ + 0.0376593171958126, + 0.249153396177344, + 0.426374573253687, + 0.249153396177344, + 0.0376593171958126, + ] + ] +) +farid_edge = np.array( + [[0.109603762960254, 0.276690988455557, 0, -0.276690988455557, -0.109603762960254]] +) +HFARID_WEIGHTS = farid_edge.T * farid_smooth +VFARID_WEIGHTS = np.copy(HFARID_WEIGHTS.T) + + +def _mask_filter_result(result, mask): + """Return result after masking. + + Input masks are eroded so that mask areas in the original image don't + affect values in the result. + """ + if mask is not None: + erosion_footprint = ndi.generate_binary_structure(mask.ndim, mask.ndim) + mask = binary_erosion(mask, erosion_footprint, border_value=0) + result *= mask + return result + + +def _kernel_shape(ndim, dim): + """Return list of `ndim` 1s except at position `dim`, where value is -1. + + Parameters + ---------- + ndim : int + The number of dimensions of the kernel shape. + dim : int + The axis of the kernel to expand to shape -1. + + Returns + ------- + shape : list of int + The requested shape. + + Examples + -------- + >>> _kernel_shape(2, 0) + [-1, 1] + >>> _kernel_shape(3, 1) + [1, -1, 1] + >>> _kernel_shape(4, -1) + [1, 1, 1, -1] + """ + shape = [ + 1, + ] * ndim + shape[dim] = -1 + return shape + + +def _reshape_nd(arr, ndim, dim): + """Reshape a 1D array to have n dimensions, all singletons but one. + + Parameters + ---------- + arr : array, shape (N,) + Input array + ndim : int + Number of desired dimensions of reshaped array. + dim : int + Which dimension/axis will not be singleton-sized. + + Returns + ------- + arr_reshaped : array, shape ([1, ...], N, [1,...]) + View of `arr` reshaped to the desired shape. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> arr = rng.random(7) + >>> _reshape_nd(arr, 2, 0).shape + (7, 1) + >>> _reshape_nd(arr, 3, 1).shape + (1, 7, 1) + >>> _reshape_nd(arr, 4, -1).shape + (1, 1, 1, 7) + """ + kernel_shape = _kernel_shape(ndim, dim) + return np.reshape(arr, kernel_shape) + + +def _generic_edge_filter( + image, + *, + smooth_weights, + edge_weights=[1, 0, -1], + axis=None, + mode='reflect', + cval=0.0, +): + """Apply a generic, n-dimensional edge filter. + + The filter is computed by applying the edge weights along one dimension + and the smoothing weights along all other dimensions. If no axis is given, + or a tuple of axes is given the filter is computed along all axes in turn, + and the magnitude is computed as the square root of the average square + magnitude of all the axes. + + Parameters + ---------- + image : array + The input image. + smooth_weights : array of float + The smoothing weights for the filter. These are applied to dimensions + orthogonal to the edge axis. + edge_weights : 1D array of float, optional + The weights to compute the edge along the chosen axes. + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + edge_mag = np.sqrt(sum([_generic_edge_filter(image, ..., axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + """ + ndim = image.ndim + if axis is None: + axes = list(range(ndim)) + elif np.isscalar(axis): + axes = [axis] + else: + axes = axis + return_magnitude = len(axes) > 1 + + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + output = np.zeros(image.shape, dtype=image.dtype) + + for edge_dim in axes: + kernel = _reshape_nd(edge_weights, ndim, edge_dim) + smooth_axes = list(set(range(ndim)) - {edge_dim}) + for smooth_dim in smooth_axes: + kernel = kernel * _reshape_nd(smooth_weights, ndim, smooth_dim) + ax_output = ndi.convolve(image, kernel, mode=mode, cval=cval) + if return_magnitude: + ax_output *= ax_output + output += ax_output + + if return_magnitude: + output = np.sqrt(output) / np.sqrt(ndim, dtype=output.dtype) + return output + + +def sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find edges in an image using the Sobel filter. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + sobel_mag = np.sqrt(sum([sobel(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Sobel edge map. + + See also + -------- + sobel_h, sobel_v : horizontal and vertical edge detection. + scharr, prewitt, farid, skimage.feature.canny + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + .. [2] https://en.wikipedia.org/wiki/Sobel_operator + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.sobel(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=SOBEL_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def sobel_h(image, mask=None): + """Find the horizontal edges of an image using the Sobel transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Sobel edge map. + + Notes + ----- + We use the following kernel:: + + 1 2 1 + 0 0 0 + -1 -2 -1 + + """ + check_nD(image, 2) + return sobel(image, mask=mask, axis=0) + + +def sobel_v(image, mask=None): + """Find the vertical edges of an image using the Sobel transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Sobel edge map. + + Notes + ----- + We use the following kernel:: + + 1 0 -1 + 2 0 -2 + 1 0 -1 + + """ + check_nD(image, 2) + return sobel(image, mask=mask, axis=1) + + +def scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Scharr transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + sch_mag = np.sqrt(sum([scharr(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Scharr edge map. + + See also + -------- + scharr_h, scharr_v : horizontal and vertical edge detection. + sobel, prewitt, farid, skimage.feature.canny + + Notes + ----- + The Scharr operator has a better rotation invariance than + other edge filters such as the Sobel or the Prewitt operators. + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + .. [2] https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.scharr(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=SCHARR_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def scharr_h(image, mask=None): + """Find the horizontal edges of an image using the Scharr transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Scharr edge map. + + Notes + ----- + We use the following kernel:: + + 3 10 3 + 0 0 0 + -3 -10 -3 + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + """ + check_nD(image, 2) + return scharr(image, mask=mask, axis=0) + + +def scharr_v(image, mask=None): + """Find the vertical edges of an image using the Scharr transform. + + Parameters + ---------- + image : 2-D array + Image to process + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Scharr edge map. + + Notes + ----- + We use the following kernel:: + + 3 0 -3 + 10 0 -10 + 3 0 -3 + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + """ + check_nD(image, 2) + return scharr(image, mask=mask, axis=1) + + +def prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Prewitt transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + prw_mag = np.sqrt(sum([prewitt(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Prewitt edge map. + + See also + -------- + prewitt_h, prewitt_v : horizontal and vertical edge detection. + sobel, scharr, farid, skimage.feature.canny + + Notes + ----- + The edge magnitude depends slightly on edge directions, since the + approximation of the gradient operator by the Prewitt operator is not + completely rotation invariant. For a better rotation invariance, the Scharr + operator should be used. The Sobel operator has a better rotation + invariance than the Prewitt operator, but a worse rotation invariance than + the Scharr operator. + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.prewitt(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=PREWITT_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def prewitt_h(image, mask=None): + """Find the horizontal edges of an image using the Prewitt transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Prewitt edge map. + + Notes + ----- + We use the following kernel:: + + 1/3 1/3 1/3 + 0 0 0 + -1/3 -1/3 -1/3 + + """ + check_nD(image, 2) + return prewitt(image, mask=mask, axis=0) + + +def prewitt_v(image, mask=None): + """Find the vertical edges of an image using the Prewitt transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Prewitt edge map. + + Notes + ----- + We use the following kernel:: + + 1/3 0 -1/3 + 1/3 0 -1/3 + 1/3 0 -1/3 + + """ + check_nD(image, 2) + return prewitt(image, mask=mask, axis=1) + + +def roberts(image, mask=None): + """Find the edge magnitude using Roberts' cross operator. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Roberts' Cross edge map. + + See also + -------- + roberts_pos_diag, roberts_neg_diag : diagonal edge detection. + sobel, scharr, prewitt, skimage.feature.canny + + Examples + -------- + >>> from skimage import data + >>> camera = data.camera() + >>> from skimage import filters + >>> edges = filters.roberts(camera) + + """ + check_nD(image, 2) + out = np.sqrt( + roberts_pos_diag(image, mask) ** 2 + roberts_neg_diag(image, mask) ** 2 + ) + out /= np.sqrt(2) + return out + + +def roberts_pos_diag(image, mask=None): + """Find the cross edges of an image using Roberts' cross operator. + + The kernel is applied to the input image to produce separate measurements + of the gradient component one orientation. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Robert's edge map. + + Notes + ----- + We use the following kernel:: + + 1 0 + 0 -1 + + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, ROBERTS_PD_WEIGHTS) + return _mask_filter_result(result, mask) + + +def roberts_neg_diag(image, mask=None): + """Find the cross edges of an image using the Roberts' Cross operator. + + The kernel is applied to the input image to produce separate measurements + of the gradient component one orientation. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Robert's edge map. + + Notes + ----- + We use the following kernel:: + + 0 1 + -1 0 + + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, ROBERTS_ND_WEIGHTS) + return _mask_filter_result(result, mask) + + +def laplace(image, ksize=3, mask=None): + """Find the edges of an image using the Laplace operator. + + Parameters + ---------- + image : ndarray + Image to process. + ksize : int, optional + Define the size of the discrete Laplacian operator such that it + will have a size of (ksize,) * image.ndim. + mask : ndarray, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : ndarray + The Laplace edge map. + + Notes + ----- + The Laplacian operator is generated using the function + skimage.restoration.uft.laplacian(). + + """ + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + # Create the discrete Laplacian operator - We keep only the real part of + # the filter + _, laplace_op = laplacian(image.ndim, (ksize,) * image.ndim) + result = convolve(image, laplace_op) + return _mask_filter_result(result, mask) + + +def farid(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Farid transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + farid_mag = np.sqrt(sum([farid(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Farid edge map. + + See also + -------- + farid_h, farid_v : horizontal and vertical edge detection. + scharr, sobel, prewitt, skimage.feature.canny + + Notes + ----- + Take the square root of the sum of the squares of the horizontal and + vertical derivatives to get a magnitude that is somewhat insensitive to + direction. Similar to the Scharr operator, this operator is designed with + a rotation invariance constraint. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + .. [2] Wikipedia, "Farid and Simoncelli Derivatives." Available at: + + + Examples + -------- + >>> from skimage import data + >>> camera = data.camera() + >>> from skimage import filters + >>> edges = filters.farid(camera) + """ + output = _generic_edge_filter( + image, + smooth_weights=farid_smooth, + edge_weights=farid_edge, + axis=axis, + mode=mode, + cval=cval, + ) + output = _mask_filter_result(output, mask) + return output + + +def farid_h(image, *, mask=None): + """Find the horizontal edges of an image using the Farid transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Farid edge map. + + Notes + ----- + The kernel was constructed using the 5-tap weights from [1]. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + .. [2] Farid, H. and Simoncelli, E. P. "Optimally rotation-equivariant + directional derivative kernels", In: 7th International Conference on + Computer Analysis of Images and Patterns, Kiel, Germany. Sep, 1997. + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, HFARID_WEIGHTS) + return _mask_filter_result(result, mask) + + +def farid_v(image, *, mask=None): + """Find the vertical edges of an image using the Farid transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Farid edge map. + + Notes + ----- + The kernel was constructed using the 5-tap weights from [1]. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, VFARID_WEIGHTS) + return _mask_filter_result(result, mask) diff --git a/envs/kitoverlay/skimage/filters/lpi_filter.py b/envs/kitoverlay/skimage/filters/lpi_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..6741eef815c8fdb438f846f8cbd9672026a60e9f --- /dev/null +++ b/envs/kitoverlay/skimage/filters/lpi_filter.py @@ -0,0 +1,261 @@ +""" +:author: Stefan van der Walt, 2008 +:license: modified BSD +""" + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type, check_nD + + +def _min_limit(x, val=np.finfo(float).eps): + mask = np.abs(x) < val + x[mask] = np.sign(x[mask]) * val + + +def _center(x, oshape): + """Return an array of shape ``oshape`` from the center of array ``x``.""" + start = (np.array(x.shape) - np.array(oshape)) // 2 + out = x[tuple(slice(s, s + n) for s, n in zip(start, oshape))] + return out + + +def _pad(data, shape): + """Pad the data to the given shape with zeros. + + Parameters + ---------- + data : 2-d ndarray + Input data + shape : (2,) tuple + + """ + out = np.zeros(shape, dtype=data.dtype) + out[tuple(slice(0, n) for n in data.shape)] = data + return out + + +class LPIFilter2D: + """Linear Position-Invariant Filter (2-dimensional)""" + + def __init__(self, impulse_response, **filter_params): + """ + Parameters + ---------- + impulse_response : callable `f(r, c, **filter_params)` + Function that yields the impulse response. ``r`` and ``c`` are + 1-dimensional vectors that represent row and column positions, in + other words coordinates are (r[0],c[0]),(r[0],c[1]) etc. + `**filter_params` are passed through. + + In other words, ``impulse_response`` would be called like this: + + >>> def impulse_response(r, c, **filter_params): + ... pass + >>> + >>> r = [0,0,0,1,1,1,2,2,2] + >>> c = [0,1,2,0,1,2,0,1,2] + >>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3} + >>> impulse_response(r, c, **filter_params) + + + Examples + -------- + Gaussian filter without normalization of coefficients: + + >>> def filt_func(r, c, sigma=1): + ... return np.exp(-(r**2 + c**2)/(2 * sigma**2)) + >>> filter = LPIFilter2D(filt_func) + + """ + if not callable(impulse_response): + raise ValueError("Impulse response must be a callable.") + + self.impulse_response = impulse_response + self.filter_params = filter_params + self._cache = None + + def _prepare(self, data): + """Calculate filter and data FFT in preparation for filtering.""" + dshape = np.array(data.shape) + even_offset = (dshape % 2 == 0).astype(int) + dshape += even_offset # all filter dimensions must be uneven + oshape = np.array(data.shape) * 2 - 1 + + float_dtype = _supported_float_type(data.dtype) + data = data.astype(float_dtype, copy=False) + + if self._cache is None or np.any(self._cache.shape != oshape): + coords = np.mgrid[ + [ + slice(0 + offset, float(n + offset)) + for (n, offset) in zip(dshape, even_offset) + ] + ] + # this steps over two sets of coordinates, + # not over the coordinates individually + for k, coord in enumerate(coords): + coord -= (dshape[k] - 1) / 2.0 + coords = coords.reshape(2, -1).T # coordinate pairs (r,c) + coords = coords.astype(float_dtype, copy=False) + + f = self.impulse_response( + coords[:, 0], coords[:, 1], **self.filter_params + ).reshape(dshape) + + f = _pad(f, oshape) + F = fft.fftn(f) + self._cache = F + else: + F = self._cache + + data = _pad(data, oshape) + G = fft.fftn(data) + + return F, G + + def __call__(self, data): + """Apply the filter to the given data. + + Parameters + ---------- + data : (M, N) ndarray + + """ + check_nD(data, 2, 'data') + F, G = self._prepare(data) + out = fft.ifftn(F * G) + out = np.abs(_center(out, data.shape)) + return out + + +def filter_forward( + data, impulse_response=None, filter_params=None, predefined_filter=None +): + """Apply the given filter to data. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See LPIFilter2D.__init__. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + Examples + -------- + + Gaussian filter without normalization: + + >>> def filt_func(r, c, sigma=1): + ... return np.exp(-(r**2 + c**2)/(2 * sigma**2)) + >>> + >>> from skimage import data + >>> filtered = filter_forward(data.coins(), filt_func) + + """ + if filter_params is None: + filter_params = {} + check_nD(data, 2, 'data') + if predefined_filter is None: + predefined_filter = LPIFilter2D(impulse_response, **filter_params) + return predefined_filter(data) + + +def filter_inverse( + data, impulse_response=None, filter_params=None, max_gain=2, predefined_filter=None +): + """Apply the filter in reverse to the given data. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See :class:`~.LPIFilter2D`. This is a required + argument unless a `predifined_filter` is provided. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + max_gain : float, optional + Limit the filter gain. Often, the filter contains zeros, which would + cause the inverse filter to have infinite gain. High gain causes + amplification of artefacts, so a conservative limit is recommended. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D, optional + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + """ + if filter_params is None: + filter_params = {} + + check_nD(data, 2, 'data') + if predefined_filter is None: + filt = LPIFilter2D(impulse_response, **filter_params) + else: + filt = predefined_filter + + F, G = filt._prepare(data) + _min_limit(F, val=np.finfo(F.real.dtype).eps) + + F = 1 / F + mask = np.abs(F) > max_gain + F[mask] = np.sign(F[mask]) * max_gain + + return _center(np.abs(fft.ifftshift(fft.ifftn(G * F))), data.shape) + + +def wiener( + data, impulse_response=None, filter_params=None, K=0.25, predefined_filter=None +): + """Minimum Mean Square Error (Wiener) inverse filter. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + K : float or (M, N) ndarray + Ratio between power spectrum of noise and undegraded + image. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See LPIFilter2D.__init__. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + """ + if filter_params is None: + filter_params = {} + + check_nD(data, 2, 'data') + + if not isinstance(K, float): + check_nD(K, 2, 'K') + + if predefined_filter is None: + filt = LPIFilter2D(impulse_response, **filter_params) + else: + filt = predefined_filter + + F, G = filt._prepare(data) + _min_limit(F, val=np.finfo(F.real.dtype).eps) + + H_mag_sqr = np.abs(F) ** 2 + F = 1 / F * H_mag_sqr / (H_mag_sqr + K) + + return _center(np.abs(fft.ifftshift(fft.ifftn(G * F))), data.shape) diff --git a/envs/kitoverlay/skimage/filters/rank/__init__.py b/envs/kitoverlay/skimage/filters/rank/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb06260488fbf9a151e7d4a7b4dbaa7edb2342db --- /dev/null +++ b/envs/kitoverlay/skimage/filters/rank/__init__.py @@ -0,0 +1,89 @@ +from .generic import ( + autolevel, + equalize, + gradient, + majority, + maximum, + mean, + geometric_mean, + subtract_mean, + median, + minimum, + modal, + enhance_contrast, + pop, + threshold, + noise_filter, + entropy, + otsu, + sum, + windowed_histogram, +) +from ._percentile import ( + autolevel_percentile, + gradient_percentile, + mean_percentile, + subtract_mean_percentile, + enhance_contrast_percentile, + percentile, + pop_percentile, + sum_percentile, + threshold_percentile, +) +from .bilateral import mean_bilateral, pop_bilateral, sum_bilateral + + +__all__ = [ + 'autolevel', + 'autolevel_percentile', + 'gradient', + 'equalize', + 'gradient_percentile', + 'majority', + 'maximum', + 'mean', + 'geometric_mean', + 'mean_percentile', + 'mean_bilateral', + 'subtract_mean', + 'subtract_mean_percentile', + 'median', + 'minimum', + 'modal', + 'enhance_contrast', + 'enhance_contrast_percentile', + 'pop', + 'pop_percentile', + 'pop_bilateral', + 'sum', + 'sum_bilateral', + 'sum_percentile', + 'threshold', + 'threshold_percentile', + 'noise_filter', + 'entropy', + 'otsu', + 'percentile', + 'windowed_histogram', +] + +__3Dfilters = [ + 'autolevel', + 'equalize', + 'gradient', + 'majority', + 'maximum', + 'mean', + 'geometric_mean', + 'subtract_mean', + 'median', + 'minimum', + 'modal', + 'enhance_contrast', + 'pop', + 'sum', + 'threshold', + 'noise_filter', + 'entropy', + 'otsu', +] diff --git a/envs/kitoverlay/skimage/filters/rank/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/filters/rank/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34bf5cffd12b32b7f1ccb9a7aa04b03654b5f1f5 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/rank/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/rank/__pycache__/_percentile.cpython-311.pyc b/envs/kitoverlay/skimage/filters/rank/__pycache__/_percentile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f9bfafbf5e133b607e1a3eb40694422a147edcc Binary files /dev/null and b/envs/kitoverlay/skimage/filters/rank/__pycache__/_percentile.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/rank/__pycache__/bilateral.cpython-311.pyc b/envs/kitoverlay/skimage/filters/rank/__pycache__/bilateral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5dc9088eb9cbce679c8f5b015c15bfbb22bf18 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/rank/__pycache__/bilateral.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/rank/__pycache__/generic.cpython-311.pyc b/envs/kitoverlay/skimage/filters/rank/__pycache__/generic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3f95bdadfcdbf658fa887dc1f8090aa42001ae3 Binary files /dev/null and b/envs/kitoverlay/skimage/filters/rank/__pycache__/generic.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/filters/rank/_percentile.py b/envs/kitoverlay/skimage/filters/rank/_percentile.py new file mode 100644 index 0000000000000000000000000000000000000000..1d734cfbd1b1bc2e166873df93792f50cdce6576 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/rank/_percentile.py @@ -0,0 +1,485 @@ +"""Inferior and superior ranks, provided by the user, are passed to the kernel +function to provide a softer version of the rank filters. E.g. +``autolevel_percentile`` will stretch image levels between percentile [p0, p1] +instead of using [min, max]. It means that isolated bright or dark pixels will +not produce halos. + +The local histogram is computed using a sliding window similar to the method +described in [1]_. + +Input image can be 8-bit or 16-bit, for 16-bit input images, the number of +histogram bins is determined from the maximum value present in the image. + +Result image is 8-/16-bit or double with respect to the input image and the +rank filter operation. + +References +---------- + +.. [1] Huang, T. ,Yang, G. ; Tang, G.. "A fast two-dimensional + median filtering algorithm", IEEE Transactions on Acoustics, Speech and + Signal Processing, Feb 1979. Volume: 27 , Issue: 1, Page(s): 13 - 18. + +""" + +from ..._shared.utils import check_nD +from . import percentile_cy +from .generic import _preprocess_input + +__all__ = [ + 'autolevel_percentile', + 'gradient_percentile', + 'mean_percentile', + 'subtract_mean_percentile', + 'enhance_contrast_percentile', + 'percentile', + 'pop_percentile', + 'threshold_percentile', +] + + +def _apply(func, image, footprint, out, mask, shift_x, shift_y, p0, p1, out_dtype=None): + check_nD(image, 2) + image, footprint, out, mask, n_bins = _preprocess_input( + image, + footprint, + out, + mask, + out_dtype, + shift_x=shift_x, + shift_y=shift_y, + ) + + func( + image, + footprint, + shift_x=shift_x, + shift_y=shift_y, + mask=mask, + out=out, + n_bins=n_bins, + p0=p0, + p1=p1, + ) + + return out.reshape(out.shape[:2]) + + +def autolevel_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return grayscale local autolevel of an image. + + This filter locally stretches the histogram of grayvalues to cover the + entire range of values from "white" to "black". + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._autolevel, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def gradient_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return local gradient of an image (i.e. local maximum - local minimum). + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._gradient, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def mean_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return local mean of an image. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def subtract_mean_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return image subtracted from its local mean. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._subtract_mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def enhance_contrast_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Enhance contrast of an image. + + This replaces each pixel by the local maximum if the pixel grayvalue is + closer to the local maximum than the local minimum. Otherwise it is + replaced by the local minimum. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._enhance_contrast, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def percentile(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0): + """Return local percentile of an image. + + Returns the value of the p0 lower percentile of the local grayvalue + distribution. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0 : float, optional, in interval [0, 1] + Set the percentile value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._percentile, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=0.0, + ) + + +def pop_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return the local number (population) of pixels. + + The number of pixels is defined as the number of pixels which are included + in the footprint and the mask. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._pop, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def sum_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0, p1=1 +): + """Return the local sum of pixels. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Note that the sum may overflow depending on the data type of the input + array. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0, p1 : float, optional, in interval [0, 1] + Define the [p0, p1] percentile interval to be considered for computing + the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._sum, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=p1, + ) + + +def threshold_percentile( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, p0=0 +): + """Local threshold of an image. + + The resulting binary mask is True if the grayvalue of the center pixel is + greater than the local mean. + + Only grayvalues between percentiles [p0, p1] are considered in the filter. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + p0 : float, optional, in interval [0, 1] + Set the percentile value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + """ + + return _apply( + percentile_cy._threshold, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + p0=p0, + p1=0, + ) diff --git a/envs/kitoverlay/skimage/filters/rank/bilateral.py b/envs/kitoverlay/skimage/filters/rank/bilateral.py new file mode 100644 index 0000000000000000000000000000000000000000..d95a18ef45e8d6161b5b6e72d105e08f05c669ea --- /dev/null +++ b/envs/kitoverlay/skimage/filters/rank/bilateral.py @@ -0,0 +1,262 @@ +"""Approximate bilateral rank filter for local (custom kernel) mean. + +The local histogram is computed using a sliding window similar to the method +described in [1]_. + +The pixel neighborhood is defined by: + +* the given footprint (structuring element) +* an interval [g-s0, g+s1] in graylevel around g the processed pixel graylevel + +The kernel is flat (i.e. each pixel belonging to the neighborhood contributes +equally). + +Result image is 8-/16-bit or double with respect to the input image and the +rank filter operation. + +References +---------- + +.. [1] Huang, T. ,Yang, G. ; Tang, G.. "A fast two-dimensional + median filtering algorithm", IEEE Transactions on Acoustics, Speech and + Signal Processing, Feb 1979. Volume: 27 , Issue: 1, Page(s): 13 - 18. + +""" + +from ..._shared.utils import check_nD +from . import bilateral_cy +from .generic import _preprocess_input + +__all__ = ['mean_bilateral', 'pop_bilateral', 'sum_bilateral'] + + +def _apply(func, image, footprint, out, mask, shift_x, shift_y, s0, s1, out_dtype=None): + check_nD(image, 2) + image, footprint, out, mask, n_bins = _preprocess_input( + image, + footprint, + out, + mask, + out_dtype, + shift_x=shift_x, + shift_y=shift_y, + ) + + func( + image, + footprint, + shift_x=shift_x, + shift_y=shift_y, + mask=mask, + out=out, + n_bins=n_bins, + s0=s0, + s1=s1, + ) + + return out.reshape(out.shape[:2]) + + +def mean_bilateral( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, s0=10, s1=10 +): + """Apply a flat kernel bilateral filter. + + This is an edge-preserving and noise reducing denoising filter. It averages + pixels based on their spatial closeness and radiometric similarity. + + Spatial closeness is measured by considering only the local pixel + neighborhood given by a footprint (structuring element). + + Radiometric similarity is defined by the graylevel interval [g-s0, g+s1] + where g is the current pixel graylevel. + + Only pixels belonging to the footprint and having a graylevel inside this + interval are averaged. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + s0, s1 : int + Define the [s0, s1] interval around the grayvalue of the center pixel + to be considered for computing the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + See also + -------- + skimage.restoration.denoise_bilateral + + Examples + -------- + >>> import numpy as np + >>> from skimage import data + >>> from skimage.morphology import disk + >>> from skimage.filters.rank import mean_bilateral + >>> img = data.camera().astype(np.uint16) + >>> bilat_img = mean_bilateral(img, disk(20), s0=10,s1=10) + + """ + + return _apply( + bilateral_cy._mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + s0=s0, + s1=s1, + ) + + +def pop_bilateral( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, s0=10, s1=10 +): + """Return the local number (population) of pixels. + + + The number of pixels is defined as the number of pixels which are included + in the footprint and the mask. Additionally pixels must have a graylevel + inside the interval [g-s0, g+s1] where g is the grayvalue of the center + pixel. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + s0, s1 : int + Define the [s0, s1] interval around the grayvalue of the center pixel + to be considered for computing the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> import skimage.filters.rank as rank + >>> img = 255 * np.array([[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint16) + >>> rank.pop_bilateral(img, footprint_rectangle((3, 3)), s0=10, s1=10) + array([[3, 4, 3, 4, 3], + [4, 4, 6, 4, 4], + [3, 6, 9, 6, 3], + [4, 4, 6, 4, 4], + [3, 4, 3, 4, 3]], dtype=uint16) + + """ + + return _apply( + bilateral_cy._pop, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + s0=s0, + s1=s1, + ) + + +def sum_bilateral( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, s0=10, s1=10 +): + """Apply a flat kernel bilateral filter. + + This is an edge-preserving and noise reducing denoising filter. It averages + pixels based on their spatial closeness and radiometric similarity. + + Spatial closeness is measured by considering only the local pixel + neighborhood given by a footprint (structuring element). + + Radiometric similarity is defined by the graylevel interval [g-s0, g+s1] + where g is the current pixel graylevel. + + Only pixels belonging to the footprint AND having a graylevel inside this + interval are summed. + + Note that the sum may overflow depending on the data type of the input + array. + + Parameters + ---------- + image : 2-D array (uint8, uint16) + Input image. + footprint : 2-D array + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array, same dtype as input `image` + If None, a new array is allocated. + mask : ndarray + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + s0, s1 : int + Define the [s0, s1] interval around the grayvalue of the center pixel + to be considered for computing the value. + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + See also + -------- + skimage.restoration.denoise_bilateral + + Examples + -------- + >>> import numpy as np + >>> from skimage import data + >>> from skimage.morphology import disk + >>> from skimage.filters.rank import sum_bilateral + >>> img = data.camera().astype(np.uint16) + >>> bilat_img = sum_bilateral(img, disk(10), s0=10, s1=10) + + """ + + return _apply( + bilateral_cy._sum, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + s0=s0, + s1=s1, + ) diff --git a/envs/kitoverlay/skimage/filters/rank/generic.py b/envs/kitoverlay/skimage/filters/rank/generic.py new file mode 100644 index 0000000000000000000000000000000000000000..719573d3ecabb562d312b8496d93125ad9e092da --- /dev/null +++ b/envs/kitoverlay/skimage/filters/rank/generic.py @@ -0,0 +1,1752 @@ +""" + +General Description +------------------- + +These filters compute the local histogram at each pixel, using a sliding window +similar to the method described in [1]_. A histogram is built using a moving +window in order to limit redundant computation. The moving window follows a +snake-like path: + +...------------------------↘ +↙--------------------------↙ +↘--------------------------... + +The local histogram is updated at each pixel as the footprint window +moves by, i.e. only those pixels entering and leaving the footprint +update the local histogram. The histogram size is 8-bit (256 bins) for 8-bit +images and 2- to 16-bit for 16-bit images depending on the maximum value of the +image. + +The filter is applied up to the image border, the neighborhood used is +adjusted accordingly. The user may provide a mask image (same size as input +image) where non zero values are the part of the image participating in the +histogram computation. By default the entire image is filtered. + +This implementation outperforms :func:`skimage.morphology.dilation` +for large footprints. + +Input images will be cast in unsigned 8-bit integer or unsigned 16-bit integer +if necessary. The number of histogram bins is then determined from the maximum +value present in the image. Eventually, the output image is cast in the input +dtype, or the `output_dtype` if set. + +To do +----- + +* add simple examples, adapt documentation on existing examples +* add/check existing doc +* adapting tests for each type of filter + + +References +---------- + +.. [1] Huang, T. ,Yang, G. ; Tang, G.. "A fast two-dimensional + median filtering algorithm", IEEE Transactions on Acoustics, Speech and + Signal Processing, Feb 1979. Volume: 27 , Issue: 1, Page(s): 13 - 18. + +""" + +import numpy as np +from scipy import ndimage as ndi + +from ..._shared.utils import check_nD, warn +from ...morphology.footprints import _footprint_is_sequence +from ...util import img_as_ubyte +from . import generic_cy + + +__all__ = [ + 'autolevel', + 'equalize', + 'gradient', + 'maximum', + 'mean', + 'geometric_mean', + 'subtract_mean', + 'median', + 'minimum', + 'modal', + 'enhance_contrast', + 'pop', + 'threshold', + 'noise_filter', + 'entropy', + 'otsu', +] + + +def _preprocess_input( + image, + footprint=None, + out=None, + mask=None, + out_dtype=None, + pixel_size=1, + shift_x=None, + shift_y=None, +): + """Preprocess and verify input for filters.rank methods. + + Parameters + ---------- + image : 2-D array (integer or float) + Input image. + footprint : 2-D array (integer or float), optional + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array (integer or float), optional + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + out_dtype : data-type, optional + Desired output data-type. Default is None, which means we cast output + in input dtype. + pixel_size : int, optional + Dimension of each pixel. Default value is 1. + shift_x, shift_y : int, optional + Offset added to the footprint center point. Shift is bounded to the + footprint size (center must be inside of the given footprint). + + Returns + ------- + image : 2-D array (np.uint8 or np.uint16) + footprint : 2-D array (np.uint8) + The neighborhood expressed as a binary 2-D array. + out : 3-D array (same dtype out_dtype or as input) + Output array. The two first dimensions are the spatial ones, the third + one is the pixel vector (length 1 by default). + mask : 2-D array (np.uint8) + Mask array that defines (>0) area of the image included in the local + neighborhood. + n_bins : int + Number of histogram bins. + + """ + check_nD(image, 2) + input_dtype = image.dtype + if input_dtype in (bool, bool) or out_dtype in (bool, bool): + raise ValueError('dtype cannot be bool.') + if input_dtype not in (np.uint8, np.uint16): + message = ( + f'Possible precision loss converting image of type ' + f'{input_dtype} to uint8 as required by rank filters. ' + f'Convert manually using skimage.util.img_as_ubyte to ' + f'silence this warning.' + ) + warn(message, stacklevel=5) + image = img_as_ubyte(image) + + if _footprint_is_sequence(footprint): + raise ValueError( + "footprint sequences are not currently supported by rank filters" + ) + + footprint = np.ascontiguousarray(img_as_ubyte(footprint > 0)) + if footprint.ndim != image.ndim: + raise ValueError('Image dimensions and neighborhood dimensions' 'do not match') + + image = np.ascontiguousarray(image) + + if mask is not None: + mask = img_as_ubyte(mask) + mask = np.ascontiguousarray(mask) + + if image is out: + raise NotImplementedError("Cannot perform rank operation in place.") + + if out is None: + if out_dtype is None: + out_dtype = image.dtype + out = np.empty(image.shape + (pixel_size,), dtype=out_dtype) + else: + if len(out.shape) == 2: + out = out.reshape(out.shape + (pixel_size,)) + + if image.dtype in (np.uint8, np.int8): + n_bins = 256 + else: + # Convert to a Python int to avoid the potential overflow when we add + # 1 to the maximum of the image. + n_bins = int(max(3, image.max())) + 1 + + if n_bins > 2**10: + warn( + f'Bad rank filter performance is expected due to a ' + f'large number of bins ({n_bins}), equivalent to an approximate ' + f'bitdepth of {np.log2(n_bins):.1f}.', + stacklevel=2, + ) + + for name, value in zip(("shift_x", "shift_y"), (shift_x, shift_y)): + if np.dtype(type(value)) == bool: + warn( + f"Paramter `{name}` is boolean and will be interpreted as int. " + "This is not officially supported, use int instead.", + category=UserWarning, + stacklevel=4, + ) + + return image, footprint, out, mask, n_bins + + +def _handle_input_3D( + image, + footprint=None, + out=None, + mask=None, + out_dtype=None, + pixel_size=1, + shift_x=None, + shift_y=None, + shift_z=None, +): + """Preprocess and verify input for filters.rank methods. + + Parameters + ---------- + image : 3-D array (integer or float) + Input image. + footprint : 3-D array (integer or float), optional + The neighborhood expressed as a 3-D array of 1's and 0's. + out : 3-D array (integer or float), optional + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + out_dtype : data-type, optional + Desired output data-type. Default is None, which means we cast output + in input dtype. + pixel_size : int, optional + Dimension of each pixel. Default value is 1. + shift_x, shift_y, shift_z : int, optional + Offset added to the footprint center point. Shift is bounded to the + footprint size (center must be inside of the given footprint). + + Returns + ------- + image : 3-D array (np.uint8 or np.uint16) + footprint : 3-D array (np.uint8) + The neighborhood expressed as a binary 3-D array. + out : 3-D array (same dtype out_dtype or as input) + Output array. The two first dimensions are the spatial ones, the third + one is the pixel vector (length 1 by default). + mask : 3-D array (np.uint8) + Mask array that defines (>0) area of the image included in the local + neighborhood. + n_bins : int + Number of histogram bins. + + """ + check_nD(image, 3) + if image.dtype not in (np.uint8, np.uint16): + message = ( + f'Possible precision loss converting image of type ' + f'{image.dtype} to uint8 as required by rank filters. ' + f'Convert manually using skimage.util.img_as_ubyte to ' + f'silence this warning.' + ) + warn(message, stacklevel=2) + image = img_as_ubyte(image) + + footprint = np.ascontiguousarray(img_as_ubyte(footprint > 0)) + if footprint.ndim != image.ndim: + raise ValueError('Image dimensions and neighborhood dimensions' 'do not match') + image = np.ascontiguousarray(image) + + if mask is None: + mask = np.ones(image.shape, dtype=np.uint8) + else: + mask = img_as_ubyte(mask) + mask = np.ascontiguousarray(mask) + + if image is out: + raise NotImplementedError("Cannot perform rank operation in place.") + + if out is None: + if out_dtype is None: + out_dtype = image.dtype + out = np.empty(image.shape + (pixel_size,), dtype=out_dtype) + else: + out = out.reshape(out.shape + (pixel_size,)) + + is_8bit = image.dtype in (np.uint8, np.int8) + + if is_8bit: + n_bins = 256 + else: + # Convert to a Python int to avoid the potential overflow when we add + # 1 to the maximum of the image. + n_bins = int(max(3, image.max())) + 1 + + if n_bins > 2**10: + warn( + f'Bad rank filter performance is expected due to a ' + f'large number of bins ({n_bins}), equivalent to an approximate ' + f'bitdepth of {np.log2(n_bins):.1f}.', + stacklevel=2, + ) + + for name, value in zip( + ("shift_x", "shift_y", "shift_z"), (shift_x, shift_y, shift_z) + ): + if np.dtype(type(value)) == bool: + warn( + f"Parameter `{name}` is boolean and will be interpreted as int. " + "This is not officially supported, use int instead.", + category=UserWarning, + stacklevel=4, + ) + + return image, footprint, out, mask, n_bins + + +def _apply_scalar_per_pixel( + func, image, footprint, out, mask, shift_x, shift_y, out_dtype=None +): + """Process the specific cython function to the image. + + Parameters + ---------- + func : function + Cython function to apply. + image : 2-D array (integer or float) + Input image. + footprint : 2-D array (integer or float) + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array (integer or float) + If None, a new array is allocated. + mask : ndarray (integer or float) + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + out_dtype : data-type, optional + Desired output data-type. Default is None, which means we cast output + in input dtype. + + """ + # preprocess and verify the input + image, footprint, out, mask, n_bins = _preprocess_input( + image, footprint, out, mask, out_dtype, shift_x=shift_x, shift_y=shift_y + ) + + # apply cython function + func( + image, + footprint, + shift_x=shift_x, + shift_y=shift_y, + mask=mask, + out=out, + n_bins=n_bins, + ) + + return np.squeeze(out, axis=-1) + + +def _apply_scalar_per_pixel_3D( + func, image, footprint, out, mask, shift_x, shift_y, shift_z, out_dtype=None +): + image, footprint, out, mask, n_bins = _handle_input_3D( + image, + footprint, + out, + mask, + out_dtype, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + + func( + image, + footprint, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + mask=mask, + out=out, + n_bins=n_bins, + ) + + return out.reshape(out.shape[:3]) + + +def _apply_vector_per_pixel( + func, image, footprint, out, mask, shift_x, shift_y, out_dtype=None, pixel_size=1 +): + """ + + Parameters + ---------- + func : function + Cython function to apply. + image : 2-D array (integer or float) + Input image. + footprint : 2-D array (integer or float) + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array (integer or float) + If None, a new array is allocated. + mask : ndarray (integer or float) + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + out_dtype : data-type, optional + Desired output data-type. Default is None, which means we cast output + in input dtype. + pixel_size : int, optional + Dimension of each pixel. + + Returns + ------- + out : 3-D array with float dtype of dimensions (H,W,N), where (H,W) are + the dimensions of the input image and N is n_bins or + ``image.max() + 1`` if no value is provided as a parameter. + Effectively, each pixel is a N-D feature vector that is the histogram. + The sum of the elements in the feature vector will be 1, unless no + pixels in the window were covered by both footprint and mask, in which + case all elements will be 0. + + """ + # preprocess and verify the input + image, footprint, out, mask, n_bins = _preprocess_input( + image, + footprint, + out, + mask, + out_dtype, + pixel_size, + shift_x=shift_x, + shift_y=shift_y, + ) + + # apply cython function + func( + image, + footprint, + shift_x=shift_x, + shift_y=shift_y, + mask=mask, + out=out, + n_bins=n_bins, + ) + + return out + + +def autolevel(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Auto-level image using local histogram. + + This filter locally stretches the histogram of gray values to cover the + entire range of values from "white" to "black". + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import autolevel + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> auto = autolevel(img, disk(5)) + >>> auto_vol = autolevel(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._autolevel, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._autolevel_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def equalize(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Equalize image using local histogram. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import equalize + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> equ = equalize(img, disk(5)) + >>> equ_vol = equalize(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._equalize, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._equalize_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def gradient(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return local gradient of an image (i.e. local maximum - local minimum). + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import gradient + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = gradient(img, disk(5)) + >>> out_vol = gradient(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._gradient, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._gradient_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def maximum(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return local maximum of an image. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + See also + -------- + skimage.morphology.dilation + + Notes + ----- + The lower algorithm complexity makes `skimage.filters.rank.maximum` + more efficient for larger images and footprints. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import maximum + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = maximum(img, disk(5)) + >>> out_vol = maximum(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._maximum, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._maximum_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def mean(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return local mean of an image. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import mean + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> avg = mean(img, disk(5)) + >>> avg_vol = mean(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._mean_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def geometric_mean( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0 +): + """Return local geometric mean of an image. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import mean + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> avg = geometric_mean(img, disk(5)) + >>> avg_vol = geometric_mean(volume, ball(5)) + + References + ---------- + .. [1] Gonzalez, R. C. and Woods, R. E. "Digital Image Processing + (3rd Edition)." Prentice-Hall Inc, 2006. + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._geometric_mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._geometric_mean_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def subtract_mean( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0 +): + """Return image subtracted from its local mean. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Notes + ----- + Subtracting the mean value may introduce underflow. To compensate + this potential underflow, the obtained difference is downscaled by + a factor of 2 and shifted by `n_bins / 2 - 1`, the median value of + the local histogram (`n_bins = max(3, image.max()) +1` for 16-bits + images and 256 otherwise). + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import subtract_mean + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = subtract_mean(img, disk(5)) + >>> out_vol = subtract_mean(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._subtract_mean, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._subtract_mean_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def median( + image, + footprint=None, + out=None, + mask=None, + shift_x=0, + shift_y=0, + shift_z=0, +): + """Return local median of an image. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. If None, a + full square of size 3 is used. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + See also + -------- + skimage.filters.median : Implementation of a median filtering which handles + images with floating precision. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import median + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> med = median(img, disk(5)) + >>> med_vol = median(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, image.ndim) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._median, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._median_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def minimum(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return local minimum of an image. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + See also + -------- + skimage.morphology.erosion + + Notes + ----- + The lower algorithm complexity makes `skimage.filters.rank.minimum` more + efficient for larger images and footprints. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import minimum + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = minimum(img, disk(5)) + >>> out_vol = minimum(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._minimum, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._minimum_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def modal(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return local mode of an image. + + The mode is the value that appears most often in the local histogram. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import modal + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = modal(img, disk(5)) + >>> out_vol = modal(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._modal, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._modal_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def enhance_contrast( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0 +): + """Enhance contrast of an image. + + This replaces each pixel by the local maximum if the pixel gray value is + closer to the local maximum than the local minimum. Otherwise it is + replaced by the local minimum. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import enhance_contrast + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = enhance_contrast(img, disk(5)) + >>> out_vol = enhance_contrast(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._enhance_contrast, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._enhance_contrast_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def pop(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return the local number (population) of pixels. + + The number of pixels is defined as the number of pixels which are included + in the footprint and the mask. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage.morphology import footprint_rectangle # Need to add 3D example + >>> import skimage.filters.rank as rank + >>> img = 255 * np.array([[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> rank.pop(img, footprint_rectangle((3, 3))) + array([[4, 6, 6, 6, 4], + [6, 9, 9, 9, 6], + [6, 9, 9, 9, 6], + [6, 9, 9, 9, 6], + [4, 6, 6, 6, 4]], dtype=uint8) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._pop, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._pop_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def sum(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Return the local sum of pixels. + + Note that the sum may overflow depending on the data type of the input + array. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage.morphology import footprint_rectangle # Need to add 3D example + >>> import skimage.filters.rank as rank # Cube seems to fail but + >>> img = np.array([[0, 0, 0, 0, 0], # Ball can pass + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> rank.sum(img, footprint_rectangle((3, 3))) + array([[1, 2, 3, 2, 1], + [2, 4, 6, 4, 2], + [3, 6, 9, 6, 3], + [2, 4, 6, 4, 2], + [1, 2, 3, 2, 1]], dtype=uint8) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._sum, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._sum_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def threshold(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Local threshold of an image. + + The resulting binary mask is True if the gray value of the center pixel is + greater than the local mean. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage.morphology import footprint_rectangle # Need to add 3D example + >>> from skimage.filters.rank import threshold + >>> img = 255 * np.array([[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> threshold(img, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._threshold, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._threshold_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def noise_filter( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0 +): + """Noise feature. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + References + ---------- + .. [1] N. Hashimoto et al. Referenceless image quality evaluation + for whole slide imaging. J Pathol Inform 2012;3:9. + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk, ball + >>> from skimage.filters.rank import noise_filter + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> out = noise_filter(img, disk(5)) + >>> out_vol = noise_filter(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if _footprint_is_sequence(footprint): + raise ValueError( + "footprint sequences are not currently supported by rank filters" + ) + if np_image.ndim == 2: + # ensure that the central pixel in the footprint is empty + centre_r = int(footprint.shape[0] / 2) + shift_y + centre_c = int(footprint.shape[1] / 2) + shift_x + # make a local copy + footprint_cpy = footprint.copy() + footprint_cpy[centre_r, centre_c] = 0 + + return _apply_scalar_per_pixel( + generic_cy._noise_filter, + image, + footprint_cpy, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + # ensure that the central pixel in the footprint is empty + centre_r = int(footprint.shape[0] / 2) + shift_y + centre_c = int(footprint.shape[1] / 2) + shift_x + centre_z = int(footprint.shape[2] / 2) + shift_z + # make a local copy + footprint_cpy = footprint.copy() + footprint_cpy[centre_r, centre_c, centre_z] = 0 + + return _apply_scalar_per_pixel_3D( + generic_cy._noise_filter_3D, + image, + footprint_cpy, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def entropy(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Local entropy. + + The entropy is computed using base 2 logarithm i.e. the filter returns the + minimum number of bits needed to encode the local gray level + distribution. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray (float) + Output image. + + References + ---------- + .. [1] `https://en.wikipedia.org/wiki/Entropy_(information_theory) `_ + + Examples + -------- + >>> from skimage import data + >>> from skimage.filters.rank import entropy + >>> from skimage.morphology import disk, ball + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> ent = entropy(img, disk(5)) + >>> ent_vol = entropy(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._entropy, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + out_dtype=np.float64, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._entropy_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + out_dtype=np.float64, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def otsu(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0): + """Local Otsu's threshold value for each pixel. + + Parameters + ---------- + image : ([P,] M, N) ndarray (uint8, uint16) + Input image. + footprint : ndarray + The neighborhood expressed as an ndarray of 1's and 0's. + out : ([P,] M, N) array (same dtype as input) + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y, shift_z : int + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : ([P,] M, N) ndarray, same dtype as `image` + Output image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Otsu's_method + + Examples + -------- + >>> from skimage import data + >>> from skimage.filters.rank import otsu + >>> from skimage.morphology import disk, ball + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> local_otsu = otsu(img, disk(5)) + >>> thresh_image = img >= local_otsu + >>> local_otsu_vol = otsu(volume, ball(5)) + >>> thresh_image_vol = volume >= local_otsu_vol + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._otsu, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._otsu_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') + + +def windowed_histogram( + image, footprint, out=None, mask=None, shift_x=0, shift_y=0, n_bins=None +): + """Normalized sliding window histogram + + Parameters + ---------- + image : 2-D array (integer or float) + Input image. + footprint : 2-D array (integer or float) + The neighborhood expressed as a 2-D array of 1's and 0's. + out : 2-D array (integer or float), optional + If None, a new array is allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int, optional + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + n_bins : int or None + The number of histogram bins. Will default to ``image.max() + 1`` + if None is passed. + + Returns + ------- + out : 3-D array (float) + Array of dimensions (H,W,N), where (H,W) are the dimensions of the + input image and N is n_bins or ``image.max() + 1`` if no value is + provided as a parameter. Effectively, each pixel is a N-D feature + vector that is the histogram. The sum of the elements in the feature + vector will be 1, unless no pixels in the window were covered by both + footprint and mask, in which case all elements will be 0. + + Examples + -------- + >>> from skimage import data + >>> from skimage.filters.rank import windowed_histogram + >>> from skimage.morphology import disk, ball + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> hist_img = windowed_histogram(img, disk(5)) + + """ + + if n_bins is None: + n_bins = int(image.max()) + 1 + + return _apply_vector_per_pixel( + generic_cy._windowed_hist, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + out_dtype=np.float64, + pixel_size=n_bins, + ) + + +def majority( + image, + footprint, + *, + out=None, + mask=None, + shift_x=0, + shift_y=0, + shift_z=0, +): + """Assign to each pixel the most common value within its neighborhood. + + Parameters + ---------- + image : ndarray + Image array (uint8, uint16 array). + footprint : 2-D array (integer or float) + The neighborhood expressed as a 2-D array of 1's and 0's. + out : ndarray (integer or float), optional + If None, a new array will be allocated. + mask : ndarray (integer or float), optional + Mask array that defines (>0) area of the image included in the local + neighborhood. If None, the complete image is used (default). + shift_x, shift_y : int, optional + Offset added to the footprint center point. Shift is bounded to the + footprint sizes (center must be inside the given footprint). + + Returns + ------- + out : 2-D array, same dtype as input `image` + Output image. + + Examples + -------- + >>> from skimage import data + >>> from skimage.filters.rank import majority + >>> from skimage.morphology import disk, ball + >>> import numpy as np + >>> img = data.camera() + >>> rng = np.random.default_rng() + >>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8) + >>> maj_img = majority(img, disk(5)) + >>> maj_img_vol = majority(volume, ball(5)) + + """ + + np_image = np.asanyarray(image) + if np_image.ndim == 2: + return _apply_scalar_per_pixel( + generic_cy._majority, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + ) + elif np_image.ndim == 3: + return _apply_scalar_per_pixel_3D( + generic_cy._majority_3D, + image, + footprint, + out=out, + mask=mask, + shift_x=shift_x, + shift_y=shift_y, + shift_z=shift_z, + ) + raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.') diff --git a/envs/kitoverlay/skimage/filters/ridges.py b/envs/kitoverlay/skimage/filters/ridges.py new file mode 100644 index 0000000000000000000000000000000000000000..f43c5b12ad76e059cdd8955c7bb1ac9f96744738 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/ridges.py @@ -0,0 +1,402 @@ +""" +Ridge filters. + +Ridge filters can be used to detect continuous edges, such as vessels, +neurites, wrinkles, rivers, and other tube-like structures. The present +class of ridge filters relies on the eigenvalues of the Hessian matrix of +image intensities to detect tube-like structures where the intensity changes +perpendicular but not along the structure. +""" + +from warnings import warn + +import numpy as np +from scipy import linalg + +from .._shared.utils import _supported_float_type, check_nD +from ..feature.corner import hessian_matrix, hessian_matrix_eigvals + + +def meijering( + image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0 +): + """ + Filter an image with the Meijering neuriteness filter. + + This filter can be used to detect continuous ridges, e.g. neurites, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Calculates the eigenvalues of the Hessian to compute the similarity of + an image region to neurites, according to the method described in [1]_. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter + alpha : float, optional + Shaping filter constant, that selects maximally flat elongated + features. The default, None, selects the optimal value -1/(ndim+1). + black_ridges : bool, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, ...]) ndarray + Filtered image (maximum of pixels across all scales). + + See also + -------- + sato + frangi + hessian + + References + ---------- + .. [1] Meijering, E., Jacob, M., Sarria, J. C., Steiner, P., Hirling, H., + Unser, M. (2004). Design and validation of a tool for neurite tracing + and analysis in fluorescence microscopy images. Cytometry Part A, + 58(2), 167-176. + :DOI:`10.1002/cyto.a.20022` + """ + + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + if alpha is None: + alpha = 1 / (image.ndim + 1) + mtx = linalg.circulant([1, *[alpha] * (image.ndim - 1)]).astype(image.dtype) + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Compute normalized eigenvalues l_i = e_i + sum_{j!=i} alpha * e_j. + vals = np.tensordot(mtx, eigvals, 1) + # Get largest normalized eigenvalue (by magnitude) at each pixel. + vals = np.take_along_axis(vals, abs(vals).argmax(0)[None], 0).squeeze(0) + # Remove negative values. + vals = np.maximum(vals, 0) + # Normalize to max = 1 (unless everything is already zero). + max_val = vals.max() + if max_val > 0: + vals /= max_val + filtered_max = np.maximum(filtered_max, vals) + + return filtered_max # Return pixel-wise max over all sigmas. + + +def sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode='reflect', cval=0): + """ + Filter an image with the Sato tubeness filter. + + This filter can be used to detect continuous ridges, e.g. tubes, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Defined only for 2-D and 3-D images. Calculates the eigenvalues of the + Hessian to compute the similarity of an image region to tubes, according to + the method described in [1]_. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter. + black_ridges : bool, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + See also + -------- + meijering + frangi + hessian + + References + ---------- + .. [1] Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., + Koller, T., ..., Kikinis, R. (1998). Three-dimensional multi-scale line + filter for segmentation and visualization of curvilinear structures in + medical images. Medical image analysis, 2(2), 143-168. + :DOI:`10.1016/S1361-8415(98)80009-1` + """ + + check_nD(image, [2, 3]) # Check image dimensions. + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Compute normalized tubeness (eqs. (9) and (22), ref. [1]_) as the + # geometric mean of eigvals other than the lowest one + # (hessian_matrix_eigvals returns eigvals in decreasing order), clipped + # to 0, multiplied by sigma^2. + eigvals = eigvals[:-1] + vals = sigma**2 * np.prod(np.maximum(eigvals, 0), 0) ** (1 / len(eigvals)) + filtered_max = np.maximum(filtered_max, vals) + return filtered_max # Return pixel-wise max over all sigmas. + + +def frangi( + image, + sigmas=range(1, 10, 2), + scale_range=None, + scale_step=None, + alpha=0.5, + beta=0.5, + gamma=None, + black_ridges=True, + mode='reflect', + cval=0, +): + """ + Filter an image with the Frangi vesselness filter. + + This filter can be used to detect continuous ridges, e.g. vessels, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Defined only for 2-D and 3-D images. Calculates the eigenvalues of the + Hessian to compute the similarity of an image region to vessels, according + to the method described in [1]_. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter, i.e., + np.arange(scale_range[0], scale_range[1], scale_step) + scale_range : 2-tuple of floats, optional + The range of sigmas used. + scale_step : float, optional + Step size between sigmas. + alpha : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a plate-like structure. + beta : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a blob-like structure. + gamma : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to areas of high variance/texture/structure. + + .. versionchanged:: 0.20 + The default, None, uses half of the maximum Hessian norm. + + black_ridges : bool, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + .. versionchanged:: 0.20 + The implementation got rewritten and gives different output values wrt + the previous implementation (backwards incompatible change). + The filter is now set to zero whenever one of the Hessian eigenvalues + has a sign which is incompatible with a ridge of the desired polarity. + + Notes + ----- + Earlier versions of this filter were implemented by Marc Schrijver, + (November 2001), D. J. Kroon, University of Twente (May 2009) [2]_, and + D. G. Ellis (January 2017) [3]_. + + See also + -------- + meijering + sato + hessian + + References + ---------- + .. [1] Frangi, A. F., Niessen, W. J., Vincken, K. L., & Viergever, M. A. + (1998,). Multiscale vessel enhancement filtering. In International + Conference on Medical Image Computing and Computer-Assisted + Intervention (pp. 130-137). Springer Berlin Heidelberg. + :DOI:`10.1007/BFb0056195` + .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter. + .. [3] Ellis, D. G.: https://github.com/ellisdg/frangi3d/tree/master/frangi + """ + if scale_range is not None and scale_step is not None: + warn( + 'Use keyword parameter `sigmas` instead of `scale_range` and ' + '`scale_range` which will be removed in version 0.17.', + stacklevel=2, + ) + sigmas = np.arange(scale_range[0], scale_range[1], scale_step) + + check_nD(image, [2, 3]) # Check image dimensions. + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Sort eigenvalues by magnitude. + eigvals = np.take_along_axis(eigvals, abs(eigvals).argsort(0), 0) + lambda1 = eigvals[0] + if image.ndim == 2: + (lambda2,) = np.maximum(eigvals[1:], 1e-10) + r_a = np.inf # implied by eq. (15). + r_b = abs(lambda1) / lambda2 # eq. (15). + else: # ndim == 3 + lambda2, lambda3 = np.maximum(eigvals[1:], 1e-10) + r_a = lambda2 / lambda3 # eq. (11). + r_b = abs(lambda1) / np.sqrt(lambda2 * lambda3) # eq. (10). + s = np.sqrt((eigvals**2).sum(0)) # eq. (12). + if gamma is None: + gamma = s.max() / 2 + if gamma == 0: + gamma = 1 # If s == 0 everywhere, gamma doesn't matter. + # Filtered image, eq. (13) and (15). Our implementation relies on the + # blobness exponential factor underflowing to zero whenever the second + # or third eigenvalues are negative (we clip them to 1e-10, to make r_b + # very large). + vals = 1.0 - np.exp( + -(r_a**2) / (2 * alpha**2), dtype=image.dtype + ) # plate sensitivity + vals *= np.exp(-(r_b**2) / (2 * beta**2), dtype=image.dtype) # blobness + vals *= 1.0 - np.exp( + -(s**2) / (2 * gamma**2), dtype=image.dtype + ) # structuredness + filtered_max = np.maximum(filtered_max, vals) + return filtered_max # Return pixel-wise max over all sigmas. + + +def hessian( + image, + sigmas=range(1, 10, 2), + scale_range=None, + scale_step=None, + alpha=0.5, + beta=0.5, + gamma=15, + black_ridges=True, + mode='reflect', + cval=0, +): + """Filter an image with the Hybrid Hessian filter. + + This filter can be used to detect continuous edges, e.g. vessels, + wrinkles, rivers. It can be used to calculate the fraction of the whole + image containing such objects. + + Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but + uses alternative method of smoothing. Refer to [1]_ to find the differences + between Frangi and Hessian filters. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter, i.e., + np.arange(scale_range[0], scale_range[1], scale_step) + scale_range : 2-tuple of floats, optional + The range of sigmas used. + scale_step : float, optional + Step size between sigmas. + beta : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a blob-like structure. + gamma : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to areas of high variance/texture/structure. + black_ridges : bool, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + Notes + ----- + Written by Marc Schrijver (November 2001) + Re-Written by D. J. Kroon University of Twente (May 2009) [2]_ + + See also + -------- + meijering + sato + frangi + + References + ---------- + .. [1] Ng, C. C., Yap, M. H., Costen, N., & Li, B. (2014,). Automatic + wrinkle detection using hybrid Hessian filter. In Asian Conference on + Computer Vision (pp. 609-622). Springer International Publishing. + :DOI:`10.1007/978-3-319-16811-1_40` + .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter. + """ + filtered = frangi( + image, + sigmas=sigmas, + scale_range=scale_range, + scale_step=scale_step, + alpha=alpha, + beta=beta, + gamma=gamma, + black_ridges=black_ridges, + mode=mode, + cval=cval, + ) + + filtered[filtered <= 0] = 1 + return filtered diff --git a/envs/kitoverlay/skimage/filters/thresholding.py b/envs/kitoverlay/skimage/filters/thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..293671fa26f3551c515fe229c5e18dae2a503344 --- /dev/null +++ b/envs/kitoverlay/skimage/filters/thresholding.py @@ -0,0 +1,1339 @@ +import inspect +import itertools +import math +from collections import OrderedDict +from collections.abc import Iterable + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, warn +from .._shared.version_requirements import require +from ..exposure import histogram +from ..filters._multiotsu import ( + _get_multiotsu_thresh_indices, + _get_multiotsu_thresh_indices_lut, +) +from ..transform import integral_image +from ..util import dtype_limits +from ._sparse import _correlate_sparse, _validate_window_size + +__all__ = [ + 'try_all_threshold', + 'threshold_otsu', + 'threshold_yen', + 'threshold_isodata', + 'threshold_li', + 'threshold_local', + 'threshold_minimum', + 'threshold_mean', + 'threshold_niblack', + 'threshold_sauvola', + 'threshold_triangle', + 'apply_hysteresis_threshold', + 'threshold_multiotsu', +] + + +__doctest_requires__ = {("try_all_threshold",): ["matpotlib"]} + + +def _try_all(image, methods=None, figsize=None, num_cols=2, verbose=True): + """Returns a figure comparing the outputs of different methods. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + methods : dict, optional + Names and associated functions. + Functions must take and return an image. + figsize : tuple, optional + Figure size (in inches). + num_cols : int, optional + Number of columns. + verbose : bool, optional + Print function name for each method. + + Returns + ------- + fig, ax : tuple + Matplotlib figure and axes. + """ + from matplotlib import pyplot as plt + + # Compute the image histogram for better performances + nbins = 256 # Default in threshold functions + hist = histogram(image.reshape(-1), nbins, source_range='image') + + # Handle default value + methods = methods or {} + + num_rows = math.ceil((len(methods) + 1.0) / num_cols) + fig, ax = plt.subplots( + num_rows, num_cols, figsize=figsize, sharex=True, sharey=True + ) + ax = ax.reshape(-1) + + ax[0].imshow(image, cmap=plt.cm.gray) + ax[0].set_title('Original') + + i = 1 + for name, func in methods.items(): + # Use precomputed histogram for supporting functions + sig = inspect.signature(func) + _kwargs = dict(hist=hist) if 'hist' in sig.parameters else {} + + ax[i].set_title(name) + try: + ax[i].imshow(func(image, **_kwargs), cmap=plt.cm.gray) + except Exception as e: + ax[i].text( + 0.5, + 0.5, + f"{type(e).__name__}", + ha="center", + va="center", + transform=ax[i].transAxes, + ) + i += 1 + if verbose: + print(func.__orifunc__) + + for a in ax: + a.axis('off') + + fig.tight_layout() + return fig, ax + + +@require("matplotlib", ">=3.3") +def try_all_threshold(image, figsize=(8, 5), verbose=True): + """Returns a figure comparing the outputs of different thresholding methods. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + figsize : tuple, optional + Figure size (in inches). + verbose : bool, optional + Print function name for each method. + + Returns + ------- + fig, ax : tuple + Matplotlib figure and axes. + + Notes + ----- + The following algorithms are used: + + * isodata + * li + * mean + * minimum + * otsu + * triangle + * yen + + Examples + -------- + >>> from skimage.data import text + >>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False) + """ + + def thresh(func): + """ + A wrapper function to return a thresholded image. + """ + + def wrapper(im): + return im > func(im) + + try: + wrapper.__orifunc__ = func.__orifunc__ + except AttributeError: + wrapper.__orifunc__ = func.__module__ + '.' + func.__name__ + return wrapper + + # Global algorithms. + methods = OrderedDict( + { + 'Isodata': thresh(threshold_isodata), + 'Li': thresh(threshold_li), + 'Mean': thresh(threshold_mean), + 'Minimum': thresh(threshold_minimum), + 'Otsu': thresh(threshold_otsu), + 'Triangle': thresh(threshold_triangle), + 'Yen': thresh(threshold_yen), + } + ) + + return _try_all(image, figsize=figsize, methods=methods, verbose=verbose) + + +def threshold_local( + image, block_size=3, method='gaussian', offset=0, mode='reflect', param=None, cval=0 +): + """Compute a threshold mask image based on local pixel neighborhood. + + Also known as adaptive or dynamic thresholding. The threshold value is + the weighted mean for the local neighborhood of a pixel subtracted by a + constant. Alternatively the threshold can be determined dynamically by a + given function, using the 'generic' method. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + block_size : int or sequence of int + Odd size of pixel neighborhood which is used to calculate the + threshold value (e.g. 3, 5, 7, ..., 21, ...). + method : {'generic', 'gaussian', 'mean', 'median'}, optional + Method used to determine adaptive threshold for local neighborhood in + weighted mean image. + + * 'generic': use custom function (see ``param`` parameter) + * 'gaussian': apply gaussian filter (see ``param`` parameter for custom\ + sigma value) + * 'mean': apply arithmetic mean filter + * 'median': apply median rank filter + + By default, the 'gaussian' method is used. + offset : float, optional + Constant subtracted from weighted mean of neighborhood to calculate + the local threshold value. Default offset is 0. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The mode parameter determines how the array borders are handled, where + cval is the value when mode is equal to 'constant'. + Default is 'reflect'. + param : {int, function}, optional + Either specify sigma for 'gaussian' method or function object for + 'generic' method. This functions takes the flat array of local + neighborhood as a single argument and returns the calculated + threshold for the centre pixel. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold image. All pixels in the input image higher than the + corresponding pixel in the threshold image are considered foreground. + + References + ---------- + .. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing + (2nd Edition)." Prentice-Hall Inc., 2002: 600--612. + ISBN: 0-201-18075-8 + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera()[:50, :50] + >>> binary_image1 = image > threshold_local(image, 15, 'mean') + >>> func = lambda arr: arr.mean() + >>> binary_image2 = image > threshold_local(image, 15, 'generic', + ... param=func) + + """ + + if np.isscalar(block_size): + block_size = (block_size,) * image.ndim + elif len(block_size) != image.ndim: + raise ValueError("len(block_size) must equal image.ndim.") + block_size = tuple(block_size) + if any(b % 2 == 0 for b in block_size): + raise ValueError( + f'block_size must be odd! Given block_size ' + f'{block_size} contains even values.' + ) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + thresh_image = np.zeros(image.shape, dtype=float_dtype) + if method == 'generic': + ndi.generic_filter( + image, param, block_size, output=thresh_image, mode=mode, cval=cval + ) + elif method == 'gaussian': + if param is None: + # automatically determine sigma which covers > 99% of distribution + sigma = tuple([(b - 1) / 6.0 for b in block_size]) + else: + sigma = param + gaussian(image, sigma=sigma, out=thresh_image, mode=mode, cval=cval) + elif method == 'mean': + ndi.uniform_filter(image, block_size, output=thresh_image, mode=mode, cval=cval) + elif method == 'median': + ndi.median_filter(image, block_size, output=thresh_image, mode=mode, cval=cval) + else: + raise ValueError( + "Invalid method specified. Please use `generic`, " + "`gaussian`, `mean`, or `median`." + ) + + return thresh_image - offset + + +def _validate_image_histogram(image, hist, nbins=None, normalize=False): + """Ensure that either image or hist were given, return valid histogram. + + If hist is given, image is ignored. + + Parameters + ---------- + image : array or None + Grayscale image. + hist : array, 2-tuple of array, or None + Histogram, either a 1D counts array, or an array of counts together + with an array of bin centers. + nbins : int, optional + The number of bins with which to compute the histogram, if `hist` is + None. + normalize : bool + If hist is not given, it will be computed by this function. This + parameter determines whether the computed histogram is normalized + (i.e. entries sum up to 1) or not. + + Returns + ------- + counts : 1D array of float + Each element is the number of pixels falling in each intensity bin. + bin_centers : 1D array + Each element is the value corresponding to the center of each intensity + bin. + + Raises + ------ + ValueError : if image and hist are both None + """ + if image is None and hist is None: + raise Exception("Either image or hist must be provided.") + + if hist is not None: + if isinstance(hist, (tuple, list)): + counts, bin_centers = hist + else: + counts = hist + bin_centers = np.arange(counts.size) + + if counts[0] == 0 or counts[-1] == 0: + # Trim histogram from both ends by removing starting and + # ending zeroes as in histogram(..., source_range="image") + cond = counts > 0 + start = np.argmax(cond) + end = cond.size - np.argmax(cond[::-1]) + counts, bin_centers = counts[start:end], bin_centers[start:end] + else: + counts, bin_centers = histogram( + image.reshape(-1), nbins, source_range='image', normalize=normalize + ) + return counts.astype('float32', copy=False), bin_centers + + +def threshold_otsu(image=None, nbins=256, *, hist=None): + """Return threshold value based on Otsu's method. + + Either image or hist must be provided. If hist is provided, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. If no hist provided, + this function will compute it from the image. + + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Wikipedia, https://en.wikipedia.org/wiki/Otsu's_Method + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_otsu(image) + >>> binary = image <= thresh + + Notes + ----- + The input image must be grayscale. + """ + if image is not None and image.ndim > 2 and image.shape[-1] in (3, 4): + warn( + f'threshold_otsu is expected to work correctly only for ' + f'grayscale images; image shape {image.shape} looks like ' + f'that of an RGB image.' + ) + + # Check if the image has more than one intensity value; if not, return that + # value + if image is not None: + first_pixel = image.reshape(-1)[0] + if np.all(image == first_pixel): + return first_pixel + + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # class probabilities for all possible thresholds + weight1 = np.cumsum(counts) + weight2 = np.cumsum(counts[::-1])[::-1] + # class means for all possible thresholds + mean1 = np.cumsum(counts * bin_centers) / weight1 + mean2 = (np.cumsum((counts * bin_centers)[::-1]) / weight2[::-1])[::-1] + + # Clip ends to align class 1 and class 2 variables: + # The last value of ``weight1``/``mean1`` should pair with zero values in + # ``weight2``/``mean2``, which do not exist. + variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2 + + idx = np.argmax(variance12) + threshold = bin_centers[idx] + + return threshold + + +def threshold_yen(image=None, nbins=256, *, hist=None): + """Return threshold value based on Yen's method. + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. + An alternative use of this function is to pass it only hist. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion + for Automatic Multilevel Thresholding" IEEE Trans. on Image + Processing, 4(3): 370-378. :DOI:`10.1109/83.366472` + .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165, :DOI:`10.1117/1.1631315` + http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf + .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_yen(image) + >>> binary = image <= thresh + """ + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # On blank images (e.g. filled with 0) with int dtype, `histogram()` + # returns ``bin_centers`` containing only one value. Speed up with it. + if bin_centers.size == 1: + return bin_centers[0] + + # Calculate probability mass function + pmf = counts.astype('float32', copy=False) / counts.sum() + P1 = np.cumsum(pmf) # Cumulative normalized histogram + P1_sq = np.cumsum(pmf**2) + # Get cumsum calculated from end of squared array: + P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1] + # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid + # '-inf' in crit. ImageJ Yen implementation replaces those values by zero. + crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) * (P1[:-1] * (1.0 - P1[:-1])) ** 2) + return bin_centers[crit.argmax()] + + +def threshold_isodata(image=None, nbins=256, return_all=False, *, hist=None): + """Return threshold value(s) based on ISODATA method. + + Histogram-based threshold, known as Ridler-Calvard method or inter-means. + Threshold values returned satisfy the following equality:: + + threshold = (image[image <= threshold].mean() + + image[image > threshold].mean()) / 2.0 + + That is, returned thresholds are intensities that separate the image into + two groups of pixels, where the threshold intensity is midway between the + mean intensities of these groups. + + For integer images, the above equality holds to within one; for floating- + point images, the equality holds to within the histogram bin-width. + + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + return_all : bool, optional + If False (default), return only the lowest threshold that satisfies + the above equality. If True, return all valid thresholds. + hist : array, or 2-tuple of arrays, optional + Histogram to determine the threshold from and a corresponding array + of bin center intensities. Alternatively, only the histogram can be + passed. + + Returns + ------- + threshold : float or int or array + Threshold value(s). + + References + ---------- + .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an + iterative selection method" + IEEE Transactions on Systems, Man and Cybernetics 8: 630-632, + :DOI:`10.1109/TSMC.1978.4310039` + .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165, + http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf + :DOI:`10.1117/1.1631315` + .. [3] ImageJ AutoThresholder code, + http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import coins + >>> image = coins() + >>> thresh = threshold_isodata(image) + >>> binary = image > thresh + """ + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # image only contains one unique value + if len(bin_centers) == 1: + if return_all: + return bin_centers + else: + return bin_centers[0] + + counts = counts.astype('float32', copy=False) + + # csuml and csumh contain the count of pixels in that bin or lower, and + # in all bins strictly higher than that bin, respectively + csuml = np.cumsum(counts) + csumh = csuml[-1] - csuml + + # intensity_sum contains the total pixel intensity from each bin + intensity_sum = counts * bin_centers + + # l and h contain average value of all pixels in that bin or lower, and + # in all bins strictly higher than that bin, respectively. + # Note that since exp.histogram does not include empty bins at the low or + # high end of the range, csuml and csumh are strictly > 0, except in the + # last bin of csumh, which is zero by construction. + # So no worries about division by zero in the following lines, except + # for the last bin, but we can ignore that because no valid threshold + # can be in the top bin. + # To avoid the division by zero, we simply skip over the last element in + # all future computation. + csum_intensity = np.cumsum(intensity_sum) + lower = csum_intensity[:-1] / csuml[:-1] + higher = (csum_intensity[-1] - csum_intensity[:-1]) / csumh[:-1] + + # isodata finds threshold values that meet the criterion t = (l + m)/2 + # where l is the mean of all pixels <= t and h is the mean of all pixels + # > t, as calculated above. So we are looking for places where + # (l + m) / 2 equals the intensity value for which those l and m figures + # were calculated -- which is, of course, the histogram bin centers. + # We only require this equality to be within the precision of the bin + # width, of course. + all_mean = (lower + higher) / 2.0 + bin_width = bin_centers[1] - bin_centers[0] + + # Look only at thresholds that are below the actual all_mean value, + # for consistency with the threshold being included in the lower pixel + # group. Otherwise, can get thresholds that are not actually fixed-points + # of the isodata algorithm. For float images, this matters less, since + # there really can't be any guarantees anymore anyway. + distances = all_mean - bin_centers[:-1] + thresholds = bin_centers[:-1][(distances >= 0) & (distances < bin_width)] + + if return_all: + return thresholds + else: + return thresholds[0] + + +# Computing a histogram using np.histogram on a uint8 image with bins=256 +# doesn't work and results in aliasing problems. We use a fully specified set +# of bins to ensure that each uint8 value false into its own bin. +_DEFAULT_ENTROPY_BINS = tuple(np.arange(-0.5, 255.51, 1)) + + +def _cross_entropy(image, threshold, bins=_DEFAULT_ENTROPY_BINS): + """Compute cross-entropy between distributions above and below a threshold. + + Parameters + ---------- + image : array + The input array of values. + threshold : float + The value dividing the foreground and background in ``image``. + bins : int or array of float, optional + The number of bins or the bin edges. (Any valid value to the ``bins`` + argument of ``np.histogram`` will work here.) For an exact calculation, + each unique value should have its own bin. The default value for bins + ensures exact handling of uint8 images: ``bins=256`` results in + aliasing problems due to bin width not being equal to 1. + + Returns + ------- + nu : float + The cross-entropy target value as defined in [1]_. + + Notes + ----- + See Li and Lee, 1993 [1]_; this is the objective function ``threshold_li`` + minimizes. This function can be improved but this implementation most + closely matches equation 8 in [1]_ and equations 1-3 in [2]_. + + References + ---------- + .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding" + Pattern Recognition, 26(4): 617-625 + :DOI:`10.1016/0031-3203(93)90115-D` + .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum + Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776 + :DOI:`10.1016/S0167-8655(98)00057-9` + """ + histogram, bin_edges = np.histogram(image, bins=bins, density=True) + bin_centers = np.convolve(bin_edges, [0.5, 0.5], mode='valid') + t = np.flatnonzero(bin_centers > threshold)[0] + m0a = np.sum(histogram[:t]) # 0th moment, background + m0b = np.sum(histogram[t:]) + m1a = np.sum(histogram[:t] * bin_centers[:t]) # 1st moment, background + m1b = np.sum(histogram[t:] * bin_centers[t:]) + mua = m1a / m0a # mean value, background + mub = m1b / m0b + nu = -m1a * np.log(mua) - m1b * np.log(mub) + return nu + + +def threshold_li(image, *, tolerance=None, initial_guess=None, iter_callback=None): + """Compute threshold value by Li's iterative Minimum Cross Entropy method. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + tolerance : float, optional + Finish the computation when the change in the threshold in an iteration + is less than this value. By default, this is half the smallest + difference between intensity values in ``image``. + initial_guess : float or Callable[[array[float]], float], optional + Li's iterative method uses gradient descent to find the optimal + threshold. If the image intensity histogram contains more than two + modes (peaks), the gradient descent could get stuck in a local optimum. + An initial guess for the iteration can help the algorithm find the + globally-optimal threshold. A float value defines a specific start + point, while a callable should take in an array of image intensities + and return a float value. Example valid callables include + ``numpy.mean`` (default), ``lambda arr: numpy.quantile(arr, 0.95)``, + or even :func:`skimage.filters.threshold_otsu`. + iter_callback : Callable[[float], Any], optional + A function that will be called on the threshold at every iteration of + the algorithm. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding" + Pattern Recognition, 26(4): 617-625 + :DOI:`10.1016/0031-3203(93)90115-D` + .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum + Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776 + :DOI:`10.1016/S0167-8655(98)00057-9` + .. [3] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165 + :DOI:`10.1117/1.1631315` + .. [4] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_li(image) + >>> binary = image > thresh + """ + # Remove nan: + image = image[~np.isnan(image)] + if image.size == 0: + return np.nan + + # Make sure image has more than one value; otherwise, return that value + # This works even for np.inf + if np.all(image == image.flat[0]): + return image.flat[0] + + # At this point, the image only contains np.inf, -np.inf, or valid numbers + image = image[np.isfinite(image)] + # if there are no finite values in the image, return 0. This is because + # at this point we *know* that there are *both* inf and -inf values, + # because inf == inf evaluates to True. We might as well separate them. + if image.size == 0: + return 0.0 + + # Li's algorithm requires positive image (because of log(mean)) + image_min = np.min(image) + image -= image_min + if image.dtype.kind in 'iu': + tolerance = tolerance or 0.5 + else: + tolerance = tolerance or np.min(np.diff(np.unique(image))) / 2 + + # Initial estimate for iteration. See "initial_guess" in the parameter list + if initial_guess is None: + t_next = np.mean(image) + elif callable(initial_guess): + t_next = initial_guess(image) + elif np.isscalar(initial_guess): # convert to new, positive image range + t_next = initial_guess - float(image_min) + image_max = np.max(image) + image_min + if not 0 < t_next < np.max(image): + msg = ( + f'The initial guess for threshold_li must be within the ' + f'range of the image. Got {initial_guess} for image min ' + f'{image_min} and max {image_max}.' + ) + raise ValueError(msg) + t_next = image.dtype.type(t_next) + else: + raise TypeError( + 'Incorrect type for `initial_guess`; should be ' + 'a floating point value, or a function mapping an ' + 'array to a floating point value.' + ) + + # initial value for t_curr must be different from t_next by at + # least the tolerance. Since the image is positive, we ensure this + # by setting to a large-enough negative number + t_curr = -2 * tolerance + + # Callback on initial iterations + if iter_callback is not None: + iter_callback(t_next + image_min) + + # Stop the iterations when the difference between the + # new and old threshold values is less than the tolerance + # or if the background mode has only one value left, + # since log(0) is not defined. + + if image.dtype.kind in 'iu': + hist, bin_centers = histogram(image.reshape(-1), source_range='image') + hist = hist.astype('float32', copy=False) + while abs(t_next - t_curr) > tolerance: + t_curr = t_next + foreground = bin_centers > t_curr + background = ~foreground + + mean_fore = np.average(bin_centers[foreground], weights=hist[foreground]) + mean_back = np.average(bin_centers[background], weights=hist[background]) + + if mean_back == 0: + break + + t_next = (mean_back - mean_fore) / (np.log(mean_back) - np.log(mean_fore)) + + if iter_callback is not None: + iter_callback(t_next + image_min) + + else: + while abs(t_next - t_curr) > tolerance: + t_curr = t_next + foreground = image > t_curr + mean_fore = np.mean(image[foreground]) + mean_back = np.mean(image[~foreground]) + + if mean_back == 0.0: + break + + t_next = (mean_back - mean_fore) / (np.log(mean_back) - np.log(mean_fore)) + + if iter_callback is not None: + iter_callback(t_next + image_min) + + threshold = t_next + image_min + return threshold + + +def threshold_minimum(image=None, nbins=256, max_num_iter=10000, *, hist=None): + """Return threshold value based on minimum method. + + The histogram of the input ``image`` is computed if not provided and + smoothed until there are only two maxima. Then the minimum in between is + the threshold value. + + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + max_num_iter : int, optional + Maximum number of iterations to smooth the histogram. + hist : array, or 2-tuple of arrays, optional + Histogram to determine the threshold from and a corresponding array + of bin center intensities. Alternatively, only the histogram can be + passed. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + Raises + ------ + RuntimeError + If unable to find two local maxima in the histogram or if the + smoothing takes more than 1e4 iterations. + + References + ---------- + .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding + algorithms," CVGIP: Graphical Models and Image Processing, + vol. 55, pp. 532-537, 1993. + .. [2] Prewitt, JMS & Mendelsohn, ML (1966), "The analysis of cell + images", Annals of the New York Academy of Sciences 128: 1035-1053 + :DOI:`10.1111/j.1749-6632.1965.tb11715.x` + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_minimum(image) + >>> binary = image > thresh + """ + + def find_local_maxima_idx(hist): + # We can't use scipy.signal.argrelmax + # as it fails on plateaus + maximum_idxs = list() + direction = 1 + + for i in range(hist.shape[0] - 1): + if direction > 0: + if hist[i + 1] < hist[i]: + direction = -1 + maximum_idxs.append(i) + else: + if hist[i + 1] > hist[i]: + direction = 1 + + return maximum_idxs + + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + smooth_hist = counts.astype('float32', copy=False) + + for counter in range(max_num_iter): + smooth_hist = ndi.uniform_filter1d(smooth_hist, 3) + maximum_idxs = find_local_maxima_idx(smooth_hist) + if len(maximum_idxs) < 3: + break + + if len(maximum_idxs) != 2: + raise RuntimeError('Unable to find two maxima in histogram') + elif counter == max_num_iter - 1: + raise RuntimeError('Maximum iteration reached for histogram' 'smoothing') + + # Find the lowest point between the maxima + threshold_idx = np.argmin(smooth_hist[maximum_idxs[0] : maximum_idxs[1] + 1]) + + return bin_centers[maximum_idxs[0] + threshold_idx] + + +def threshold_mean(image): + """Return threshold value based on the mean of grayscale values. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding + algorithms," CVGIP: Graphical Models and Image Processing, + vol. 55, pp. 532-537, 1993. + :DOI:`10.1006/cgip.1993.1040` + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_mean(image) + >>> binary = image > thresh + """ + return np.mean(image) + + +def threshold_triangle(image, nbins=256): + """Return threshold value based on the triangle algorithm. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Zack, G. W., Rogers, W. E. and Latt, S. A., 1977, + Automatic Measurement of Sister Chromatid Exchange Frequency, + Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753 + :DOI:`10.1177/25.7.70454` + .. [2] ImageJ AutoThresholder code, + http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_triangle(image) + >>> binary = image > thresh + """ + # nbins is ignored for integer arrays + # so, we recalculate the effective nbins. + hist, bin_centers = histogram(image.reshape(-1), nbins, source_range='image') + nbins = len(hist) + + # Find peak, lowest and highest gray levels. + arg_peak_height = np.argmax(hist) + peak_height = hist[arg_peak_height] + arg_low_level, arg_high_level = np.flatnonzero(hist)[[0, -1]] + + if arg_low_level == arg_high_level: + # Image has constant intensity. + return image.ravel()[0] + + # Flip is True if left tail is shorter. + flip = arg_peak_height - arg_low_level < arg_high_level - arg_peak_height + if flip: + hist = hist[::-1] + arg_low_level = nbins - arg_high_level - 1 + arg_peak_height = nbins - arg_peak_height - 1 + + # If flip == True, arg_high_level becomes incorrect + # but we don't need it anymore. + del arg_high_level + + # Set up the coordinate system. + width = arg_peak_height - arg_low_level + x1 = np.arange(width) + y1 = hist[x1 + arg_low_level] + + # Normalize. + norm = np.sqrt(peak_height**2 + width**2) + peak_height /= norm + width /= norm + + # Maximize the length. + # The ImageJ implementation includes an additional constant when calculating + # the length, but here we omit it as it does not affect the location of the + # minimum. + length = peak_height * x1 - width * y1 + arg_level = np.argmax(length) + arg_low_level + + if flip: + arg_level = nbins - arg_level - 1 + + return bin_centers[arg_level] + + +def _mean_std(image, w): + """Return local mean and standard deviation of each pixel using a + neighborhood defined by a rectangular window size ``w``. + The algorithm uses integral images to speedup computation. This is + used by :func:`threshold_niblack` and :func:`threshold_sauvola`. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + w : int, or iterable of int + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + + Returns + ------- + m : ndarray of float, same shape as ``image`` + Local mean of the image. + s : ndarray of float, same shape as ``image`` + Local standard deviation of the image. + + References + ---------- + .. [1] F. Shafait, D. Keysers, and T. M. Breuel, "Efficient + implementation of local adaptive thresholding techniques + using integral images." in Document Recognition and + Retrieval XV, (San Jose, USA), Jan. 2008. + :DOI:`10.1117/12.767755` + """ + + if not isinstance(w, Iterable): + w = (w,) * image.ndim + _validate_window_size(w) + + float_dtype = _supported_float_type(image.dtype) + pad_width = tuple((k // 2 + 1, k // 2) for k in w) + padded = np.pad(image.astype(float_dtype, copy=False), pad_width, mode='reflect') + + # Note: keep float64 integral images for accuracy. Outputs of + # _correlate_sparse can later be safely cast to float_dtype + integral = integral_image(padded, dtype=np.float64) + padded *= padded + integral_sq = integral_image(padded, dtype=np.float64) + + # Create lists of non-zero kernel indices and values + kernel_indices = list(itertools.product(*tuple([(0, _w) for _w in w]))) + kernel_values = [ + (-1) ** (image.ndim % 2 != np.sum(indices) % 2) for indices in kernel_indices + ] + + total_window_size = math.prod(w) + kernel_shape = tuple(_w + 1 for _w in w) + m = _correlate_sparse(integral, kernel_shape, kernel_indices, kernel_values) + m = m.astype(float_dtype, copy=False) + m /= total_window_size + g2 = _correlate_sparse(integral_sq, kernel_shape, kernel_indices, kernel_values) + g2 = g2.astype(float_dtype, copy=False) + g2 /= total_window_size + # Note: we use np.clip because g2 is not guaranteed to be greater than + # m*m when floating point error is considered + s = np.sqrt(np.clip(g2 - m * m, 0, None)) + return m, s + + +def threshold_niblack(image, window_size=15, k=0.2): + """Applies Niblack local threshold to an array. + + A threshold T is calculated for every pixel in the image using the + following formula:: + + T = m(x,y) - k * s(x,y) + + where m(x,y) and s(x,y) are the mean and standard deviation of + pixel (x,y) neighborhood defined by a rectangular window with size w + times w centered around the pixel. k is a configurable parameter + that weights the effect of standard deviation. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + window_size : int, or iterable of int, optional + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + k : float, optional + Value of parameter k in threshold formula. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold mask. All pixels with an intensity higher than + this value are assumed to be foreground. + + Notes + ----- + This algorithm is originally designed for text recognition. + + The Bradley threshold is a particular case of the Niblack + one, being equivalent to + + >>> from skimage import data + >>> image = data.page() + >>> q = 1 + >>> threshold_image = threshold_niblack(image, k=0) * q + + for some value ``q``. By default, Bradley and Roth use ``q=1``. + + + References + ---------- + .. [1] W. Niblack, An introduction to Digital Image Processing, + Prentice-Hall, 1986. + .. [2] D. Bradley and G. Roth, "Adaptive thresholding using Integral + Image", Journal of Graphics Tools 12(2), pp. 13-21, 2007. + :DOI:`10.1080/2151237X.2007.10129236` + + Examples + -------- + >>> from skimage import data + >>> image = data.page() + >>> threshold_image = threshold_niblack(image, window_size=7, k=0.1) + """ + m, s = _mean_std(image, window_size) + return m - k * s + + +def threshold_sauvola(image, window_size=15, k=0.2, r=None): + """Applies Sauvola local threshold to an array. Sauvola is a + modification of Niblack technique. + + In the original method a threshold T is calculated for every pixel + in the image using the following formula:: + + T = m(x,y) * (1 + k * ((s(x,y) / R) - 1)) + + where m(x,y) and s(x,y) are the mean and standard deviation of + pixel (x,y) neighborhood defined by a rectangular window with size w + times w centered around the pixel. k is a configurable parameter + that weights the effect of standard deviation. + R is the maximum standard deviation of a grayscale image. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + window_size : int, or iterable of int, optional + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + k : float, optional + Value of the positive parameter k. + r : float, optional + Value of R, the dynamic range of standard deviation. + If None, set to the half of the image dtype range. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold mask. All pixels with an intensity higher than + this value are assumed to be foreground. + + Notes + ----- + This algorithm is originally designed for text recognition. + + References + ---------- + .. [1] J. Sauvola and M. Pietikainen, "Adaptive document image + binarization," Pattern Recognition 33(2), + pp. 225-236, 2000. + :DOI:`10.1016/S0031-3203(99)00055-2` + + Examples + -------- + >>> from skimage import data + >>> image = data.page() + >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2) + >>> binary_image = image > t_sauvola + """ + if r is None: + imin, imax = dtype_limits(image, clip_negative=False) + r = 0.5 * (imax - imin) + m, s = _mean_std(image, window_size) + return m * (1 + k * ((s / r) - 1)) + + +def apply_hysteresis_threshold(image, low, high): + """Apply hysteresis thresholding to ``image``. + + This algorithm finds regions where ``image`` is greater than ``high`` + OR ``image`` is greater than ``low`` *and* that region is connected to + a region greater than ``high``. + + Parameters + ---------- + image : (M[, ...]) ndarray + Grayscale input image. + low : float, or array of same shape as ``image`` + Lower threshold. + high : float, or array of same shape as ``image`` + Higher threshold. + + Returns + ------- + thresholded : (M[, ...]) array of bool + Array in which ``True`` indicates the locations where ``image`` + was above the hysteresis threshold. + + Examples + -------- + >>> image = np.array([1, 2, 3, 2, 1, 2, 1, 3, 2]) + >>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int) + array([0, 1, 1, 1, 0, 0, 0, 1, 1]) + + References + ---------- + .. [1] J. Canny. A computational approach to edge detection. + IEEE Transactions on Pattern Analysis and Machine Intelligence. + 1986; vol. 8, pp.679-698. + :DOI:`10.1109/TPAMI.1986.4767851` + """ + low = np.clip(low, a_min=None, a_max=high) # ensure low always below high + mask_low = image > low + mask_high = image > high + # Connected components of mask_low + labels_low, num_labels = ndi.label(mask_low) + # Check which connected components contain pixels from mask_high + sums = ndi.sum(mask_high, labels_low, np.arange(num_labels + 1)) + connected_to_high = sums > 0 + thresholded = connected_to_high[labels_low] + return thresholded + + +def threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None): + r"""Generate `classes`-1 threshold values to divide gray levels in `image`, + following Otsu's method for multiple classes. + + The threshold values are chosen to maximize the total sum of pairwise + variances between the thresholded graylevel classes. See Notes and [1]_ + for more details. + + Either image or hist must be provided. If hist is provided, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + classes : int, optional + Number of classes to be thresholded, i.e. the number of resulting + regions. + nbins : int, optional + Number of bins used to calculate the histogram. This value is ignored + for integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. If no hist provided, + this function will compute it from the image (see notes). + + Returns + ------- + thresh : array + Array containing the threshold values for the desired classes. + + Raises + ------ + ValueError + If ``image`` contains less grayscale value then the desired + number of classes. + + Notes + ----- + This implementation relies on a Cython function whose complexity + is :math:`O\left(\frac{Ch^{C-1}}{(C-1)!}\right)`, where :math:`h` + is the number of histogram bins and :math:`C` is the number of + classes desired. + + If no hist is given, this function will make use of + `skimage.exposure.histogram`, which behaves differently than + `np.histogram`. While both allowed, use the former for consistent + behaviour. + + The input image must be grayscale. + + References + ---------- + .. [1] Liao, P-S., Chen, T-S. and Chung, P-C., "A fast algorithm for + multilevel thresholding", Journal of Information Science and + Engineering 17 (5): 713-727, 2001. Available at: + + :DOI:`10.6688/JISE.2001.17.5.1` + .. [2] Tosa, Y., "Multi-Otsu Threshold", a java plugin for ImageJ. + Available at: + + + Examples + -------- + >>> from skimage.color import label2rgb + >>> from skimage import data + >>> image = data.camera() + >>> thresholds = threshold_multiotsu(image) + >>> regions = np.digitize(image, bins=thresholds) + >>> regions_colorized = label2rgb(regions) + """ + if image is not None and image.ndim > 2 and image.shape[-1] in (3, 4): + warn( + f'threshold_multiotsu is expected to work correctly only for ' + f'grayscale images; image shape {image.shape} looks like ' + f'that of an RGB image.' + ) + + # calculating the histogram and the probability of each gray level. + prob, bin_centers = _validate_image_histogram(image, hist, nbins, normalize=True) + prob = prob.astype('float32', copy=False) + + nvalues = np.count_nonzero(prob) + if nvalues < classes: + msg = ( + f'After discretization into bins, the input image has ' + f'only {nvalues} different values. It cannot be thresholded ' + f'in {classes} classes. If there are more unique values ' + f'before discretization, try increasing the number of bins ' + f'(`nbins`).' + ) + raise ValueError(msg) + elif nvalues == classes: + thresh_idx = np.flatnonzero(prob)[:-1] + else: + # Get threshold indices + try: + thresh_idx = _get_multiotsu_thresh_indices_lut(prob, classes - 1) + except MemoryError: + # Don't use LUT if the number of bins is too large (if the + # image is uint16 for example): in this case, the + # allocated memory is too large. + thresh_idx = _get_multiotsu_thresh_indices(prob, classes - 1) + + thresh = bin_centers[thresh_idx] + + return thresh diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner_luts.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner_luts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbd89d152f2ed5d6009203b554c5804e365e618c Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner_luts.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_moments.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_moments.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e1ed939c278939f0952326afc402dec9ae3cfc3 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_moments.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_regionprops_utils.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_regionprops_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59ba226d573448b6aa80360f7d698b7af1adb414 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_regionprops_utils.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/entropy.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/entropy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1b8c7ef24db410da90f0ad2c87c79f35b5cdbf Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/entropy.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__init__.py b/envs/kitoverlay/skimage/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..110d8e8d2144925a548d468a7717d702b5824fe5 --- /dev/null +++ b/envs/kitoverlay/skimage/util/__init__.py @@ -0,0 +1,81 @@ +"""Generic utilities. + +This module contains a number of utility functions to work with images in general. +""" + +import functools +import warnings + +import numpy as np + +# keep .dtype imports first to avoid circular imports +from .dtype import ( + dtype_limits, + img_as_float, + img_as_float32, + img_as_float64, + img_as_bool, + img_as_int, + img_as_ubyte, + img_as_uint, +) +from ._slice_along_axes import slice_along_axes +from ._invert import invert +from ._label import label_points +from ._montage import montage +from ._map_array import map_array +from ._regular_grid import regular_grid, regular_seeds +from .apply_parallel import apply_parallel +from .arraycrop import crop +from .compare import compare_images +from .noise import random_noise +from .shape import view_as_blocks, view_as_windows +from .unique import unique_rows +from .lookfor import lookfor +from .._shared.utils import FailedEstimationAccessError + + +__all__ = [ + 'img_as_float32', + 'img_as_float64', + 'img_as_float', + 'img_as_int', + 'img_as_uint', + 'img_as_ubyte', + 'img_as_bool', + 'dtype_limits', + 'view_as_blocks', + 'view_as_windows', + 'slice_along_axes', + 'crop', + 'compare_images', + 'map_array', + 'montage', + 'random_noise', + 'regular_grid', + 'regular_seeds', + 'apply_parallel', + 'invert', + 'unique_rows', + 'label_points', + 'lookfor', + 'FailedEstimationAccessError', + 'PendingSkimage2Change', +] + + +class PendingSkimage2Change(PendingDeprecationWarning): + """A warning about API usage that will silently change or break in skimage2. + + As a subclass of :class:`PendingDeprecationWarning`, this warning isn't + shown by default. But it can be enabled with a warnings filter to prepare + for code changes related to skimage2 early on: + + .. code-block:: python + + import warnings + import skimage as ski + warnings.filterwarnings( + action="default", category=ski.util.PendingSkimage2Change + ) + """ diff --git a/envs/kitoverlay/skimage/util/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03f971b7079f353d91a2775b2b62617a3f32f55e Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_backends.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_backends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c5decd1aee5370612b52f37accfafc7c2b56bf1 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_backends.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_invert.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_invert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f8996adcdb02901b0e4bd16d971c8f71c6b5d7 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_invert.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_label.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_label.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9f3073d8f4f2b1d27e5103aedae13ae13b4b8c6 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_label.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_map_array.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_map_array.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c65419477713ddd1e4d0d255d0fa47733e63b1a5 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_map_array.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_montage.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_montage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65d3bad9820801219b3b7e572ff1ad5b414f4d6b Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_montage.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_regular_grid.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_regular_grid.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36acba6d07eb567df40b555350f48a6c93b6dbf9 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_regular_grid.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/_slice_along_axes.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/_slice_along_axes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56dab5d5ec9b749315777c27effeb92afaf39da8 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/_slice_along_axes.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/apply_parallel.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/apply_parallel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e37d20bd1a39515c5479d022170556b80373487 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/apply_parallel.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/arraycrop.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/arraycrop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8074dcdab1d704d042eadf44632f7bc56c54147c Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/arraycrop.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/compare.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/compare.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a87d95ecce06fd682951ccd7111f542ac30cb749 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/compare.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/dtype.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/dtype.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f648c3265752db0826a3ba0763d8999473fd23a6 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/dtype.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/lookfor.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/lookfor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dfadd9e52fd15cedb57ff3f8cd98e435176ed95 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/lookfor.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/noise.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/noise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8942c120fe6748dc92a531fc0c221229cc793efa Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/noise.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/shape.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/shape.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c0ee354901a826b3241f392b69500277f73cf30 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/shape.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/__pycache__/unique.cpython-311.pyc b/envs/kitoverlay/skimage/util/__pycache__/unique.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4122d3f5984da4b143f1dd8d98dc4a18b8ca8354 Binary files /dev/null and b/envs/kitoverlay/skimage/util/__pycache__/unique.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/util/_backends.py b/envs/kitoverlay/skimage/util/_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e30897977a8eb73f9d188235674925621aab84 --- /dev/null +++ b/envs/kitoverlay/skimage/util/_backends.py @@ -0,0 +1,146 @@ +import functools +from importlib.metadata import entry_points +from functools import cache +import os +import warnings + + +def dispatching_disabled(): + """Determine if dispatching has been disabled by the user.""" + no_dispatching = os.environ.get("SKIMAGE_NO_DISPATCHING", False) + if no_dispatching == "1": + return True + else: + return False + + +def public_api_module(func): + """Get the name of the public module for a scikit-image function. + + This computes the name of the public submodule in which the function can + be found. + """ + full_name = func.__module__ + # This relies on the fact that scikit-image does not use + # sub-submodules in its public API, except in one case. + # This means that public name can be atmost `skimage.foobar` + # for everything else + + sub_submodules = ["skimage.filters.rank"] + candidates = [name for name in sub_submodules if full_name.startswith(name)] + if len(candidates) == 0: + # Assume first two parts of the name are where the function is in our public API + parts = full_name.split(".") + if len(parts) <= 2: + msg = f"expected {func.__module__=} with more than 2 dot-delimited parts" + raise ValueError(msg) + public_name = ".".join(parts[:2]) + elif len(candidates) == 1: + public_name = candidates[0] + else: + msg = f"{func!r} matches more than one sub-submodule: {candidates!r}" + raise ValueError(msg) + + # It would be nice to sanity check things by doing something like the + # following. However we can't because this code is executed while the + # module is being imported, which means this would create a circular + # import + # mod = importlib.import_module(public_name) + # assert getattr(mod, func.__name__) is func + + return public_name + + +@cache +def all_backends(): + """List all installed backends and information about them.""" + backends = {} + backends_ = entry_points(group="skimage_backends") + backend_infos = entry_points(group="skimage_backend_infos") + + for backend in backends_: + backends[backend.name] = {"implementation": backend} + try: + info = backend_infos[backend.name] + # Double () to load and then call the backend information function + backends[backend.name]["info"] = info.load()() + except KeyError: + pass + + return backends + + +def dispatchable(func): + """Mark a function as dispatchable. + + When a decorated function is called, the installed backends are + searched for an implementation. If no backend implements the function + then the scikit-image implementation is used. + """ + func_name = func.__name__ + func_module = public_api_module(func) + + # If no backends are installed at all or dispatching is disabled, + # return the original function. This way people who don't care about it + # don't see anything related to dispatching + if dispatching_disabled() or not all_backends(): + return func + + @functools.wraps(func) + def wrapper(*args, **kwargs): + # Backends are tried in alphabetical order, this makes things + # predictable and stable across runs. Might need a better solution + # when it becomes common that users have more than one backend + # that would accept a call. + for name in sorted(all_backends()): + backend = all_backends()[name] + # Check if the function we are looking for is implemented in + # the backend + if f"{func_module}:{func_name}" not in backend["info"].supported_functions: + continue + + backend_impl = backend["implementation"].load() + + # Allow the backend to accept/reject a call based on the function + # name and the arguments + wants_it = backend_impl.can_has( + f"{func_module}:{func_name}", *args, **kwargs + ) + if not wants_it: + continue + + func_impl = backend_impl.get_implementation(f"{func_module}:{func_name}") + warnings.warn( + f"Call to '{func_module}:{func_name}' was dispatched to" + f" the '{name}' backend. Set SKIMAGE_NO_DISPATCHING=1 to" + " disable this.", + DispatchNotification, + # XXX from where should this warning originate? + # XXX from where the function that was dispatched was called? + # XXX or from where the user called a function that called + # XXX a function that was dispatched? + stacklevel=2, + ) + return func_impl(*args, **kwargs) + + else: + return func(*args, **kwargs) + + return wrapper + + +class BackendInformation: + """Information about a backend + + A backend that wants to provide additional information about itself + should return an instance of this from its information entry point. + """ + + def __init__(self, supported_functions): + self.supported_functions = supported_functions + + +class DispatchNotification(RuntimeWarning): + """Notification issued when a function is dispatched to a backend.""" + + pass diff --git a/envs/kitoverlay/skimage/util/_invert.py b/envs/kitoverlay/skimage/util/_invert.py new file mode 100644 index 0000000000000000000000000000000000000000..bef2865d5679aa08307022ed14246a29471e6cef --- /dev/null +++ b/envs/kitoverlay/skimage/util/_invert.py @@ -0,0 +1,74 @@ +import numpy as np +from .dtype import dtype_limits + + +def invert(image, signed_float=False): + """Invert an image. + + Invert the intensity range of the input image, so that the dtype maximum + is now the dtype minimum, and vice-versa. This operation is + slightly different depending on the input dtype: + + - unsigned integers: subtract the image from the dtype maximum + - signed integers: subtract the image from -1 (see Notes) + - floats: subtract the image from 1 (if signed_float is False, so we + assume the image is unsigned), or from 0 (if signed_float is True). + + See the examples for clarification. + + Parameters + ---------- + image : ndarray + Input image. + signed_float : bool, optional + If True and the image is of type float, the range is assumed to + be [-1, 1]. If False and the image is of type float, the range is + assumed to be [0, 1]. + + Returns + ------- + inverted : ndarray + Inverted image. + + Notes + ----- + Ideally, for signed integers we would simply multiply by -1. However, + signed integer ranges are asymmetric. For example, for np.int8, the range + of possible values is [-128, 127], so that -128 * -1 equals -128! By + subtracting from -1, we correctly map the maximum dtype value to the + minimum. + + Examples + -------- + >>> img = np.array([[100, 0, 200], + ... [ 0, 50, 0], + ... [ 30, 0, 255]], np.uint8) + >>> invert(img) + array([[155, 255, 55], + [255, 205, 255], + [225, 255, 0]], dtype=uint8) + >>> img2 = np.array([[ -2, 0, -128], + ... [127, 0, 5]], np.int8) + >>> invert(img2) + array([[ 1, -1, 127], + [-128, -1, -6]], dtype=int8) + >>> img3 = np.array([[ 0., 1., 0.5, 0.75]]) + >>> invert(img3) + array([[1. , 0. , 0.5 , 0.25]]) + >>> img4 = np.array([[ 0., 1., -1., -0.25]]) + >>> invert(img4, signed_float=True) + array([[-0. , -1. , 1. , 0.25]]) + """ + if image.dtype == 'bool': + inverted = ~image + elif np.issubdtype(image.dtype, np.unsignedinteger): + max_val = dtype_limits(image, clip_negative=False)[1] + inverted = np.subtract(max_val, image, dtype=image.dtype) + elif np.issubdtype(image.dtype, np.signedinteger): + inverted = np.subtract(-1, image, dtype=image.dtype) + else: # float dtype + if signed_float: + inverted = -image + else: + inverted = np.subtract(1, image, dtype=image.dtype) + return inverted diff --git a/envs/kitoverlay/skimage/util/_label.py b/envs/kitoverlay/skimage/util/_label.py new file mode 100644 index 0000000000000000000000000000000000000000..70b48944842ade82b6f56c388d4bca795b8bb73c --- /dev/null +++ b/envs/kitoverlay/skimage/util/_label.py @@ -0,0 +1,51 @@ +import numpy as np + +__all__ = ["label_points"] + + +def label_points(coords, output_shape): + """Assign unique integer labels to coordinates on an image mask + + Parameters + ---------- + coords : ndarray + An array of N coordinates with dimension D + output_shape : tuple + The shape of the mask on which `coords` are labelled + + Returns + ------- + labels: ndarray + A mask of zeroes containing unique integer labels at the `coords` + + Examples + -------- + >>> import numpy as np + >>> from skimage.util._label import label_points + >>> coords = np.array([[0, 1], [2, 2]]) + >>> output_shape = (5, 5) + >>> mask = label_points(coords, output_shape) + >>> mask + array([[0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 2, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint64) + + Notes + ----- + - The labels are assigned to coordinates that are converted to + integer and considered to start from 0. + - Coordinates that are out of range of the mask raise an IndexError. + - Negative coordinates raise a ValueError + """ + if coords.shape[1] != len(output_shape): + raise ValueError("Dimensionality of points should match the " "output shape") + + if np.any(coords < 0): + raise ValueError("Coordinates should be positive and start from 0") + + np_indices = tuple(np.transpose(np.round(coords).astype(int, copy=False))) + labels = np.zeros(output_shape, dtype=np.uint64) + labels[np_indices] = np.arange(1, coords.shape[0] + 1) + return labels diff --git a/envs/kitoverlay/skimage/util/_map_array.py b/envs/kitoverlay/skimage/util/_map_array.py new file mode 100644 index 0000000000000000000000000000000000000000..92b01d8882889366673654a42b760fa335f9592d --- /dev/null +++ b/envs/kitoverlay/skimage/util/_map_array.py @@ -0,0 +1,199 @@ +import numpy as np + + +def map_array(input_arr, input_vals, output_vals, out=None): + """Map values from input array from input_vals to output_vals. + + Parameters + ---------- + input_arr : array of int, shape (M[, ...]) + The input label image. + input_vals : array of int, shape (K,) + The values to map from. + output_vals : array, shape (K,) + The values to map to. + out : array, same shape as `input_arr` + The output array. Will be created if not provided. It should + have the same dtype as `output_vals`. + + Returns + ------- + out : array, same shape as `input_arr` + The array of mapped values. + + Notes + ----- + If `input_arr` contains values that aren't covered by `input_vals`, they + are set to 0. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + >>> ski.util.map_array( + ... input_arr=np.array([[0, 2, 2, 0], [3, 4, 5, 0]]), + ... input_vals=np.array([1, 2, 3, 4, 6]), + ... output_vals=np.array([6, 7, 8, 9, 10]), + ... ) + array([[0, 7, 7, 0], + [8, 9, 0, 0]]) + """ + from ._remap import _map_array + + if not np.issubdtype(input_arr.dtype, np.integer): + raise TypeError('The dtype of an array to be remapped should be integer.') + # We ravel the input array for simplicity of iteration in Cython: + orig_shape = input_arr.shape + # NumPy docs for `np.ravel()` says: + # "When a view is desired in as many cases as possible, + # arr.reshape(-1) may be preferable." + input_arr = input_arr.reshape(-1) + if out is None: + out = np.empty(orig_shape, dtype=output_vals.dtype) + elif out.shape != orig_shape: + raise ValueError( + 'If out array is provided, it should have the same shape as ' + f'the input array. Input array has shape {orig_shape}, provided ' + f'output array has shape {out.shape}.' + ) + try: + out_view = out.view() + out_view.shape = (-1,) # no-copy reshape/ravel + except AttributeError: # if out strides are not compatible with 0-copy + raise ValueError( + 'If out array is provided, it should be either contiguous ' + f'or 1-dimensional. Got array with shape {out.shape} and ' + f'strides {out.strides}.' + ) + + # ensure all arrays have matching types before sending to Cython + input_vals = input_vals.astype(input_arr.dtype, copy=False) + output_vals = output_vals.astype(out.dtype, copy=False) + _map_array(input_arr, out_view, input_vals, output_vals) + return out + + +class ArrayMap: + """Class designed to mimic mapping by NumPy array indexing. + + This class is designed to replicate the use of NumPy arrays for mapping + values with indexing: + + >>> values = np.array([0.25, 0.5, 1.0]) + >>> indices = np.array([[0, 0, 1], [2, 2, 1]]) + >>> values[indices] + array([[0.25, 0.25, 0.5 ], + [1. , 1. , 0.5 ]]) + + The issue with this indexing is that you need a very large ``values`` + array if the values in the ``indices`` array are large. + + >>> values = np.array([0.25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0]) + >>> indices = np.array([[0, 0, 10], [0, 10, 10]]) + >>> values[indices] + array([[0.25, 0.25, 1. ], + [0.25, 1. , 1. ]]) + + Using this class, the approach is similar, but there is no need to + create a large values array: + + >>> in_indices = np.array([0, 10]) + >>> out_values = np.array([0.25, 1.0]) + >>> values = ArrayMap(in_indices, out_values) + >>> values + ArrayMap(array([ 0, 10]), array([0.25, 1. ])) + >>> print(values) + ArrayMap: + 0 → 0.25 + 10 → 1.0 + >>> indices = np.array([[0, 0, 10], [0, 10, 10]]) + >>> values[indices] + array([[0.25, 0.25, 1. ], + [0.25, 1. , 1. ]]) + + Parameters + ---------- + in_values : array of int, shape (K,) + The source values from which to map. + out_values : array, shape (K,) + The destination values from which to map. + """ + + def __init__(self, in_values, out_values): + self.in_values = in_values + self.out_values = out_values + self._max_str_lines = 4 + self._array = None + + def __len__(self): + """Return one more than the maximum label value being remapped.""" + return np.max(self.in_values) + 1 + + def __array__(self, dtype=None, copy=None): + """Return an array that behaves like the arraymap when indexed. + + This array can be very large: it is the size of the largest value + in the ``in_vals`` array, plus one. + """ + if dtype is None: + dtype = self.out_values.dtype + output = np.zeros(np.max(self.in_values) + 1, dtype=dtype) + output[self.in_values] = self.out_values + return output + + @property + def dtype(self): + return self.out_values.dtype + + def __repr__(self): + return f'ArrayMap({repr(self.in_values)}, {repr(self.out_values)})' + + def __str__(self): + if len(self.in_values) <= self._max_str_lines + 1: + rows = range(len(self.in_values)) + string = '\n'.join( + ['ArrayMap:'] + + [f' {self.in_values[i]} → {self.out_values[i]}' for i in rows] + ) + else: + rows0 = list(range(0, self._max_str_lines // 2)) + rows1 = list(range(-self._max_str_lines // 2, 0)) + string = '\n'.join( + ['ArrayMap:'] + + [f' {self.in_values[i]} → {self.out_values[i]}' for i in rows0] + + [' ...'] + + [f' {self.in_values[i]} → {self.out_values[i]}' for i in rows1] + ) + return string + + def __call__(self, arr): + return self.__getitem__(arr) + + def __getitem__(self, index): + scalar = np.isscalar(index) + if scalar: + index = np.array([index]) + elif isinstance(index, slice): + start = index.start or 0 # treat None or 0 the same way + stop = index.stop if index.stop is not None else len(self) + step = index.step + index = np.arange(start, stop, step) + if index.dtype == bool: + index = np.flatnonzero(index) + + out = map_array( + index, + self.in_values.astype(index.dtype, copy=False), + self.out_values, + ) + + if scalar: + out = out[0] + return out + + def __setitem__(self, indices, values): + if self._array is None: + self._array = self.__array__() + self._array[indices] = values + self.in_values = np.flatnonzero(self._array) + self.out_values = self._array[self.in_values] diff --git a/envs/kitoverlay/skimage/util/_montage.py b/envs/kitoverlay/skimage/util/_montage.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb4ccaa28f73e5f8c3bd1a5e6844f04e0b1572c --- /dev/null +++ b/envs/kitoverlay/skimage/util/_montage.py @@ -0,0 +1,157 @@ +import numpy as np + +from .._shared import utils +from .. import exposure + +__all__ = ['montage'] + + +@utils.channel_as_last_axis(multichannel_output=False) +def montage( + arr_in, + fill='mean', + rescale_intensity=False, + grid_shape=None, + padding_width=0, + *, + channel_axis=None, +): + """Create a montage of several single- or multichannel images. + + Create a rectangular montage from an input array representing an ensemble + of equally shaped single- (gray) or multichannel (color) images. + + For example, ``montage(arr_in)`` called with the following `arr_in` + + +---+---+---+ + | 1 | 2 | 3 | + +---+---+---+ + + will return + + +---+---+ + | 1 | 2 | + +---+---+ + | 3 | * | + +---+---+ + + where the '*' patch will be determined by the `fill` parameter. + + Parameters + ---------- + arr_in : ndarray, shape (K, M, N[, C]) + An array representing an ensemble of `K` images of equal shape. + fill : float or array-like of floats or 'mean', optional + Value to fill the padding areas and/or the extra tiles in + the output array. Has to be `float` for single channel collections. + For multichannel collections has to be an array-like of shape of + number of channels. If `mean`, uses the mean value over all images. + rescale_intensity : bool, optional + Whether to rescale the intensity of each image to [0, 1]. + grid_shape : tuple, optional + The desired grid shape for the montage `(ntiles_row, ntiles_column)`. + The default aspect ratio is square. + padding_width : int, optional + The size of the spacing between the tiles and between the tiles and + the borders. If non-zero, makes the boundaries of individual images + easier to perceive. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + arr_out : (K*(M+p)+p, K*(N+p)+p[, C]) ndarray + Output array with input images glued together (including padding `p`). + + Examples + -------- + >>> import numpy as np + >>> from skimage.util import montage + >>> arr_in = np.arange(3 * 2 * 2).reshape(3, 2, 2) + >>> arr_in # doctest: +NORMALIZE_WHITESPACE + array([[[ 0, 1], + [ 2, 3]], + [[ 4, 5], + [ 6, 7]], + [[ 8, 9], + [10, 11]]]) + >>> arr_out = montage(arr_in) + >>> arr_out.shape + (4, 4) + >>> arr_out + array([[ 0, 1, 4, 5], + [ 2, 3, 6, 7], + [ 8, 9, 5, 5], + [10, 11, 5, 5]]) + >>> arr_in.mean() + 5.5 + >>> arr_out_nonsquare = montage(arr_in, grid_shape=(1, 3)) + >>> arr_out_nonsquare + array([[ 0, 1, 4, 5, 8, 9], + [ 2, 3, 6, 7, 10, 11]]) + >>> arr_out_nonsquare.shape + (2, 6) + """ + + if channel_axis is not None: + arr_in = np.asarray(arr_in) + else: + arr_in = np.asarray(arr_in)[..., np.newaxis] + + if arr_in.ndim != 4: + raise ValueError( + 'Input array has to be 3-dimensional for grayscale ' + 'images, or 4-dimensional with a `channel_axis` ' + 'specified.' + ) + + n_images, n_rows, n_cols, n_chan = arr_in.shape + + if grid_shape: + ntiles_row, ntiles_col = (int(s) for s in grid_shape) + else: + ntiles_row = ntiles_col = int(np.ceil(np.sqrt(n_images))) + + # Rescale intensity if necessary + if rescale_intensity: + for i in range(n_images): + arr_in[i] = exposure.rescale_intensity(arr_in[i]) + + # Calculate the fill value + if fill == 'mean': + fill = arr_in.mean(axis=(0, 1, 2)) + fill = np.atleast_1d(fill).astype(arr_in.dtype) + + # Pre-allocate an array with padding for montage + n_pad = padding_width + arr_out = np.empty( + ( + (n_rows + n_pad) * ntiles_row + n_pad, + (n_cols + n_pad) * ntiles_col + n_pad, + n_chan, + ), + dtype=arr_in.dtype, + ) + for idx_chan in range(n_chan): + arr_out[..., idx_chan] = fill[idx_chan] + + slices_row = [ + slice(n_pad + (n_rows + n_pad) * n, n_pad + (n_rows + n_pad) * n + n_rows) + for n in range(ntiles_row) + ] + slices_col = [ + slice(n_pad + (n_cols + n_pad) * n, n_pad + (n_cols + n_pad) * n + n_cols) + for n in range(ntiles_col) + ] + + # Copy the data to the output array + for idx_image, image in enumerate(arr_in): + idx_sr, idx_sc = divmod(idx_image, ntiles_col) + arr_out[slices_row[idx_sr], slices_col[idx_sc], :] = image + + if channel_axis is not None: + return arr_out + else: + return arr_out[..., 0] diff --git a/envs/kitoverlay/skimage/util/_regular_grid.py b/envs/kitoverlay/skimage/util/_regular_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..13bf47ef0cb035abbe51a077b162cb5e69930ad1 --- /dev/null +++ b/envs/kitoverlay/skimage/util/_regular_grid.py @@ -0,0 +1,114 @@ +import numpy as np + + +def regular_grid(ar_shape, n_points): + """Find `n_points` regularly spaced along `ar_shape`. + + The returned points (as slices) should be as close to cubically-spaced as + possible. Essentially, the points are spaced by the Nth root of the input + array size, where N is the number of dimensions. However, if an array + dimension cannot fit a full step size, it is "discarded", and the + computation is done for only the remaining dimensions. + + Parameters + ---------- + ar_shape : array-like of ints + The shape of the space embedding the grid. ``len(ar_shape)`` is the + number of dimensions. + n_points : int + The (approximate) number of points to embed in the space. + + Returns + ------- + slices : tuple of slice objects + A slice along each dimension of `ar_shape`, such that the intersection + of all the slices give the coordinates of regularly spaced points. + + .. versionchanged:: 0.14.1 + In scikit-image 0.14.1 and 0.15, the return type was changed from a + list to a tuple to ensure `compatibility with Numpy 1.15`_ and + higher. If your code requires the returned result to be a list, you + may convert the output of this function to a list with: + + >>> result = list(regular_grid(ar_shape=(3, 20, 40), n_points=8)) + + .. _compatibility with NumPy 1.15: https://github.com/numpy/numpy/blob/master/doc/release/1.15.0-notes.rst#deprecations + + Examples + -------- + >>> ar = np.zeros((20, 40)) + >>> g = regular_grid(ar.shape, 8) + >>> g + (slice(5, None, 10), slice(5, None, 10)) + >>> ar[g] = 1 + >>> ar.sum() + 8.0 + >>> ar = np.zeros((20, 40)) + >>> g = regular_grid(ar.shape, 32) + >>> g + (slice(2, None, 5), slice(2, None, 5)) + >>> ar[g] = 1 + >>> ar.sum() + 32.0 + >>> ar = np.zeros((3, 20, 40)) + >>> g = regular_grid(ar.shape, 8) + >>> g + (slice(1, None, 3), slice(5, None, 10), slice(5, None, 10)) + >>> ar[g] = 1 + >>> ar.sum() + 8.0 + """ + ar_shape = np.asanyarray(ar_shape) + ndim = len(ar_shape) + unsort_dim_idxs = np.argsort(np.argsort(ar_shape)) + sorted_dims = np.sort(ar_shape) + space_size = float(np.prod(ar_shape)) + if space_size <= n_points: + return (slice(None),) * ndim + stepsizes = np.full(ndim, (space_size / n_points) ** (1.0 / ndim), dtype='float64') + if (sorted_dims < stepsizes).any(): + for dim in range(ndim): + stepsizes[dim] = sorted_dims[dim] + space_size = float(np.prod(sorted_dims[dim + 1 :])) + stepsizes[dim + 1 :] = (space_size / n_points) ** (1.0 / (ndim - dim - 1)) + if (sorted_dims >= stepsizes).all(): + break + starts = (stepsizes // 2).astype(int) + stepsizes = np.round(stepsizes).astype(int) + slices = [slice(start, None, step) for start, step in zip(starts, stepsizes)] + slices = tuple(slices[i] for i in unsort_dim_idxs) + return slices + + +def regular_seeds(ar_shape, n_points, dtype=int): + """Return an image with ~`n_points` regularly-spaced nonzero pixels. + + Parameters + ---------- + ar_shape : tuple of int + The shape of the desired output image. + n_points : int + The desired number of nonzero points. + dtype : numpy data type, optional + The desired data type of the output. + + Returns + ------- + seed_img : array of int or bool + The desired image. + + Examples + -------- + >>> regular_seeds((5, 5), 4) + array([[0, 0, 0, 0, 0], + [0, 1, 0, 2, 0], + [0, 0, 0, 0, 0], + [0, 3, 0, 4, 0], + [0, 0, 0, 0, 0]]) + """ + grid = regular_grid(ar_shape, n_points) + seed_img = np.zeros(ar_shape, dtype=dtype) + seed_img[grid] = 1 + np.reshape( + np.arange(seed_img[grid].size), seed_img[grid].shape + ) + return seed_img diff --git a/envs/kitoverlay/skimage/util/_slice_along_axes.py b/envs/kitoverlay/skimage/util/_slice_along_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf6fd6cd235281efe300e725d8c80991d4d4b93 --- /dev/null +++ b/envs/kitoverlay/skimage/util/_slice_along_axes.py @@ -0,0 +1,86 @@ +__all__ = ['slice_along_axes'] + + +def slice_along_axes(image, slices, axes=None, copy=False): + """Slice an image along given axes. + + Parameters + ---------- + image : ndarray + Input image. + slices : list of 2-tuple (a, b) where a < b. + For each axis in `axes`, a corresponding 2-tuple + ``(min_val, max_val)`` to slice with (as with Python slices, + ``max_val`` is non-inclusive). + axes : int or tuple, optional + Axes corresponding to the limits given in `slices`. If None, + axes are in ascending order, up to the length of `slices`. + copy : bool, optional + If True, ensure that the output is not a view of `image`. + + Returns + ------- + out : ndarray + The region of `image` corresponding to the given slices and axes. + + Examples + -------- + >>> from skimage import data + >>> img = data.camera() + >>> img.shape + (512, 512) + >>> cropped_img = slice_along_axes(img, [(0, 100)]) + >>> cropped_img.shape + (100, 512) + >>> cropped_img = slice_along_axes(img, [(0, 100), (0, 100)]) + >>> cropped_img.shape + (100, 100) + >>> cropped_img = slice_along_axes(img, [(0, 100), (0, 75)], axes=[1, 0]) + >>> cropped_img.shape + (75, 100) + """ + + # empty length of bounding box detected on None + if not slices: + return image + + if axes is None: + axes = list(range(image.ndim)) + if len(axes) < len(slices): + raise ValueError("More `slices` than available axes") + + elif len(axes) != len(slices): + raise ValueError("`axes` and `slices` must have equal length") + + if len(axes) != len(set(axes)): + raise ValueError("`axes` must be unique") + + if not all(a >= 0 and a < image.ndim for a in axes): + raise ValueError( + f"axes {axes} out of range; image has only " f"{image.ndim} dimensions" + ) + + _slices = [ + slice(None), + ] * image.ndim + for (a, b), ax in zip(slices, axes): + if a < 0: + a %= image.shape[ax] + if b < 0: + b %= image.shape[ax] + if a > b: + raise ValueError( + f"Invalid slice ({a}, {b}): must be ordered `(min_val, max_val)`" + ) + if a < 0 or b > image.shape[ax]: + raise ValueError( + f"Invalid slice ({a}, {b}) for image with dimensions {image.shape}" + ) + _slices[ax] = slice(a, b) + + image_slice = image[tuple(_slices)] + + if copy and image_slice.base is not None: + image_slice = image_slice.copy() + + return image_slice diff --git a/envs/kitoverlay/skimage/util/apply_parallel.py b/envs/kitoverlay/skimage/util/apply_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..57a7638c2a2e1deba587537f96335f6f99702665 --- /dev/null +++ b/envs/kitoverlay/skimage/util/apply_parallel.py @@ -0,0 +1,213 @@ +import numpy + +__all__ = ['apply_parallel'] + + +def _get_chunks(shape, ncpu): + """Split the array into equal sized chunks based on the number of + available processors. The last chunk in each dimension absorbs the + remainder array elements if the number of CPUs does not divide evenly into + the number of array elements. + + Examples + -------- + >>> _get_chunks((4, 4), 4) + ((2, 2), (2, 2)) + >>> _get_chunks((4, 4), 2) + ((2, 2), (4,)) + >>> _get_chunks((5, 5), 2) + ((2, 3), (5,)) + >>> _get_chunks((2, 4), 2) + ((1, 1), (4,)) + """ + # since apply_parallel is in the critical import path, we lazy import + # math just when we need it. + from math import ceil + + chunks = [] + nchunks_per_dim = int(ceil(ncpu ** (1.0 / len(shape)))) + + used_chunks = 1 + for i in shape: + if used_chunks < ncpu: + regular_chunk = i // nchunks_per_dim + remainder_chunk = regular_chunk + (i % nchunks_per_dim) + + if regular_chunk == 0: + chunk_lens = (remainder_chunk,) + else: + chunk_lens = (regular_chunk,) * (nchunks_per_dim - 1) + ( + remainder_chunk, + ) + else: + chunk_lens = (i,) + + chunks.append(chunk_lens) + used_chunks *= nchunks_per_dim + return tuple(chunks) + + +def _ensure_dask_array(array, chunks=None): + import dask.array as da + + if isinstance(array, da.Array): + return array + + return da.from_array(array, chunks=chunks) + + +def apply_parallel( + function, + array, + chunks=None, + depth=0, + mode=None, + extra_arguments=(), + extra_keywords=None, + *, + dtype=None, + compute=None, + channel_axis=None, +): + """Map a function in parallel across an array. + + Split an array into possibly overlapping chunks of a given depth and + boundary type, call the given function in parallel on the chunks, combine + the chunks and return the resulting array. + + Parameters + ---------- + function : function + Function to be mapped which takes an array as an argument. + array : numpy array or dask array + Array which the function will be applied to. + chunks : int, tuple, or tuple of tuples, optional + A single integer is interpreted as the length of one side of a square + chunk that should be tiled across the array. One tuple of length + ``array.ndim`` represents the shape of a chunk, and it is tiled across + the array. A list of tuples of length ``ndim``, where each sub-tuple + is a sequence of chunk sizes along the corresponding dimension. If + None, the array is broken up into chunks based on the number of + available cpus. More information about chunks is in the documentation + `here `_. When + `channel_axis` is not None, the tuples can be length ``ndim - 1`` and + a single chunk will be used along the channel axis. + depth : int or sequence of int, optional + The depth of the added boundary cells. A tuple can be used to specify a + different depth per array axis. Defaults to zero. When `channel_axis` + is not None, and a tuple of length ``ndim - 1`` is provided, a depth of + 0 will be used along the channel axis. + mode : {'reflect', 'symmetric', 'periodic', 'wrap', 'nearest', 'edge'}, optional + Type of external boundary padding. + extra_arguments : tuple, optional + Tuple of arguments to be passed to the function. + extra_keywords : dictionary, optional + Dictionary of keyword arguments to be passed to the function. + dtype : data-type or None, optional + The data-type of the `function` output. If None, Dask will attempt to + infer this by calling the function on data of shape ``(1,) * ndim``. + For functions expecting RGB or multichannel data this may be + problematic. In such cases, the user should manually specify this dtype + argument instead. + + .. versionadded:: 0.18 + ``dtype`` was added in 0.18. + compute : bool, optional + If ``True``, compute eagerly returning a NumPy Array. + If ``False``, compute lazily returning a Dask Array. + If ``None`` (default), compute based on array type provided + (eagerly for NumPy Arrays and lazily for Dask Arrays). + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + out : ndarray or dask Array + Returns the result of the applying the operation. + Type is dependent on the ``compute`` argument. + + Notes + ----- + Numpy edge modes 'symmetric', 'wrap', and 'edge' are converted to the + equivalent ``dask`` boundary modes 'reflect', 'periodic' and 'nearest', + respectively. + Setting ``compute=False`` can be useful for chaining later operations. + For example region selection to preview a result or storing large data + to disk instead of loading in memory. + + """ + try: + # Importing dask takes time. since apply_parallel is on the + # minimum import path of skimage, we lazy attempt to import dask + import dask.array as da + except ImportError: + raise RuntimeError( + "Could not import 'dask'. Please install " "using 'pip install dask'" + ) + + if extra_keywords is None: + extra_keywords = {} + + if compute is None: + compute = not isinstance(array, da.Array) + + if channel_axis is not None: + channel_axis = channel_axis % array.ndim + + if chunks is None: + shape = array.shape + try: + # since apply_parallel is in the critical import path, we lazy + # import multiprocessing just when we need it. + from multiprocessing import cpu_count + + ncpu = cpu_count() + except NotImplementedError: + ncpu = 4 + if channel_axis is not None: + # use a single chunk along the channel axis + spatial_shape = shape[:channel_axis] + shape[channel_axis + 1 :] + chunks = list(_get_chunks(spatial_shape, ncpu)) + chunks.insert(channel_axis, shape[channel_axis]) + chunks = tuple(chunks) + else: + chunks = _get_chunks(shape, ncpu) + elif channel_axis is not None and len(chunks) == array.ndim - 1: + # insert a single chunk along the channel axis + chunks = list(chunks) + chunks.insert(channel_axis, array.shape[channel_axis]) + chunks = tuple(chunks) + + if mode == 'wrap': + mode = 'periodic' + elif mode == 'symmetric': + mode = 'reflect' + elif mode == 'edge': + mode = 'nearest' + elif mode is None: + # default value for Dask. + # Note: that for dask >= 2022.03 it will change to 'none' so we set it + # here for consistent behavior across Dask versions. + mode = 'reflect' + + if channel_axis is not None: + if numpy.isscalar(depth): + # depth is zero along channel_axis + depth = [depth] * (array.ndim - 1) + depth = list(depth) + if len(depth) == array.ndim - 1: + depth.insert(channel_axis, 0) + depth = tuple(depth) + + def wrapped_func(arr): + return function(arr, *extra_arguments, **extra_keywords) + + darr = _ensure_dask_array(array, chunks=chunks) + + res = darr.map_overlap(wrapped_func, depth, boundary=mode, dtype=dtype) + if compute: + res = res.compute() + + return res diff --git a/envs/kitoverlay/skimage/util/arraycrop.py b/envs/kitoverlay/skimage/util/arraycrop.py new file mode 100644 index 0000000000000000000000000000000000000000..9d02ad16e26ca42992a205876036ffa4c891d796 --- /dev/null +++ b/envs/kitoverlay/skimage/util/arraycrop.py @@ -0,0 +1,72 @@ +""" +The arraycrop module contains functions to crop values from the edges of an +n-dimensional array. +""" + +import numpy as np +from numbers import Integral + +__all__ = ['crop'] + + +def crop(ar, crop_width, copy=False, order='K'): + """Crop array `ar` by `crop_width` along each dimension. + + Parameters + ---------- + ar : array-like of rank N + Input array. + crop_width : {sequence, int} + Number of values to remove from the edges of each axis. + ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies + unique crop widths at the start and end of each axis. + ``((before, after),) or (before, after)`` specifies + a fixed start and end crop for every axis. + ``(n,)`` or ``n`` for integer ``n`` is a shortcut for + before = after = ``n`` for all axes. + copy : bool, optional + If `True`, ensure the returned array is a contiguous copy. Normally, + a crop operation will return a discontiguous view of the underlying + input array. + order : {'C', 'F', 'A', 'K'}, optional + If ``copy==True``, control the memory layout of the copy. See + ``np.copy``. + + Returns + ------- + cropped : array + The cropped array. If ``copy=False`` (default), this is a sliced + view of the input array. + """ + ar = np.array(ar, copy=False) + + if isinstance(crop_width, Integral): + crops = [[crop_width, crop_width]] * ar.ndim + elif isinstance(crop_width[0], Integral): + if len(crop_width) == 1: + crops = [[crop_width[0], crop_width[0]]] * ar.ndim + elif len(crop_width) == 2: + crops = [crop_width] * ar.ndim + else: + raise ValueError( + f'crop_width has an invalid length: {len(crop_width)}\n' + f'crop_width should be a sequence of N pairs, ' + f'a single pair, or a single integer' + ) + elif len(crop_width) == 1: + crops = [crop_width[0]] * ar.ndim + elif len(crop_width) == ar.ndim: + crops = crop_width + else: + raise ValueError( + f'crop_width has an invalid length: {len(crop_width)}\n' + f'crop_width should be a sequence of N pairs, ' + f'a single pair, or a single integer' + ) + + slices = tuple(slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)) + if copy: + cropped = np.array(ar[slices], order=order, copy=True) + else: + cropped = ar[slices] + return cropped diff --git a/envs/kitoverlay/skimage/util/compare.py b/envs/kitoverlay/skimage/util/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7be44d610095074048870bbc1b158532bef678 --- /dev/null +++ b/envs/kitoverlay/skimage/util/compare.py @@ -0,0 +1,99 @@ +import functools +from itertools import product + +import numpy as np + +from .dtype import img_as_float + + +def _rename_image_params(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + # Turn all args into kwargs + for i, (value, param) in enumerate( + zip(args, ["image0", "image1", "method", "n_tiles"]) + ): + if param in kwargs: + raise ValueError( + f"{param} passed both as positional and keyword argument." + ) + else: + kwargs[param] = value + args = tuple() + + return func(*args, **kwargs) + + return wrapper + + +@_rename_image_params +def compare_images(image0, image1, *, method='diff', n_tiles=(8, 8)): + """ + Return an image showing the differences between two images. + + .. versionadded:: 0.16 + + Parameters + ---------- + image0, image1 : ndarray, shape (M, N) + Images to process, must be of the same shape. + + .. versionchanged:: 0.24 + `image1` and `image2` were renamed into `image0` and `image1` + respectively. + method : {'diff', 'blend', 'checkerboard'}, optional + Method used for the comparison. + Details are provided in the note section. + + .. versionchanged:: 0.24 + This parameter and following ones are keyword-only. + n_tiles : tuple, optional + Used only for the `checkerboard` method. Specifies the number + of tiles (row, column) to divide the image. + + Returns + ------- + comparison : ndarray, shape (M, N) + Image showing the differences. + + Notes + ----- + ``'diff'`` computes the absolute difference between the two images. + ``'blend'`` computes the mean value. + ``'checkerboard'`` makes tiles of dimension `n_tiles` that display + alternatively the first and the second image. Note that images must be + 2-dimensional to be compared with the checkerboard method. + """ + + if image1.shape != image0.shape: + raise ValueError('Images must have the same shape.') + + img1 = img_as_float(image0) + img2 = img_as_float(image1) + + if method == 'diff': + comparison = np.abs(img2 - img1) + elif method == 'blend': + comparison = 0.5 * (img2 + img1) + elif method == 'checkerboard': + if img1.ndim != 2: + raise ValueError( + 'Images must be 2-dimensional to be compared with the ' + 'checkerboard method.' + ) + shapex, shapey = img1.shape + mask = np.full((shapex, shapey), False) + stepx = int(shapex / n_tiles[0]) + stepy = int(shapey / n_tiles[1]) + for i, j in product(range(n_tiles[0]), range(n_tiles[1])): + if (i + j) % 2 == 0: + mask[i * stepx : (i + 1) * stepx, j * stepy : (j + 1) * stepy] = True + comparison = np.zeros_like(img1) + comparison[mask] = img1[mask] + comparison[~mask] = img2[~mask] + else: + raise ValueError( + 'Wrong value for `method`. ' + 'Must be either "diff", "blend" or "checkerboard".' + ) + return comparison diff --git a/envs/kitoverlay/skimage/util/dtype.py b/envs/kitoverlay/skimage/util/dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..7576d562522bef98b19e85bf93daeaa686d7934a --- /dev/null +++ b/envs/kitoverlay/skimage/util/dtype.py @@ -0,0 +1,602 @@ +import warnings +from warnings import warn + +import numpy as np + + +__all__ = [ + 'img_as_float32', + 'img_as_float64', + 'img_as_float', + 'img_as_int', + 'img_as_uint', + 'img_as_ubyte', + 'img_as_bool', + 'dtype_limits', +] + +# Some of these may or may not be aliases depending on architecture & platform +_integer_types = ( + np.int8, + np.byte, + np.int16, + np.short, + np.int32, + np.int64, + np.longlong, + np.int_, + np.intp, + np.intc, + int, + np.uint8, + np.ubyte, + np.uint16, + np.ushort, + np.uint32, + np.uint64, + np.ulonglong, + np.uint, + np.uintp, + np.uintc, +) +_integer_ranges = {t: (np.iinfo(t).min, np.iinfo(t).max) for t in _integer_types} +dtype_range = { + bool: (False, True), + np.bool_: (False, True), + float: (-1, 1), + np.float16: (-1, 1), + np.float32: (-1, 1), + np.float64: (-1, 1), +} + +with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=DeprecationWarning) + + # np.bool8 is a deprecated alias of np.bool_ + if hasattr(np, 'bool8'): + dtype_range[np.bool8] = (False, True) + +dtype_range.update(_integer_ranges) + +_supported_types = list(dtype_range.keys()) + + +def dtype_limits(image, clip_negative=False): + """Return intensity limits, i.e. (min, max) tuple, of the image's dtype. + + Parameters + ---------- + image : ndarray + Input image. + clip_negative : bool, optional + If True, clip the negative range (i.e. return 0 for min intensity) + even if the image dtype allows negative values. + + Returns + ------- + imin, imax : tuple + Lower and upper intensity limits. + """ + imin, imax = dtype_range[image.dtype.type] + if clip_negative: + imin = 0 + return imin, imax + + +def _dtype_itemsize(itemsize, *dtypes): + """Return first of `dtypes` with itemsize greater than `itemsize` + + Parameters + ---------- + itemsize : int + The data type object element size. + + Other Parameters + ---------------- + *dtypes + Any Object accepted by `np.dtype` to be converted to a data + type object + + Returns + ------- + dtype: data type object + First of `dtypes` with itemsize greater than `itemsize`. + + """ + return next(dt for dt in dtypes if np.dtype(dt).itemsize >= itemsize) + + +def _dtype_bits(kind, bits, itemsize=1): + """Return dtype of `kind` that can store a `bits` wide unsigned int + + Parameters: + kind: str + Data type kind. + bits: int + Desired number of bits. + itemsize: int + The data type object element size. + + Returns + ------- + dtype: data type object + Data type of `kind` that can store a `bits` wide unsigned int + + """ + + s = next( + i + for i in (itemsize,) + (2, 4, 8) + if bits < (i * 8) or (bits == (i * 8) and kind == 'u') + ) + + return np.dtype(kind + str(s)) + + +def _scale(a, n, m, copy=True): + """Scale an array of unsigned/positive integers from `n` to `m` bits. + + Numbers can be represented exactly only if `m` is a multiple of `n`. + + Parameters + ---------- + a : ndarray + Input image array. + n : int + Number of bits currently used to encode the values in `a`. + m : int + Desired number of bits to encode the values in `out`. + copy : bool, optional + If True, allocates and returns new array. Otherwise, modifies + `a` in place. + + Returns + ------- + out : array + Output image array. Has the same kind as `a`. + """ + kind = a.dtype.kind + if n > m and a.max() < 2**m: + mnew = int(np.ceil(m / 2) * 2) + if mnew > m: + dtype = f'int{mnew}' + else: + dtype = f'uint{mnew}' + n = int(np.ceil(n / 2) * 2) + warn( + f'Downcasting {a.dtype} to {dtype} without scaling because max ' + f'value {a.max()} fits in {dtype}', + stacklevel=3, + ) + return a.astype(_dtype_bits(kind, m)) + elif n == m: + return a.copy() if copy else a + elif n > m: + # downscale with precision loss + if copy: + b = np.empty(a.shape, _dtype_bits(kind, m)) + np.floor_divide(a, 2 ** (n - m), out=b, dtype=a.dtype, casting='unsafe') + return b + else: + a //= 2 ** (n - m) + return a + elif m % n == 0: + # exact upscale to a multiple of `n` bits + if copy: + b = np.empty(a.shape, _dtype_bits(kind, m)) + np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype) + return b + else: + a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False) + a *= (2**m - 1) // (2**n - 1) + return a + else: + # upscale to a multiple of `n` bits, + # then downscale with precision loss + o = (m // n + 1) * n + if copy: + b = np.empty(a.shape, _dtype_bits(kind, o)) + np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype) + b //= 2 ** (o - m) + return b + else: + a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False) + a *= (2**o - 1) // (2**n - 1) + a //= 2 ** (o - m) + return a + + +def _convert(image, dtype, force_copy=False, uniform=False): + """ + Convert an image to the requested data-type. + + Warnings are issued in case of precision loss, or when negative values + are clipped during conversion to unsigned integer types (sign loss). + + Floating point values are expected to be normalized and will be clipped + to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or + signed integers respectively. + + Numbers are not shifted to the negative side when converting from + unsigned to signed integer types. Negative values will be clipped when + converting to unsigned integers. + + Parameters + ---------- + image : ndarray + Input image. + dtype : dtype + Target data-type. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + uniform : bool, optional + Uniformly quantize the floating point range to the integer range. + By default (uniform=False) floating point values are scaled and + rounded to the nearest integers, which minimizes back and forth + conversion errors. + + Notes + ----- + .. versionchanged:: 0.15 + ``_convert`` no longer warns about possible precision or sign + information loss. See discussions on these warnings at: + https://github.com/scikit-image/scikit-image/issues/2602 + https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228 + https://github.com/scikit-image/scikit-image/pull/3575 + + References + ---------- + .. [1] DirectX data conversion rules. + https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx + .. [2] Data Conversions. In "OpenGL ES 2.0 Specification v2.0.25", + pp 7-8. Khronos Group, 2010. + .. [3] Proper treatment of pixels as integers. A.W. Paeth. + In "Graphics Gems I", pp 249-256. Morgan Kaufmann, 1990. + .. [4] Dirty Pixels. J. Blinn. In "Jim Blinn's corner: Dirty Pixels", + pp 47-57. Morgan Kaufmann, 1998. + + """ + image = np.asarray(image) + dtypeobj_in = image.dtype + if dtype is np.floating: + dtypeobj_out = np.dtype('float64') + else: + dtypeobj_out = np.dtype(dtype) + dtype_in = dtypeobj_in.type + dtype_out = dtypeobj_out.type + kind_in = dtypeobj_in.kind + kind_out = dtypeobj_out.kind + itemsize_in = dtypeobj_in.itemsize + itemsize_out = dtypeobj_out.itemsize + + # Below, we do an `issubdtype` check. Its purpose is to find out + # whether we can get away without doing any image conversion. This happens + # when: + # + # - the output and input dtypes are the same or + # - when the output is specified as a type, and the input dtype + # is a subclass of that type (e.g. `np.floating` will allow + # `float32` and `float64` arrays through) + + if np.issubdtype(dtype_in, dtype): + if force_copy: + image = image.copy() + return image + + if not (dtype_in in _supported_types and dtype_out in _supported_types): + raise ValueError(f'Cannot convert from {dtypeobj_in} to ' f'{dtypeobj_out}.') + + if kind_in in 'ui': + imin_in = np.iinfo(dtype_in).min + imax_in = np.iinfo(dtype_in).max + if kind_out in 'ui': + imin_out = np.iinfo(dtype_out).min + imax_out = np.iinfo(dtype_out).max + + # any -> binary + if kind_out == 'b': + return image > dtype_in(dtype_range[dtype_in][1] / 2) + + # binary -> any + if kind_in == 'b': + result = image.astype(dtype_out) + if kind_out != 'f': + result *= dtype_out(dtype_range[dtype_out][1]) + return result + + # float -> any + if kind_in == 'f': + if kind_out == 'f': + # float -> float + return image.astype(dtype_out) + + if np.min(image) < -1.0 or np.max(image) > 1.0: + raise ValueError("Images of type float must be between -1 and 1.") + # floating point -> integer + # use float type that can represent output integer type + computation_type = _dtype_itemsize( + itemsize_out, dtype_in, np.float32, np.float64 + ) + + if not uniform: + if kind_out == 'u': + image_out = np.multiply(image, imax_out, dtype=computation_type) + else: + image_out = np.multiply( + image, (imax_out - imin_out) / 2, dtype=computation_type + ) + image_out -= 1.0 / 2.0 + np.rint(image_out, out=image_out) + np.clip(image_out, imin_out, imax_out, out=image_out) + elif kind_out == 'u': + image_out = np.multiply(image, imax_out + 1, dtype=computation_type) + np.clip(image_out, 0, imax_out, out=image_out) + else: + image_out = np.multiply( + image, (imax_out - imin_out + 1.0) / 2.0, dtype=computation_type + ) + np.floor(image_out, out=image_out) + np.clip(image_out, imin_out, imax_out, out=image_out) + return image_out.astype(dtype_out) + + # signed/unsigned int -> float + if kind_out == 'f': + # use float type that can exactly represent input integers + computation_type = _dtype_itemsize( + itemsize_in, dtype_out, np.float32, np.float64 + ) + + if kind_in == 'u': + # using np.divide or np.multiply doesn't copy the data + # until the computation time + image = np.multiply(image, 1.0 / imax_in, dtype=computation_type) + # DirectX uses this conversion also for signed ints + # if imin_in: + # np.maximum(image, -1.0, out=image) + elif kind_in == 'i': + # From DirectX conversions: + # The most negative value maps to -1.0f + # Every other value is converted to a float (call it c) + # and then result = c * (1.0f / (2⁽ⁿ⁻¹⁾-1)). + + image = np.multiply(image, 1.0 / imax_in, dtype=computation_type) + np.maximum(image, -1.0, out=image) + + else: + image = np.add(image, 0.5, dtype=computation_type) + image *= 2 / (imax_in - imin_in) + + return np.asarray(image, dtype_out) + + # unsigned int -> signed/unsigned int + if kind_in == 'u': + if kind_out == 'i': + # unsigned int -> signed int + image = _scale(image, 8 * itemsize_in, 8 * itemsize_out - 1) + return image.view(dtype_out) + else: + # unsigned int -> unsigned int + return _scale(image, 8 * itemsize_in, 8 * itemsize_out) + + # signed int -> unsigned int + if kind_out == 'u': + image = _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out) + result = np.empty(image.shape, dtype_out) + np.maximum(image, 0, out=result, dtype=image.dtype, casting='unsafe') + return result + + # signed int -> signed int + if itemsize_in > itemsize_out: + return _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out - 1) + + image = image.astype(_dtype_bits('i', itemsize_out * 8)) + image -= imin_in + image = _scale(image, 8 * itemsize_in, 8 * itemsize_out, copy=False) + image += imin_out + return image.astype(dtype_out) + + +def convert(image, dtype, force_copy=False, uniform=False): + warn( + "The use of this function is discouraged as its behavior may change " + "dramatically in scikit-image 1.0. This function will be removed " + "in scikit-image 1.0.", + FutureWarning, + stacklevel=2, + ) + return _convert(image=image, dtype=dtype, force_copy=force_copy, uniform=uniform) + + +if _convert.__doc__ is not None: + convert.__doc__ = ( + _convert.__doc__ + + """ + + Warns + ----- + FutureWarning: + .. versionadded:: 0.17 + + The use of this function is discouraged as its behavior may change + dramatically in scikit-image 1.0. This function will be removed + in scikit-image 1.0. + """ + ) + + +def img_as_float32(image, force_copy=False): + """Convert an image to single-precision (32-bit) floating point format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of float32 + Output image. + + Notes + ----- + The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when + converting from unsigned or signed datatypes, respectively. + If the input image has a float type, intensity values are not modified + and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. + + """ + return _convert(image, np.float32, force_copy) + + +def img_as_float64(image, force_copy=False): + """Convert an image to double-precision (64-bit) floating point format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of float64 + Output image. + + Notes + ----- + The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when + converting from unsigned or signed datatypes, respectively. + If the input image has a float type, intensity values are not modified + and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. + + """ + return _convert(image, np.float64, force_copy) + + +def img_as_float(image, force_copy=False): + """Convert an image to floating point format. + + This function is similar to `img_as_float64`, but will not convert + lower-precision floating point arrays to `float64`. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of float + Output image. + + Notes + ----- + The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when + converting from unsigned or signed datatypes, respectively. + If the input image has a float type, intensity values are not modified + and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. + + """ + return _convert(image, np.floating, force_copy) + + +def img_as_uint(image, force_copy=False): + """Convert an image to 16-bit unsigned integer format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of uint16 + Output image. + + Notes + ----- + Negative input values will be clipped. + Positive values are scaled between 0 and 65535. + + """ + return _convert(image, np.uint16, force_copy) + + +def img_as_int(image, force_copy=False): + """Convert an image to 16-bit signed integer format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of int16 + Output image. + + Notes + ----- + The values are scaled between -32768 and 32767. + If the input data-type is positive-only (e.g., uint8), then + the output image will still only have positive values. + + """ + return _convert(image, np.int16, force_copy) + + +def img_as_ubyte(image, force_copy=False): + """Convert an image to 8-bit unsigned integer format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of ubyte (uint8) + Output image. + + Notes + ----- + Negative input values will be clipped. + Positive values are scaled between 0 and 255. + + """ + return _convert(image, np.uint8, force_copy) + + +def img_as_bool(image, force_copy=False): + """Convert an image to boolean format. + + Parameters + ---------- + image : ndarray + Input image. + force_copy : bool, optional + Force a copy of the data, irrespective of its current dtype. + + Returns + ------- + out : ndarray of bool (`bool_`) + Output image. + + Notes + ----- + The upper half of the input dtype's positive range is True, and the lower + half is False. All negative values (if present) are False. + + """ + return _convert(image, bool, force_copy) diff --git a/envs/kitoverlay/skimage/util/lookfor.py b/envs/kitoverlay/skimage/util/lookfor.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb2df9a00de216f557ad83f5dda941e80db3586 --- /dev/null +++ b/envs/kitoverlay/skimage/util/lookfor.py @@ -0,0 +1,33 @@ +import sys + +from .._vendored.numpy_lookfor import lookfor as _lookfor + + +__doctest_requires__ = {("lookfor",): ["SimpleITK"]} + + +def lookfor(what): + """Do a keyword search on scikit-image docstrings and print results. + + .. warning:: + + This function may also print results that are not part of + scikit-image's public API. + + Parameters + ---------- + what : str + Words to look for. + + Examples + -------- + >>> import skimage as ski + >>> ski.util.lookfor('regular_grid') + Search results for 'regular_grid' + --------------------------------- + skimage.util.regular_grid + Find `n_points` regularly spaced along `ar_shape`. + skimage.util.lookfor + Do a keyword search on scikit-image docstrings and print results. + """ + return _lookfor(what, sys.modules[__name__.split('.')[0]]) diff --git a/envs/kitoverlay/skimage/util/noise.py b/envs/kitoverlay/skimage/util/noise.py new file mode 100644 index 0000000000000000000000000000000000000000..6758299f91a250a57302b6025438b8d8c1f9628e --- /dev/null +++ b/envs/kitoverlay/skimage/util/noise.py @@ -0,0 +1,243 @@ +__all__ = ['random_noise'] + + +import numpy as np +from .dtype import img_as_float + + +def _bernoulli(p, shape, *, rng): + """ + Bernoulli trials at a given probability of a given size. + + This function is meant as a lower-memory alternative to calls such as + `np.random.choice([True, False], size=image.shape, p=[p, 1-p])`. + While `np.random.choice` can handle many classes, for the 2-class case + (Bernoulli trials), this function is much more efficient. + + Parameters + ---------- + p : float + The probability that any given trial returns `True`. + shape : int or tuple of ints + The shape of the ndarray to return. + rng : `numpy.random.Generator` + ``Generator`` instance, typically obtained via `np.random.default_rng()`. + + Returns + ------- + out : ndarray[bool] + The results of Bernoulli trials in the given `size` where success + occurs with probability `p`. + """ + if p == 0: + return np.zeros(shape, dtype=bool) + if p == 1: + return np.ones(shape, dtype=bool) + return rng.random(shape) <= p + + +def random_noise(image, mode='gaussian', rng=None, clip=True, **kwargs): + """ + Function to add random noise of various types to a floating-point image. + + Parameters + ---------- + image : ndarray + Input image data. Will be converted to float. + mode : str, optional + One of the following strings, selecting the type of noise to add: + + 'gaussian' (default) + Gaussian-distributed additive noise. + 'localvar' + Gaussian-distributed additive noise, with specified local variance + at each point of `image`. + 'poisson' + Poisson-distributed noise generated from the data. + 'salt' + Replaces random pixels with 1. + 'pepper' + Replaces random pixels with 0 (for unsigned images) or -1 (for + signed images). + 's&p' + Replaces random pixels with either 1 or `low_val`, where `low_val` + is 0 for unsigned images or -1 for signed images. + 'speckle' + Multiplicative noise using ``out = image + n * image``, where ``n`` + is Gaussian noise with specified mean & variance. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + clip : bool, optional + If True (default), the output will be clipped after noise is applied. + This may be needed to maintain the proper image data range. + If False, clipping is not applied, and the output may extend beyond + the range [-1, 1]. + mean : float, optional + Mean of random distribution. Used in 'gaussian' and 'speckle'. + Default : 0. + var : float, optional + Variance of random distribution. Used in 'gaussian' and 'speckle'. + Note: variance = (standard deviation) ** 2. Default : 0.01 + local_vars : ndarray, optional + Array of positive floats, same shape as `image`, defining the local + variance at every image point. Used in 'localvar'. + amount : float, optional + Proportion of image pixels to replace with noise on range [0, 1]. + Used in 'salt', 'pepper', and 'salt & pepper'. Default : 0.05 + salt_vs_pepper : float, optional + Proportion of salt vs. pepper noise for 's&p' on range [0, 1]. + Higher values represent more salt. Default : 0.5 (equal amounts) + + Returns + ------- + out : ndarray + Output floating-point image data on range [0, 1] or [-1, 1] if the + input `image` was unsigned or signed, respectively. + + Notes + ----- + Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside + the valid image range. The default is to clip (not alias) these values, + but they may be preserved by setting `clip=False`. Note that in this case + the output may contain values outside the ranges [0, 1] or [-1, 1]. + Use this option with care. + + Because of the prevalence of exclusively positive floating-point images in + intermediate calculations, it is not possible to intuit if an input is + signed based on dtype alone. Instead, negative values are explicitly + searched for. Only if found does this function assume signed input. + Unexpected results only occur in rare, poorly exposes cases (e.g. if all + values are above 50 percent gray in a signed `image`). In this event, + manually scaling the input to the positive domain will solve the problem. + + The Poisson distribution is only defined for positive integers. To apply + this noise type, the number of unique values in the image is found and + the next round power of two is used to scale up the floating-point result, + after which it is scaled back down to the floating-point image range. + + To generate Poisson noise against a signed image, the signed image is + temporarily converted to an unsigned image in the floating point domain, + Poisson noise is generated, then it is returned to the original range. + + """ + mode = mode.lower() + + # Detect if a signed image was input + if image.min() < 0: + low_clip = -1.0 + else: + low_clip = 0.0 + + image = img_as_float(image) + + rng = np.random.default_rng(rng) + + allowedtypes = { + 'gaussian': 'gaussian_values', + 'localvar': 'localvar_values', + 'poisson': 'poisson_values', + 'salt': 'sp_values', + 'pepper': 'sp_values', + 's&p': 's&p_values', + 'speckle': 'gaussian_values', + } + + kwdefaults = { + 'mean': 0.0, + 'var': 0.01, + 'amount': 0.05, + 'salt_vs_pepper': 0.5, + 'local_vars': np.zeros_like(image) + 0.01, + } + + allowedkwargs = { + 'gaussian_values': ['mean', 'var'], + 'localvar_values': ['local_vars'], + 'sp_values': ['amount'], + 's&p_values': ['amount', 'salt_vs_pepper'], + 'poisson_values': [], + } + + for key in kwargs: + if key not in allowedkwargs[allowedtypes[mode]]: + raise ValueError( + f"{key} keyword not in allowed keywords " + f"{allowedkwargs[allowedtypes[mode]]}" + ) + + # Set kwarg defaults + for kw in allowedkwargs[allowedtypes[mode]]: + kwargs.setdefault(kw, kwdefaults[kw]) + + if mode == 'gaussian': + noise = rng.normal(kwargs['mean'], kwargs['var'] ** 0.5, image.shape) + out = image + noise + + elif mode == 'localvar': + # Ensure local variance input is correct + if (kwargs['local_vars'] <= 0).any(): + raise ValueError('All values of `local_vars` must be > 0.') + + # Safe shortcut usage broadcasts kwargs['local_vars'] as a ufunc + out = image + rng.normal(0, kwargs['local_vars'] ** 0.5) + + elif mode == 'poisson': + # Determine unique values in image & calculate the next power of two + vals = len(np.unique(image)) + vals = 2 ** np.ceil(np.log2(vals)) + + # Ensure image is exclusively positive + if low_clip == -1.0: + old_max = image.max() + image = (image + 1.0) / (old_max + 1.0) + + # Generating noise for each unique value in image. + out = rng.poisson(image * vals) / float(vals) + + # Return image to original range if input was signed + if low_clip == -1.0: + out = out * (old_max + 1.0) - 1.0 + + elif mode == 'salt': + # Re-call function with mode='s&p' and p=1 (all salt noise) + out = random_noise( + image, + mode='s&p', + rng=rng, + amount=kwargs['amount'], + salt_vs_pepper=1.0, + clip=False, + ) + + elif mode == 'pepper': + # Re-call function with mode='s&p' and p=1 (all pepper noise) + out = random_noise( + image, + mode='s&p', + rng=rng, + amount=kwargs['amount'], + salt_vs_pepper=0.0, + clip=False, + ) + + elif mode == 's&p': + out = image.copy() + p = kwargs['amount'] + q = kwargs['salt_vs_pepper'] + flipped = _bernoulli(p, image.shape, rng=rng) + salted = _bernoulli(q, image.shape, rng=rng) + peppered = ~salted + out[flipped & salted] = 1 + out[flipped & peppered] = low_clip + + elif mode == 'speckle': + noise = rng.normal(kwargs['mean'], kwargs['var'] ** 0.5, image.shape) + out = image + image * noise + + # Clip back to original range, if necessary + if clip: + out = np.clip(out, low_clip, 1.0) + + return out diff --git a/envs/kitoverlay/skimage/util/shape.py b/envs/kitoverlay/skimage/util/shape.py new file mode 100644 index 0000000000000000000000000000000000000000..a42df4c4074ea99568776bd31fc3ed9f884cba78 --- /dev/null +++ b/envs/kitoverlay/skimage/util/shape.py @@ -0,0 +1,247 @@ +import numbers +import numpy as np +from numpy.lib.stride_tricks import as_strided + +__all__ = ['view_as_blocks', 'view_as_windows'] + + +def view_as_blocks(arr_in, block_shape): + """Block view of the input n-dimensional array (using re-striding). + + Blocks are non-overlapping views of the input array. + + Parameters + ---------- + arr_in : ndarray, shape (M[, ...]) + Input array. + block_shape : tuple + The shape of the block. Each dimension must divide evenly into the + corresponding dimensions of `arr_in`. + + Returns + ------- + arr_out : ndarray + Block view of the input array. + + Examples + -------- + >>> import numpy as np + >>> from skimage.util.shape import view_as_blocks + >>> A = np.arange(4*4).reshape(4,4) + >>> A + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + >>> B = view_as_blocks(A, block_shape=(2, 2)) + >>> B[0, 0] + array([[0, 1], + [4, 5]]) + >>> B[0, 1] + array([[2, 3], + [6, 7]]) + >>> B[1, 0, 1, 1] + 13 + + >>> A = np.arange(4*4*6).reshape(4,4,6) + >>> A # doctest: +NORMALIZE_WHITESPACE + array([[[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 21, 22, 23]], + [[24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35], + [36, 37, 38, 39, 40, 41], + [42, 43, 44, 45, 46, 47]], + [[48, 49, 50, 51, 52, 53], + [54, 55, 56, 57, 58, 59], + [60, 61, 62, 63, 64, 65], + [66, 67, 68, 69, 70, 71]], + [[72, 73, 74, 75, 76, 77], + [78, 79, 80, 81, 82, 83], + [84, 85, 86, 87, 88, 89], + [90, 91, 92, 93, 94, 95]]]) + >>> B = view_as_blocks(A, block_shape=(1, 2, 2)) + >>> B.shape + (4, 2, 3, 1, 2, 2) + >>> B[2:, 0, 2] # doctest: +NORMALIZE_WHITESPACE + array([[[[52, 53], + [58, 59]]], + [[[76, 77], + [82, 83]]]]) + """ + if not isinstance(block_shape, tuple): + raise TypeError('block needs to be a tuple') + + block_shape = np.array(block_shape) + if (block_shape <= 0).any(): + raise ValueError("'block_shape' elements must be strictly positive") + + if block_shape.size != arr_in.ndim: + raise ValueError("'block_shape' must have the same length " "as 'arr_in.shape'") + + arr_shape = np.array(arr_in.shape) + if (arr_shape % block_shape).sum() != 0: + raise ValueError("'block_shape' is not compatible with 'arr_in'") + + # -- restride the array to build the block view + new_shape = tuple(arr_shape // block_shape) + tuple(block_shape) + new_strides = tuple(arr_in.strides * block_shape) + arr_in.strides + + arr_out = as_strided(arr_in, shape=new_shape, strides=new_strides) + + return arr_out + + +def view_as_windows(arr_in, window_shape, step=1): + """Rolling window view of the input n-dimensional array. + + Windows are overlapping views of the input array, with adjacent windows + shifted by a single row or column (or an index of a higher dimension). + + Parameters + ---------- + arr_in : ndarray, shape (M[, ...]) + Input array. + window_shape : integer or tuple of length arr_in.ndim + Defines the shape of the elementary n-dimensional orthotope + (better know as hyperrectangle [1]_) of the rolling window view. + If an integer is given, the shape will be a hypercube of + sidelength given by its value. + step : integer or tuple of length arr_in.ndim + Indicates step size at which extraction shall be performed. + If integer is given, then the step is uniform in all dimensions. + + Returns + ------- + arr_out : ndarray + (rolling) window view of the input array. + + Notes + ----- + One should be very careful with rolling views when it comes to + memory usage. Indeed, although a 'view' has the same memory + footprint as its base array, the actual array that emerges when this + 'view' is used in a computation is generally a (much) larger array + than the original, especially for 2-dimensional arrays and above. + + For example, let us consider a 3 dimensional array of size (100, + 100, 100) of ``float64``. This array takes about 8*100**3 Bytes for + storage which is just 8 MB. If one decides to build a rolling view + on this array with a window of (3, 3, 3) the hypothetical size of + the rolling view (if one was to reshape the view for example) would + be 8*(100-3+1)**3*3**3 which is about 203 MB! The scaling becomes + even worse as the dimension of the input array becomes larger. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Hyperrectangle + + Examples + -------- + >>> import numpy as np + >>> from skimage.util.shape import view_as_windows + >>> A = np.arange(4*4).reshape(4,4) + >>> A + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + >>> window_shape = (2, 2) + >>> B = view_as_windows(A, window_shape) + >>> B[0, 0] + array([[0, 1], + [4, 5]]) + >>> B[0, 1] + array([[1, 2], + [5, 6]]) + + >>> A = np.arange(10) + >>> A + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> window_shape = (3,) + >>> B = view_as_windows(A, window_shape) + >>> B.shape + (8, 3) + >>> B + array([[0, 1, 2], + [1, 2, 3], + [2, 3, 4], + [3, 4, 5], + [4, 5, 6], + [5, 6, 7], + [6, 7, 8], + [7, 8, 9]]) + + >>> A = np.arange(5*4).reshape(5, 4) + >>> A + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15], + [16, 17, 18, 19]]) + >>> window_shape = (4, 3) + >>> B = view_as_windows(A, window_shape) + >>> B.shape + (2, 2, 4, 3) + >>> B # doctest: +NORMALIZE_WHITESPACE + array([[[[ 0, 1, 2], + [ 4, 5, 6], + [ 8, 9, 10], + [12, 13, 14]], + [[ 1, 2, 3], + [ 5, 6, 7], + [ 9, 10, 11], + [13, 14, 15]]], + [[[ 4, 5, 6], + [ 8, 9, 10], + [12, 13, 14], + [16, 17, 18]], + [[ 5, 6, 7], + [ 9, 10, 11], + [13, 14, 15], + [17, 18, 19]]]]) + """ + + # -- basic checks on arguments + if not isinstance(arr_in, np.ndarray): + raise TypeError("`arr_in` must be a numpy ndarray") + + ndim = arr_in.ndim + + if isinstance(window_shape, numbers.Number): + window_shape = (window_shape,) * ndim + if not (len(window_shape) == ndim): + raise ValueError("`window_shape` is incompatible with `arr_in.shape`") + + if isinstance(step, numbers.Number): + if step < 1: + raise ValueError("`step` must be >= 1") + step = (step,) * ndim + if len(step) != ndim: + raise ValueError("`step` is incompatible with `arr_in.shape`") + + arr_shape = np.array(arr_in.shape) + window_shape = np.array(window_shape, dtype=arr_shape.dtype) + + if ((arr_shape - window_shape) < 0).any(): + raise ValueError("`window_shape` is too large") + + if ((window_shape - 1) < 0).any(): + raise ValueError("`window_shape` is too small") + + # -- build rolling window view + slices = tuple(slice(None, None, st) for st in step) + window_strides = np.array(arr_in.strides) + + indexing_strides = arr_in[slices].strides + + win_indices_shape = ( + (np.array(arr_in.shape) - np.array(window_shape)) // np.array(step) + ) + 1 + + new_shape = tuple(list(win_indices_shape) + list(window_shape)) + strides = tuple(list(indexing_strides) + list(window_strides)) + + arr_out = as_strided(arr_in, shape=new_shape, strides=strides) + return arr_out diff --git a/envs/kitoverlay/skimage/util/unique.py b/envs/kitoverlay/skimage/util/unique.py new file mode 100644 index 0000000000000000000000000000000000000000..8a857bde5dadc4ab40ff38f2c330b7346eaa4dcd --- /dev/null +++ b/envs/kitoverlay/skimage/util/unique.py @@ -0,0 +1,51 @@ +import numpy as np + + +def unique_rows(ar): + """Remove repeated rows from a 2D array. + + In particular, if given an array of coordinates of shape + (Npoints, Ndim), it will remove repeated points. + + Parameters + ---------- + ar : ndarray, shape (M, N) + The input array. + + Returns + ------- + ar_out : ndarray, shape (P, N) + A copy of the input array with repeated rows removed. + + Raises + ------ + ValueError : if `ar` is not two-dimensional. + + Notes + ----- + The function will generate a copy of `ar` if it is not + C-contiguous, which will negatively affect performance for large + input arrays. + + Examples + -------- + >>> ar = np.array([[1, 0, 1], + ... [0, 1, 0], + ... [1, 0, 1]], np.uint8) + >>> unique_rows(ar) + array([[0, 1, 0], + [1, 0, 1]], dtype=uint8) + """ + if ar.ndim != 2: + raise ValueError( + "unique_rows() only makes sense for 2D arrays, " f"got {ar.ndim}" + ) + # the view in the next line only works if the array is C-contiguous + ar = np.ascontiguousarray(ar) + # np.unique() finds identical items in a raveled array. To make it + # see each row as a single item, we create a view of each row as a + # byte string of length itemsize times number of columns in `ar` + ar_row_view = ar.view(f"|S{ar.itemsize * ar.shape[1]}") + _, unique_row_indices = np.unique(ar_row_view, return_index=True) + ar_out = ar[unique_row_indices] + return ar_out diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/INSTALLER b/envs/kitoverlay/tifffile-2026.3.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/METADATA b/envs/kitoverlay/tifffile-2026.3.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1cce21b281eea15627fc9c0a1d9d2366bf34ee89 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/METADATA @@ -0,0 +1,854 @@ +Metadata-Version: 2.4 +Name: tifffile +Version: 2026.3.3 +Summary: Read and write TIFF files +Home-page: https://www.cgohlke.com +Author: Christoph Gohlke +Author-email: cgohlke@cgohlke.com +License: BSD-3-Clause +Project-URL: Bug Tracker, https://github.com/cgohlke/tifffile/issues +Project-URL: Source Code, https://github.com/cgohlke/tifffile +Platform: any +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.11 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: numpy +Provides-Extra: codecs +Requires-Dist: imagecodecs>=2025.11.11; extra == "codecs" +Provides-Extra: xml +Requires-Dist: defusedxml; extra == "xml" +Requires-Dist: lxml; extra == "xml" +Provides-Extra: zarr +Requires-Dist: zarr>=3.1.5; extra == "zarr" +Requires-Dist: fsspec; extra == "zarr" +Requires-Dist: kerchunk; extra == "zarr" +Provides-Extra: plot +Requires-Dist: matplotlib; extra == "plot" +Provides-Extra: all +Requires-Dist: imagecodecs>=2025.11.11; extra == "all" +Requires-Dist: matplotlib; extra == "all" +Requires-Dist: defusedxml; extra == "all" +Requires-Dist: lxml; extra == "all" +Requires-Dist: zarr>=3.1.5; extra == "all" +Requires-Dist: fsspec; extra == "all" +Requires-Dist: kerchunk; extra == "all" +Provides-Extra: test +Requires-Dist: cmapfile; extra == "test" +Requires-Dist: czifile; extra == "test" +Requires-Dist: dask; extra == "test" +Requires-Dist: defusedxml; extra == "test" +Requires-Dist: fsspec; extra == "test" +Requires-Dist: imagecodecs; extra == "test" +Requires-Dist: kerchunk; extra == "test" +Requires-Dist: lfdfiles; extra == "test" +Requires-Dist: lxml; extra == "test" +Requires-Dist: ndtiff; extra == "test" +Requires-Dist: oiffile; extra == "test" +Requires-Dist: psdtags; extra == "test" +Requires-Dist: pytest; extra == "test" +Requires-Dist: requests; extra == "test" +Requires-Dist: roifile; extra == "test" +Requires-Dist: xarray; extra == "test" +Requires-Dist: zarr>=3.1.5; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +Read and write TIFF files +========================= + +Tifffile is a comprehensive Python library to + +(1) store NumPy arrays in TIFF (Tagged Image File Format) files, and +(2) read image and metadata from TIFF-like files used in bioimaging. + +Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, GeoTIFF, +Adobe DNG, ZIF (Zoomable Image File Format), MetaMorph STK, Zeiss LSM, +ImageJ hyperstack, Micro-Manager MMStack and NDTiff, SGI, NIHImage, +Olympus FluoView and SIS, ScanImage, Molecular Dynamics GEL, +Aperio SVS, Leica SCN, Roche BIF, PerkinElmer QPTIFF (QPI, PKI), +Hamamatsu NDPI, Argos AVS, Philips DP, and ThermoFisher EER formatted files. + +Image data can be read as NumPy arrays or Zarr arrays/groups from strips, +tiles, pages (IFDs), SubIFDs, higher-order series, and pyramidal levels. + +Image data can be written to TIFF, BigTIFF, OME-TIFF, and ImageJ hyperstack +compatible files in multi-page, volumetric, pyramidal, memory-mappable, +tiled, predicted, or compressed form. + +Many compression and predictor schemes are supported via the imagecodecs +library, including LZW, PackBits, Deflate, CCITT, PIXTIFF, LZMA, LERC, Zstd, +JPEG (8 and 12-bit, lossless), JPEG 2000, JPEG XR, JPEG XL, WebP, PNG, EER, +Jetraw, 24-bit floating-point, and horizontal differencing. + +Tifffile can also be used to inspect TIFF structures, read image data from +multi-dimensional file sequences, write fsspec ReferenceFileSystem for +TIFF files and image file sequences, patch TIFF tag values, and parse +many proprietary metadata formats. + +:Author: `Christoph Gohlke `_ +:License: BSD-3-Clause +:Version: 2026.3.3 +:DOI: `10.5281/zenodo.6795860 `_ + +Quickstart +---------- + +Install the tifffile package and all dependencies from the +`Python Package Index `_:: + + python -m pip install -U tifffile[all] + +Tifffile is also available in other package repositories such as Anaconda, +Debian, and MSYS2. + +The tifffile library is type annotated and documented via docstrings:: + + python -c "import tifffile; help(tifffile)" + +Tifffile can be used as a console script to inspect and preview TIFF files:: + + python -m tifffile --help + +See `Examples`_ for using the programming interface. + +Source code and support are available on +`GitHub `_. + +Support is also provided on the +`image.sc `_ forum. + +Requirements +------------ + +This revision was tested with the following requirements and dependencies +(other versions may work): + +- `CPython `_ 3.11.9, 3.12.10, 3.13.12, 3.14.3 64-bit +- `NumPy `_ 2.4.2 +- `Imagecodecs `_ 2026.1.14 + (required for encoding or decoding LZW, JPEG, etc. compressed segments) +- `Matplotlib `_ 3.10.8 + (required for plotting) +- `Lxml `_ 6.0.2 + (required only for validating and printing XML) +- `Zarr `_ 3.1.5 + (required only for using Zarr stores; Zarr 2 is not compatible) +- `Kerchunk `_ 0.2.9 + (required only for opening ReferenceFileSystem files) + +Revisions +--------- + +2026.3.3 + +- Pass 5137 tests. +- Do not convert TVIPS pixel sizes to m (#319). +- Support writing packed integers with imagecodecs > 2026.1.14. +- Support reading ccitt compressed images with imagecodecs > 2026.1.14. + +2026.2.24 + +- Remove deprecated TiffPages.pages and FileSequence.files (breaking). +- Remove stripnull, stripascii, and bytestr functions (breaking). +- Rewrite command line interfaces (breaking). +- Support Experimenter and Project elements in OmeXml. +- Refactor TiffPages. +- Fix code review issues. + +2026.2.20 + +- Fix rounding of high resolutions (#318). +- Fix code review issues. + +2026.2.16 + +- Optimize reading multi-file pyramidal OME TIFF files. + +2026.2.15 + +- Support reading multi-file pyramidal OME TIFF files (image.sc/t/119259). + +2026.1.28 + +- Deprecate colormaped parameter in imagej_description (use colormapped). +- Fix code review issues. + +2026.1.14 + +- Improve code quality. + +2025.12.20 + +- Do not initialize output arrays. + +2025.12.12 + +- Improve code quality. + +2025.10.16 + +- Add option to decode EER super-resolution sub-pixels (breaking, #313). +- Parse EER metadata to dict (breaking). + +2025.10.4 + +- Fix parsing SVS description ending with "|". + +2025.9.30 + +- Fix reading NDTiff series with unordered axes in index (#311). + +2025.9.20 + +- Derive TiffFileError from ValueError. +- Natural-sort files in glob pattern passed to imread by default (breaking). +- Fix optional sorting of list of files passed to FileSequence and imread. + +2025.9.9 + +- Consolidate Nuvu camera metadata. + +2025.8.28 + +- Support DNG DCP files (#306). + +2025.6.11 + +- Fix reading images with dimension length 1 through Zarr (#303). + +2025.6.1 + +- Add experimental option to write iterator of bytes and bytecounts (#301). + +2025.5.26 + +- Use threads in Zarr stores. + +2025.5.24 + +- Fix incorrect tags created by Philips DP v1.1 (#299). +- Make Zarr stores partially listable. + +2025.5.21 + +- Move Zarr stores to tifffile.zarr namespace (breaking). +- Require Zarr 3 for Zarr stores and remove support for Zarr 2 (breaking). +- Drop support for Python 3.10. + +2025.5.10 + +- Raise ValueError when using Zarr 3 (#296). +- Fall back to compression.zstd on Python >= 3.14 if no imagecodecs. +- Remove doctest command line option. +- Support Python 3.14. + +2025.3.30 + +- Fix for imagecodecs 2025.3.30. + +2025.3.13 + +- … + +Refer to the CHANGES file for older revisions. + +Notes +----- + +TIFF, the Tagged Image File Format, was created by the Aldus Corporation and +Adobe Systems Incorporated. + +Tifffile supports a large subset of the TIFF6 specification, mainly 1-32, +and 64-bit integer, 16, 32, and 64-bit float, grayscale and multi-sample +images. +Specifically, OJPEG compression, chroma subsampling without JPEG compression, +color space transformations, samples with differing types, or IPTC, ICC, +and XMP metadata are not implemented. + +Besides classic TIFF, tifffile supports several TIFF-like formats that do not +strictly adhere to the TIFF6 specification. Some formats extend TIFF +capabilities in various ways, including exceeding the 4 GB limit, +handling multi-dimensional data, or working around format constraints: + +- **BigTIFF** is identified by version number 43 and uses different file + header, IFD, and tag structures with 64-bit offsets. The format also adds + 64-bit data types. Tifffile can read and write BigTIFF files. +- **ImageJ hyperstacks** store all image data, which may exceed 4 GB, + contiguously after the first IFD. Files > 4 GB contain one IFD only. + The size and shape of the up to 6-dimensional image data can be determined + from the ImageDescription tag of the first IFD, which is Latin-1 encoded. + Tifffile can read and write ImageJ hyperstacks. +- **OME-TIFF** files store up to 8-dimensional image data in one or multiple + TIFF or BigTIFF files. The UTF-8 encoded OME-XML metadata found in the + ImageDescription tag of the first IFD defines the position of TIFF IFDs in + the high-dimensional image data. Tifffile can read OME-TIFF files + and write NumPy arrays to single-file OME-TIFF. +- **Micro-Manager NDTiff** stores multi-dimensional image data in one + or more classic TIFF files. Metadata contained in a separate NDTiff.index + binary file defines the position of the TIFF IFDs in the image array. + Each TIFF file also contains metadata in a non-TIFF binary structure at + offset 8. Downsampled image data of pyramidal datasets are stored in + separate folders. Tifffile can read NDTiff files. Version 0 and 1 series, + tiling, stitching, and multi-resolution pyramids are not supported. +- **Micro-Manager MMStack** stores 6-dimensional image data in one or more + classic TIFF files. Metadata contained in non-TIFF binary structures and + JSON strings define the image stack dimensions and the position of the image + frame data in the file and the image stack. The TIFF structures and metadata + are often corrupted or wrong. Tifffile can read MMStack files. +- **Carl Zeiss LSM** files store all IFDs below 4 GB and wrap around 32-bit + StripOffsets pointing to image data above 4 GB. The StripOffsets of each + series and position require separate unwrapping. The StripByteCounts tag + contains the number of bytes for the uncompressed data. Tifffile can read + LSM files of any size. +- **MetaMorph STK** files contain additional image planes stored + contiguously after the image data of the first page. The total number of + planes is equal to the count of the UIC2 tag. Tifffile can read STK files. +- **ZIF**, the Zoomable Image File format, is a subspecification of BigTIFF + with SGI's ImageDepth extension and additional compression schemes. + Only little-endian, tiled, interleaved, 8-bit per sample images with + JPEG, PNG, JPEG XR, and JPEG 2000 compression are allowed. Tifffile can + read and write ZIF files. +- **Hamamatsu NDPI** files use some 64-bit offsets in the file header, IFD, + and tag structures. Single, LONG typed tag values can exceed 32-bit. + The high bytes of 64-bit tag values and offsets are stored after IFD + structures. Tifffile can read NDPI files > 4 GB. + JPEG compressed segments with dimensions >65530 or missing restart markers + cannot be decoded with common JPEG libraries. Tifffile works around this + limitation by separately decoding the MCUs between restart markers, which + performs poorly. BitsPerSample, SamplesPerPixel, and + PhotometricInterpretation tags may contain wrong values, which can be + corrected using the value of tag 65441. +- **Philips TIFF** slides store padded ImageWidth and ImageLength tag values + for tiled pages. The values can be corrected using the DICOM_PIXEL_SPACING + attributes of the XML formatted description of the first page. Tile offsets + and byte counts may be 0. Tifffile can read Philips slides. +- **Ventana/Roche BIF** slides store tiles and metadata in a BigTIFF container. + Tiles may overlap and require stitching based on the TileJointInfo elements + in the XMP tag. Volumetric scans are stored using the ImageDepth extension. + Tifffile can read BIF and decode individual tiles but does not perform + stitching. +- **ScanImage** optionally allows corrupted non-BigTIFF files > 2 GB. + The values of StripOffsets and StripByteCounts can be recovered using the + constant differences of the offsets of IFD and tag values throughout the + file. Tifffile can read such files if the image data are stored contiguously + in each page. +- **GeoTIFF sparse** files allow strip or tile offsets and byte counts to be 0. + Such segments are implicitly set to 0 or the NODATA value on reading. + Tifffile can read GeoTIFF sparse files. +- **Tifffile shaped** files store the array shape and user-provided metadata + of multi-dimensional image series in JSON format in the ImageDescription tag + of the first page of the series. The format allows multiple series, + SubIFDs, sparse segments with zero offset and byte count, and truncated + series, where only the first page of a series is present, and the image data + are stored contiguously. No other software besides Tifffile supports the + truncated format. + +Other libraries for reading, writing, inspecting, or manipulating scientific +TIFF files from Python are +`bioio `_, +`aicsimageio `_, +`apeer-ometiff-library +`_, +`bigtiff `_, +`fabio.TiffIO `_, +`GDAL `_, +`imread `_, +`large_image `_, +`openslide-python `_, +`opentile `_, +`pylibtiff `_, +`pylsm `_, +`pymimage `_, +`python-bioformats `_, +`pytiff `_, +`scanimagetiffreader-python +`_, +`SimpleITK `_, +`slideio `_, +`tiffslide `_, +`tifftools `_, +`tyf `_, +`xtiff `_, and +`ndtiff `_. + +References +---------- + +- TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated. + https://www.adobe.io/open/standards/TIFF.html + https://download.osgeo.org/libtiff/doc/ +- TIFF File Format FAQ. https://www.awaresystems.be/imaging/tiff/faq.html +- The BigTIFF File Format. + https://www.awaresystems.be/imaging/tiff/bigtiff.html +- MetaMorph Stack (STK) Image File Format. + http://mdc.custhelp.com/app/answers/detail/a_id/18862 +- Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010). + Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011 +- The OME-TIFF format. + https://docs.openmicroscopy.org/ome-model/latest/ +- UltraQuant(r) Version 6.0 for Windows Start-Up Guide. + http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf +- Micro-Manager File Formats. + https://micro-manager.org/wiki/Micro-Manager_File_Formats +- ScanImage BigTiff Specification. + https://docs.scanimage.org/Appendix/ScanImage+BigTiff+Specification.html +- ZIF, the Zoomable Image File format. https://zif.photo/ +- GeoTIFF File Format. https://gdal.org/drivers/raster/gtiff.html +- Cloud optimized GeoTIFF. + https://github.com/cogeotiff/cog-spec/blob/master/spec.md +- Tags for TIFF and Related Specifications. Digital Preservation. + https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml +- CIPA DC-008-2016: Exchangeable image file format for digital still cameras: + Exif Version 2.31. + http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf +- The EER (Electron Event Representation) file format. + https://github.com/fei-company/EerReaderLib +- Digital Negative (DNG) Specification. Version 1.7.1.0, September 2023. + https://helpx.adobe.com/content/dam/help/en/photoshop/pdf/DNG_Spec_1_7_1_0.pdf +- Roche Digital Pathology. BIF image file format for digital pathology. + https://diagnostics.roche.com/content/dam/diagnostics/Blueprint/en/pdf/rmd/Roche-Digital-Pathology-BIF-Whitepaper.pdf +- Astro-TIFF specification. https://astro-tiff.sourceforge.io/ +- Aperio Technologies, Inc. Digital Slides and Third-Party Data Interchange. + Aperio_Digital_Slides_and_Third-party_data_interchange.pdf +- PerkinElmer image format. + https://downloads.openmicroscopy.org/images/Vectra-QPTIFF/perkinelmer/PKI_Image%20Format.docx +- NDTiffStorage. https://github.com/micro-manager/NDTiffStorage +- Argos AVS File Format. + https://github.com/user-attachments/files/15580286/ARGOS.AVS.File.Format.pdf + +Examples +-------- + +Write a NumPy array to a single-page RGB TIFF file: + +>>> import numpy +>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8') +>>> imwrite('temp.tif', data, photometric='rgb') + +Read the image from the TIFF file as NumPy array: + +>>> image = imread('temp.tif') +>>> image.shape +(256, 256, 3) + +Use the `photometric` and `planarconfig` arguments to write a 3x3x3 NumPy +array to an interleaved RGB, a planar RGB, or a 3-page grayscale TIFF: + +>>> data = numpy.random.randint(0, 255, (3, 3, 3), 'uint8') +>>> imwrite('temp.tif', data, photometric='rgb') +>>> imwrite('temp.tif', data, photometric='rgb', planarconfig='separate') +>>> imwrite('temp.tif', data, photometric='minisblack') + +Use the `extrasamples` argument to specify how extra components are +interpreted, for example, for an RGBA image with unassociated alpha channel: + +>>> data = numpy.random.randint(0, 255, (256, 256, 4), 'uint8') +>>> imwrite('temp.tif', data, photometric='rgb', extrasamples=['unassalpha']) + +Write a 3-dimensional NumPy array to a multi-page, 16-bit grayscale TIFF file: + +>>> data = numpy.random.randint(0, 2**12, (64, 301, 219), 'uint16') +>>> imwrite('temp.tif', data, photometric='minisblack') + +Read the whole image stack from the multi-page TIFF file as NumPy array: + +>>> image_stack = imread('temp.tif') +>>> image_stack.shape +(64, 301, 219) +>>> image_stack.dtype +dtype('uint16') + +Read the image from the first page in the TIFF file as NumPy array: + +>>> image = imread('temp.tif', key=0) +>>> image.shape +(301, 219) + +Read images from a selected range of pages: + +>>> images = imread('temp.tif', key=range(4, 40, 2)) +>>> images.shape +(18, 301, 219) + +Iterate over all pages in the TIFF file and successively read images: + +>>> with TiffFile('temp.tif') as tif: +... for page in tif.pages: +... image = page.asarray() +... + +Get information about the image stack in the TIFF file without reading +any image data: + +>>> tif = TiffFile('temp.tif') +>>> len(tif.pages) # number of pages in the file +64 +>>> page = tif.pages[0] # get shape and dtype of image in first page +>>> page.shape +(301, 219) +>>> page.dtype +dtype('uint16') +>>> page.axes +'YX' +>>> series = tif.series[0] # get shape and dtype of first image series +>>> series.shape +(64, 301, 219) +>>> series.dtype +dtype('uint16') +>>> series.axes +'QYX' +>>> tif.close() + +Inspect the "XResolution" tag from the first page in the TIFF file: + +>>> with TiffFile('temp.tif') as tif: +... tag = tif.pages[0].tags['XResolution'] +... +>>> tag.value +(1, 1) +>>> tag.name +'XResolution' +>>> tag.code +282 +>>> tag.count +1 +>>> tag.dtype + + +Iterate over all tags in the TIFF file: + +>>> with TiffFile('temp.tif') as tif: +... for page in tif.pages: +... for tag in page.tags: +... tag_name, tag_value = tag.name, tag.value +... + +Overwrite the value of an existing tag, for example, XResolution: + +>>> with TiffFile('temp.tif', mode='r+') as tif: +... _ = tif.pages[0].tags['XResolution'].overwrite((96000, 1000)) +... + +Write a 5-dimensional floating-point array using BigTIFF format, separate +color components, tiling, Zlib compression level 8, horizontal differencing +predictor, and additional metadata: + +>>> data = numpy.random.rand(2, 5, 3, 301, 219).astype('float32') +>>> imwrite( +... 'temp.tif', +... data, +... bigtiff=True, +... photometric='rgb', +... planarconfig='separate', +... tile=(32, 32), +... compression='zlib', +... compressionargs={'level': 8}, +... predictor=True, +... metadata={'axes': 'TZCYX'}, +... ) + +Write a 10 fps time series of volumes with xyz voxel size 2.6755x2.6755x3.9474 +micron^3 to an ImageJ hyperstack formatted TIFF file: + +>>> volume = numpy.random.randn(6, 57, 256, 256).astype('float32') +>>> image_labels = [f'{i}' for i in range(volume.shape[0] * volume.shape[1])] +>>> imwrite( +... 'temp.tif', +... volume, +... imagej=True, +... resolution=(1.0 / 2.6755, 1.0 / 2.6755), +... metadata={ +... 'spacing': 3.947368, +... 'unit': 'um', +... 'finterval': 1 / 10, +... 'fps': 10.0, +... 'axes': 'TZYX', +... 'Labels': image_labels, +... }, +... ) + +Read the volume and metadata from the ImageJ hyperstack file: + +>>> with TiffFile('temp.tif') as tif: +... volume = tif.asarray() +... axes = tif.series[0].axes +... imagej_metadata = tif.imagej_metadata +... +>>> volume.shape +(6, 57, 256, 256) +>>> axes +'TZYX' +>>> imagej_metadata['slices'] +57 +>>> imagej_metadata['frames'] +6 + +Memory-map the contiguous image data in the ImageJ hyperstack file: + +>>> memmap_volume = memmap('temp.tif') +>>> memmap_volume.shape +(6, 57, 256, 256) +>>> del memmap_volume + +Create a TIFF file containing an empty image and write to the memory-mapped +NumPy array (note: this does not work with compression or tiling): + +>>> memmap_image = memmap( +... 'temp.tif', shape=(256, 256, 3), dtype='float32', photometric='rgb' +... ) +>>> type(memmap_image) + +>>> memmap_image[255, 255, 1] = 1.0 +>>> memmap_image.flush() +>>> del memmap_image + +Write two NumPy arrays to a multi-series TIFF file (note: other TIFF readers +will not recognize the two series; use the OME-TIFF format for better +interoperability): + +>>> series0 = numpy.random.randint(0, 255, (32, 32, 3), 'uint8') +>>> series1 = numpy.random.randint(0, 255, (4, 256, 256), 'uint16') +>>> with TiffWriter('temp.tif') as tif: +... tif.write(series0, photometric='rgb') +... tif.write(series1, photometric='minisblack') +... + +Read the second image series from the TIFF file: + +>>> series1 = imread('temp.tif', series=1) +>>> series1.shape +(4, 256, 256) + +Successively write the frames of one contiguous series to a TIFF file: + +>>> data = numpy.random.randint(0, 255, (30, 301, 219), 'uint8') +>>> with TiffWriter('temp.tif') as tif: +... for frame in data: +... tif.write(frame, contiguous=True) +... + +Append an image series to the existing TIFF file (note: this does not work +with ImageJ hyperstack or OME-TIFF files): + +>>> data = numpy.random.randint(0, 255, (301, 219, 3), 'uint8') +>>> imwrite('temp.tif', data, photometric='rgb', append=True) + +Create a TIFF file from a generator of tiles: + +>>> data = numpy.random.randint(0, 2**12, (31, 33, 3), 'uint16') +>>> def tiles(data, tileshape): +... for y in range(0, data.shape[0], tileshape[0]): +... for x in range(0, data.shape[1], tileshape[1]): +... yield data[y : y + tileshape[0], x : x + tileshape[1]] +... +>>> imwrite( +... 'temp.tif', +... tiles(data, (16, 16)), +... tile=(16, 16), +... shape=data.shape, +... dtype=data.dtype, +... photometric='rgb', +... ) + +Write a multi-dimensional, multi-resolution (pyramidal), multi-series OME-TIFF +file with optional metadata. Sub-resolution images are written to SubIFDs. +Limit parallel encoding to 2 threads. Write a thumbnail image as a separate +image series: + +>>> data = numpy.random.randint(0, 255, (8, 2, 512, 512, 3), 'uint8') +>>> subresolutions = 2 +>>> pixelsize = 0.29 # micrometer +>>> with TiffWriter('temp.ome.tif', bigtiff=True) as tif: +... metadata = { +... 'axes': 'TCYXS', +... 'SignificantBits': 8, +... 'TimeIncrement': 0.1, +... 'TimeIncrementUnit': 's', +... 'PhysicalSizeX': pixelsize, +... 'PhysicalSizeXUnit': 'µm', +... 'PhysicalSizeY': pixelsize, +... 'PhysicalSizeYUnit': 'µm', +... 'Channel': {'Name': ['Channel 1', 'Channel 2']}, +... 'Plane': {'PositionX': [0.0] * 16, 'PositionXUnit': ['µm'] * 16}, +... 'Description': 'A multi-dimensional, multi-resolution image', +... 'MapAnnotation': { # for OMERO +... 'Namespace': 'openmicroscopy.org/PyramidResolution', +... '1': '256 256', +... '2': '128 128', +... }, +... } +... options = dict( +... photometric='rgb', +... tile=(128, 128), +... compression='jpeg', +... resolutionunit='CENTIMETER', +... maxworkers=2, +... ) +... tif.write( +... data, +... subifds=subresolutions, +... resolution=(1e4 / pixelsize, 1e4 / pixelsize), +... metadata=metadata, +... **options, +... ) +... # write pyramid levels to the two subifds +... # in production use resampling to generate sub-resolution images +... for level in range(subresolutions): +... mag = 2 ** (level + 1) +... tif.write( +... data[..., ::mag, ::mag, :], +... subfiletype=1, # FILETYPE.REDUCEDIMAGE +... resolution=(1e4 / mag / pixelsize, 1e4 / mag / pixelsize), +... **options, +... ) +... # add a thumbnail image as a separate series +... # it is recognized by QuPath as an associated image +... thumbnail = (data[0, 0, ::8, ::8] >> 2).astype('uint8') +... tif.write(thumbnail, metadata={'Name': 'thumbnail'}) +... + +Access the image levels in the pyramidal OME-TIFF file: + +>>> baseimage = imread('temp.ome.tif') +>>> second_level = imread('temp.ome.tif', series=0, level=1) +>>> with TiffFile('temp.ome.tif') as tif: +... baseimage = tif.series[0].asarray() +... second_level = tif.series[0].levels[1].asarray() +... number_levels = len(tif.series[0].levels) # includes base level +... + +Iterate over and decode single JPEG compressed tiles in the TIFF file: + +>>> with TiffFile('temp.ome.tif') as tif: +... fh = tif.filehandle +... for page in tif.pages: +... for index, (offset, bytecount) in enumerate( +... zip(page.dataoffsets, page.databytecounts) +... ): +... _ = fh.seek(offset) +... data = fh.read(bytecount) +... tile, indices, shape = page.decode( +... data, index, jpegtables=page.jpegtables +... ) +... + +Use Zarr to read parts of the tiled, pyramidal images in the TIFF file: + +>>> import zarr +>>> store = imread('temp.ome.tif', aszarr=True) +>>> z = zarr.open(store, mode='r') +>>> z + +>>> z['0'] # base layer + +>>> z['0'][2, 0, 128:384, 256:].shape # read a tile from the base layer +(256, 256, 3) +>>> store.close() + +Load the base layer from the Zarr store as a dask array: + +>>> import dask.array +>>> store = imread('temp.ome.tif', aszarr=True) +>>> dask.array.from_zarr(store, '0', zarr_format=2) +dask.array<...shape=(8, 2, 512, 512, 3)...chunksize=(1, 1, 128, 128, 3)... +>>> store.close() + +Write the Zarr store to a fsspec ReferenceFileSystem in JSON format: + +>>> store = imread('temp.ome.tif', aszarr=True) +>>> store.write_fsspec('temp.ome.tif.json', url='file://') +>>> store.close() + +Open the fsspec ReferenceFileSystem as a Zarr group: + +>>> from kerchunk.utils import refs_as_store +>>> import imagecodecs.numcodecs +>>> imagecodecs.numcodecs.register_codecs(verbose=False) +>>> z = zarr.open(refs_as_store('temp.ome.tif.json'), mode='r') +>>> z +> + +Create an OME-TIFF file containing an empty, tiled image series and write +to it via the Zarr interface (note: this does not work with compression): + +>>> imwrite( +... 'temp2.ome.tif', +... shape=(8, 800, 600), +... dtype='uint16', +... photometric='minisblack', +... tile=(128, 128), +... metadata={'axes': 'CYX'}, +... ) +>>> store = imread('temp2.ome.tif', mode='r+', aszarr=True) +>>> z = zarr.open(store, mode='r+') +>>> z + +>>> z[3, 100:200, 200:300:2] = 1024 +>>> store.close() + +Read images from a sequence of TIFF files as NumPy array using two I/O worker +threads: + +>>> imwrite('temp_C001T001.tif', numpy.random.rand(64, 64)) +>>> imwrite('temp_C001T002.tif', numpy.random.rand(64, 64)) +>>> image_sequence = imread( +... ['temp_C001T001.tif', 'temp_C001T002.tif'], ioworkers=2, maxworkers=1 +... ) +>>> image_sequence.shape +(2, 64, 64) +>>> image_sequence.dtype +dtype('float64') + +Read an image stack from a series of TIFF files with a file name pattern +as NumPy or Zarr arrays: + +>>> image_sequence = TiffSequence('temp_C0*.tif', pattern=r'_(C)(\d+)(T)(\d+)') +>>> image_sequence.shape +(1, 2) +>>> image_sequence.axes +'CT' +>>> data = image_sequence.asarray() +>>> data.shape +(1, 2, 64, 64) +>>> store = image_sequence.aszarr() +>>> zarr.open(store, mode='r', ioworkers=2, maxworkers=1) + +>>> image_sequence.close() + +Write the Zarr store to a fsspec ReferenceFileSystem in JSON format: + +>>> store = image_sequence.aszarr() +>>> store.write_fsspec('temp.json', url='file://') + +Open the fsspec ReferenceFileSystem as a Zarr array: + +>>> from kerchunk.utils import refs_as_store +>>> import tifffile.numcodecs +>>> tifffile.numcodecs.register_codec() +>>> zarr.open(refs_as_store('temp.json'), mode='r') + shape=(1, 2, 64, 64) ...> + +Inspect the TIFF file from the command line:: + + $ python -m tifffile temp.ome.tif diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/RECORD b/envs/kitoverlay/tifffile-2026.3.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b5bcfbaa1352af755ba10dad4d4674b02e1f28c6 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/RECORD @@ -0,0 +1,33 @@ +../../bin/lsm2bin,sha256=0GJ5yc_1PgB732SZCY2Kj00-uv92naymgToot3vp8Z0,232 +../../bin/tiff2fsspec,sha256=8Mn2X8Eg6U2KRvIOsB8ed8amA3L_Lcvr0H_Rh3UzHIU,236 +../../bin/tiffcomment,sha256=L48_Q-hPEwLQ6ZvmYHz2wMn3r0Ze5OOOLXpn7b9ImNI,236 +../../bin/tifffile,sha256=Z4oU91fL98pKotjGZ1XC0gD62L6lzrY6NHrQQ9sqSow,224 +tifffile-2026.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tifffile-2026.3.3.dist-info/METADATA,sha256=ao1I8iBbffWoOl5g-2lLT0HC-AVI7TKNS07qnQQLh10,31502 +tifffile-2026.3.3.dist-info/RECORD,, +tifffile-2026.3.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tifffile-2026.3.3.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91 +tifffile-2026.3.3.dist-info/entry_points.txt,sha256=yynC-8YKYqjyaVBY_0jUdl6o0Sjsas8yPACRHnXe8b8,155 +tifffile-2026.3.3.dist-info/licenses/LICENSE,sha256=ZeZB8Xz84l7SwC8NU8lM-iOCzIgX7KZJp__yuJARSqQ,1559 +tifffile-2026.3.3.dist-info/top_level.txt,sha256=h6eqaHNqakJq0tVN037XQiRuWh1_3JA8SJLhkzbTfLg,9 +tifffile/__init__.py,sha256=Oc-e8gNiNXq73j5jEaxBwdKRRl8z9hl507gMlOfcbYM,217 +tifffile/__main__.py,sha256=IoJVoxI17vHliQoDCH6kIIr5FrV2I3KWzLBMbIJ2o-Q,200 +tifffile/__pycache__/__init__.cpython-311.pyc,, +tifffile/__pycache__/__main__.cpython-311.pyc,, +tifffile/__pycache__/_imagecodecs.cpython-311.pyc,, +tifffile/__pycache__/geodb.cpython-311.pyc,, +tifffile/__pycache__/lsm2bin.cpython-311.pyc,, +tifffile/__pycache__/numcodecs.cpython-311.pyc,, +tifffile/__pycache__/tiff2fsspec.cpython-311.pyc,, +tifffile/__pycache__/tiffcomment.cpython-311.pyc,, +tifffile/__pycache__/tifffile.cpython-311.pyc,, +tifffile/__pycache__/zarr.cpython-311.pyc,, +tifffile/_imagecodecs.py,sha256=oCKa0vyfchWB9XdyDF545GcYQ7U-tXfKpopT0D2VEvo,16900 +tifffile/geodb.py,sha256=a8gtB9UX8DWmLnEwfZk4zK-57fYOizaRV2Ci0KAywuk,61794 +tifffile/lsm2bin.py,sha256=9mUKikHBfeUSUEh4AGXVeCanoA5_YpXINqvaXyER6Zo,1887 +tifffile/numcodecs.py,sha256=5jguxDzNKuC--U7J-3SL4Chx1E7X6E7t6ELhasF-hqs,6162 +tifffile/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tifffile/tiff2fsspec.py,sha256=uw8PvyldRipuX-xpKOiUQbYhDk4XbqLlgeEsMUMx-34,3447 +tifffile/tiffcomment.py,sha256=UMZtNCIzgiFF5ycRe6RJKUlNzKjaEFQXJWQitkSflYI,3419 +tifffile/tifffile.py,sha256=qoOttwe-OVEH2vJIH7NngjOMxSEMcNk6dh5UBdeQtrk,901568 +tifffile/zarr.py,sha256=NllMWY72RwTpHA0sTWPczEqny7oJCe6Ib18DLcaQj8Q,58983 diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/REQUESTED b/envs/kitoverlay/tifffile-2026.3.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/WHEEL b/envs/kitoverlay/tifffile-2026.3.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ef5583317a5e59140e3f1c85c2db91aec0961e8 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/entry_points.txt b/envs/kitoverlay/tifffile-2026.3.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4225e4057ae716122b25be64c2accec3e338b42 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +lsm2bin = tifffile.lsm2bin:main +tiff2fsspec = tifffile.tiff2fsspec:main +tiffcomment = tifffile.tiffcomment:main +tifffile = tifffile:main diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/licenses/LICENSE b/envs/kitoverlay/tifffile-2026.3.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2bfc98bedf212914e953350606b06eb408bb4678 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/licenses/LICENSE @@ -0,0 +1,30 @@ +BSD-3-Clause license + +Copyright (c) 2008-2026, Christoph Gohlke +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/envs/kitoverlay/tifffile-2026.3.3.dist-info/top_level.txt b/envs/kitoverlay/tifffile-2026.3.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b626201914129589c7294a2367e9b577cf8b3a8 --- /dev/null +++ b/envs/kitoverlay/tifffile-2026.3.3.dist-info/top_level.txt @@ -0,0 +1 @@ +tifffile diff --git a/envs/sbin/cmake b/envs/sbin/cmake new file mode 100644 index 0000000000000000000000000000000000000000..fbcebf696b5ba8c0e93ca90194f6c72d8df9b9f0 --- /dev/null +++ b/envs/sbin/cmake @@ -0,0 +1,3 @@ +#!/bin/bash +HERE=$(cd "$(dirname "$0")" && pwd) +exec "$HERE/../../toolchain"/cmake-*-linux-x86_64/bin/cmake "$@" diff --git a/vendor/eigen/include/eigen3/Eigen/Cholesky b/vendor/eigen/include/eigen3/Eigen/Cholesky new file mode 100644 index 0000000000000000000000000000000000000000..a318ceb797dbaa10b2e1185583eb4803d7a83f8f --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Cholesky @@ -0,0 +1,45 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLESKY_MODULE_H +#define EIGEN_CHOLESKY_MODULE_H + +#include "Core" +#include "Jacobi" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Cholesky_Module Cholesky module + * + * + * + * This module provides two variants of the Cholesky decomposition for selfadjoint (hermitian) matrices. + * Those decompositions are also accessible via the following methods: + * - MatrixBase::llt() + * - MatrixBase::ldlt() + * - SelfAdjointView::llt() + * - SelfAdjointView::ldlt() + * + * \code + * #include + * \endcode + */ + +#include "src/Cholesky/LLT.h" +#include "src/Cholesky/LDLT.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/Cholesky/LLT_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CHOLESKY_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/CholmodSupport b/vendor/eigen/include/eigen3/Eigen/CholmodSupport new file mode 100644 index 0000000000000000000000000000000000000000..bed8924d31e0b3f46713cf74ba3deb6a63f9f590 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/CholmodSupport @@ -0,0 +1,48 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLMODSUPPORT_MODULE_H +#define EIGEN_CHOLMODSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { + #include +} + +/** \ingroup Support_modules + * \defgroup CholmodSupport_Module CholmodSupport module + * + * This module provides an interface to the Cholmod library which is part of the suitesparse package. + * It provides the two following main factorization classes: + * - class CholmodSupernodalLLT: a supernodal LLT Cholesky factorization. + * - class CholmodDecomposiiton: a general L(D)LT Cholesky factorization with automatic or explicit runtime selection of the underlying factorization method (supernodal or simplicial). + * + * For the sake of completeness, this module also propose the two following classes: + * - class CholmodSimplicialLLT + * - class CholmodSimplicialLDLT + * Note that these classes does not bring any particular advantage compared to the built-in + * SimplicialLLT and SimplicialLDLT factorization classes. + * + * \code + * #include + * \endcode + * + * In order to use this module, the cholmod headers must be accessible from the include paths, and your binary must be linked to the cholmod library and its dependencies. + * The dependencies depend on how cholmod has been compiled. + * For a cmake based project, you can use our FindCholmod.cmake module to help you in this task. + * + */ + +#include "src/CholmodSupport/CholmodSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CHOLMODSUPPORT_MODULE_H + diff --git a/vendor/eigen/include/eigen3/Eigen/Core b/vendor/eigen/include/eigen3/Eigen/Core new file mode 100644 index 0000000000000000000000000000000000000000..5921e15f9df46319ceb5436296b3271ca4dc9e65 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Core @@ -0,0 +1,384 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2007-2011 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CORE_H +#define EIGEN_CORE_H + +// first thing Eigen does: stop the compiler from reporting useless warnings. +#include "src/Core/util/DisableStupidWarnings.h" + +// then include this file where all our macros are defined. It's really important to do it first because +// it's where we do all the compiler/OS/arch detections and define most defaults. +#include "src/Core/util/Macros.h" + +// This detects SSE/AVX/NEON/etc. and configure alignment settings +#include "src/Core/util/ConfigureVectorization.h" + +// We need cuda_runtime.h/hip_runtime.h to ensure that +// the EIGEN_USING_STD macro works properly on the device side +#if defined(EIGEN_CUDACC) + #include +#elif defined(EIGEN_HIPCC) + #include +#endif + + +#ifdef EIGEN_EXCEPTIONS + #include +#endif + +// Disable the ipa-cp-clone optimization flag with MinGW 6.x or newer (enabled by default with -O3) +// See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=556 for details. +#if EIGEN_COMP_MINGW && EIGEN_GNUC_AT_LEAST(4,6) && EIGEN_GNUC_AT_MOST(5,5) + #pragma GCC optimize ("-fno-ipa-cp-clone") +#endif + +// Prevent ICC from specializing std::complex operators that silently fail +// on device. This allows us to use our own device-compatible specializations +// instead. +#if defined(EIGEN_COMP_ICC) && defined(EIGEN_GPU_COMPILE_PHASE) \ + && !defined(_OVERRIDE_COMPLEX_SPECIALIZATION_) +#define _OVERRIDE_COMPLEX_SPECIALIZATION_ 1 +#endif +#include + +// this include file manages BLAS and MKL related macros +// and inclusion of their respective header files +#include "src/Core/util/MKL_support.h" + + +#if defined(EIGEN_HAS_CUDA_FP16) || defined(EIGEN_HAS_HIP_FP16) + #define EIGEN_HAS_GPU_FP16 +#endif + +#if defined(EIGEN_HAS_CUDA_BF16) || defined(EIGEN_HAS_HIP_BF16) + #define EIGEN_HAS_GPU_BF16 +#endif + +#if (defined _OPENMP) && (!defined EIGEN_DONT_PARALLELIZE) + #define EIGEN_HAS_OPENMP +#endif + +#ifdef EIGEN_HAS_OPENMP +#include +#endif + +// MSVC for windows mobile does not have the errno.h file +#if !(EIGEN_COMP_MSVC && EIGEN_OS_WINCE) && !EIGEN_COMP_ARM +#define EIGEN_HAS_ERRNO +#endif + +#ifdef EIGEN_HAS_ERRNO +#include +#endif +#include +#include +#include +#include +#include +#include +#ifndef EIGEN_NO_IO + #include +#endif +#include +#include +#include +#include // for CHAR_BIT +// for min/max: +#include + +#if EIGEN_HAS_CXX11 +#include +#endif + +// for std::is_nothrow_move_assignable +#ifdef EIGEN_INCLUDE_TYPE_TRAITS +#include +#endif + +// for outputting debug info +#ifdef EIGEN_DEBUG_ASSIGN +#include +#endif + +// required for __cpuid, needs to be included after cmath +#if EIGEN_COMP_MSVC && EIGEN_ARCH_i386_OR_x86_64 && !EIGEN_OS_WINCE + #include +#endif + +#if defined(EIGEN_USE_SYCL) + #undef min + #undef max + #undef isnan + #undef isinf + #undef isfinite + #include + #include + #include + #include + #include + #ifndef EIGEN_SYCL_LOCAL_THREAD_DIM0 + #define EIGEN_SYCL_LOCAL_THREAD_DIM0 16 + #endif + #ifndef EIGEN_SYCL_LOCAL_THREAD_DIM1 + #define EIGEN_SYCL_LOCAL_THREAD_DIM1 16 + #endif +#endif + + +#if defined EIGEN2_SUPPORT_STAGE40_FULL_EIGEN3_STRICTNESS || defined EIGEN2_SUPPORT_STAGE30_FULL_EIGEN3_API || defined EIGEN2_SUPPORT_STAGE20_RESOLVE_API_CONFLICTS || defined EIGEN2_SUPPORT_STAGE10_FULL_EIGEN2_API || defined EIGEN2_SUPPORT +// This will generate an error message: +#error Eigen2-support is only available up to version 3.2. Please go to "http://eigen.tuxfamily.org/index.php?title=Eigen2" for further information +#endif + +namespace Eigen { + +// we use size_t frequently and we'll never remember to prepend it with std:: every time just to +// ensure QNX/QCC support +using std::size_t; +// gcc 4.6.0 wants std:: for ptrdiff_t +using std::ptrdiff_t; + +} + +/** \defgroup Core_Module Core module + * This is the main module of Eigen providing dense matrix and vector support + * (both fixed and dynamic size) with all the features corresponding to a BLAS library + * and much more... + * + * \code + * #include + * \endcode + */ + +#include "src/Core/util/Constants.h" +#include "src/Core/util/Meta.h" +#include "src/Core/util/ForwardDeclarations.h" +#include "src/Core/util/StaticAssert.h" +#include "src/Core/util/XprHelper.h" +#include "src/Core/util/Memory.h" +#include "src/Core/util/IntegralConstant.h" +#include "src/Core/util/SymbolicIndex.h" + +#include "src/Core/NumTraits.h" +#include "src/Core/MathFunctions.h" +#include "src/Core/GenericPacketMath.h" +#include "src/Core/MathFunctionsImpl.h" +#include "src/Core/arch/Default/ConjHelper.h" +// Generic half float support +#include "src/Core/arch/Default/Half.h" +#include "src/Core/arch/Default/BFloat16.h" +#include "src/Core/arch/Default/TypeCasting.h" +#include "src/Core/arch/Default/GenericPacketMathFunctionsFwd.h" + +#if defined EIGEN_VECTORIZE_AVX512 + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/SSE/TypeCasting.h" + #include "src/Core/arch/SSE/Complex.h" + #include "src/Core/arch/AVX/PacketMath.h" + #include "src/Core/arch/AVX/TypeCasting.h" + #include "src/Core/arch/AVX/Complex.h" + #include "src/Core/arch/AVX512/PacketMath.h" + #include "src/Core/arch/AVX512/TypeCasting.h" + #include "src/Core/arch/AVX512/Complex.h" + #include "src/Core/arch/SSE/MathFunctions.h" + #include "src/Core/arch/AVX/MathFunctions.h" + #include "src/Core/arch/AVX512/MathFunctions.h" +#elif defined EIGEN_VECTORIZE_AVX + // Use AVX for floats and doubles, SSE for integers + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/SSE/TypeCasting.h" + #include "src/Core/arch/SSE/Complex.h" + #include "src/Core/arch/AVX/PacketMath.h" + #include "src/Core/arch/AVX/TypeCasting.h" + #include "src/Core/arch/AVX/Complex.h" + #include "src/Core/arch/SSE/MathFunctions.h" + #include "src/Core/arch/AVX/MathFunctions.h" +#elif defined EIGEN_VECTORIZE_SSE + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/SSE/TypeCasting.h" + #include "src/Core/arch/SSE/MathFunctions.h" + #include "src/Core/arch/SSE/Complex.h" +#elif defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) + #include "src/Core/arch/AltiVec/PacketMath.h" + #include "src/Core/arch/AltiVec/MathFunctions.h" + #include "src/Core/arch/AltiVec/Complex.h" +#elif defined EIGEN_VECTORIZE_NEON + #include "src/Core/arch/NEON/PacketMath.h" + #include "src/Core/arch/NEON/TypeCasting.h" + #include "src/Core/arch/NEON/MathFunctions.h" + #include "src/Core/arch/NEON/Complex.h" +#elif defined EIGEN_VECTORIZE_SVE + #include "src/Core/arch/SVE/PacketMath.h" + #include "src/Core/arch/SVE/TypeCasting.h" + #include "src/Core/arch/SVE/MathFunctions.h" +#elif defined EIGEN_VECTORIZE_ZVECTOR + #include "src/Core/arch/ZVector/PacketMath.h" + #include "src/Core/arch/ZVector/MathFunctions.h" + #include "src/Core/arch/ZVector/Complex.h" +#elif defined EIGEN_VECTORIZE_MSA + #include "src/Core/arch/MSA/PacketMath.h" + #include "src/Core/arch/MSA/MathFunctions.h" + #include "src/Core/arch/MSA/Complex.h" +#endif + +#if defined EIGEN_VECTORIZE_GPU + #include "src/Core/arch/GPU/PacketMath.h" + #include "src/Core/arch/GPU/MathFunctions.h" + #include "src/Core/arch/GPU/TypeCasting.h" +#endif + +#if defined(EIGEN_USE_SYCL) + #include "src/Core/arch/SYCL/SyclMemoryModel.h" + #include "src/Core/arch/SYCL/InteropHeaders.h" +#if !defined(EIGEN_DONT_VECTORIZE_SYCL) + #include "src/Core/arch/SYCL/PacketMath.h" + #include "src/Core/arch/SYCL/MathFunctions.h" + #include "src/Core/arch/SYCL/TypeCasting.h" +#endif +#endif + +#include "src/Core/arch/Default/Settings.h" +// This file provides generic implementations valid for scalar as well +#include "src/Core/arch/Default/GenericPacketMathFunctions.h" + +#include "src/Core/functors/TernaryFunctors.h" +#include "src/Core/functors/BinaryFunctors.h" +#include "src/Core/functors/UnaryFunctors.h" +#include "src/Core/functors/NullaryFunctors.h" +#include "src/Core/functors/StlFunctors.h" +#include "src/Core/functors/AssignmentFunctors.h" + +// Specialized functors to enable the processing of complex numbers +// on CUDA devices +#ifdef EIGEN_CUDACC +#include "src/Core/arch/CUDA/Complex.h" +#endif + +#include "src/Core/util/IndexedViewHelper.h" +#include "src/Core/util/ReshapedHelper.h" +#include "src/Core/ArithmeticSequence.h" +#ifndef EIGEN_NO_IO + #include "src/Core/IO.h" +#endif +#include "src/Core/DenseCoeffsBase.h" +#include "src/Core/DenseBase.h" +#include "src/Core/MatrixBase.h" +#include "src/Core/EigenBase.h" + +#include "src/Core/Product.h" +#include "src/Core/CoreEvaluators.h" +#include "src/Core/AssignEvaluator.h" + +#ifndef EIGEN_PARSED_BY_DOXYGEN // work around Doxygen bug triggered by Assign.h r814874 + // at least confirmed with Doxygen 1.5.5 and 1.5.6 + #include "src/Core/Assign.h" +#endif + +#include "src/Core/ArrayBase.h" +#include "src/Core/util/BlasUtil.h" +#include "src/Core/DenseStorage.h" +#include "src/Core/NestByValue.h" + +// #include "src/Core/ForceAlignedAccess.h" + +#include "src/Core/ReturnByValue.h" +#include "src/Core/NoAlias.h" +#include "src/Core/PlainObjectBase.h" +#include "src/Core/Matrix.h" +#include "src/Core/Array.h" +#include "src/Core/CwiseTernaryOp.h" +#include "src/Core/CwiseBinaryOp.h" +#include "src/Core/CwiseUnaryOp.h" +#include "src/Core/CwiseNullaryOp.h" +#include "src/Core/CwiseUnaryView.h" +#include "src/Core/SelfCwiseBinaryOp.h" +#include "src/Core/Dot.h" +#include "src/Core/StableNorm.h" +#include "src/Core/Stride.h" +#include "src/Core/MapBase.h" +#include "src/Core/Map.h" +#include "src/Core/Ref.h" +#include "src/Core/Block.h" +#include "src/Core/VectorBlock.h" +#include "src/Core/IndexedView.h" +#include "src/Core/Reshaped.h" +#include "src/Core/Transpose.h" +#include "src/Core/DiagonalMatrix.h" +#include "src/Core/Diagonal.h" +#include "src/Core/DiagonalProduct.h" +#include "src/Core/Redux.h" +#include "src/Core/Visitor.h" +#include "src/Core/Fuzzy.h" +#include "src/Core/Swap.h" +#include "src/Core/CommaInitializer.h" +#include "src/Core/GeneralProduct.h" +#include "src/Core/Solve.h" +#include "src/Core/Inverse.h" +#include "src/Core/SolverBase.h" +#include "src/Core/PermutationMatrix.h" +#include "src/Core/Transpositions.h" +#include "src/Core/TriangularMatrix.h" +#include "src/Core/SelfAdjointView.h" +#include "src/Core/products/GeneralBlockPanelKernel.h" +#include "src/Core/products/Parallelizer.h" +#include "src/Core/ProductEvaluators.h" +#include "src/Core/products/GeneralMatrixVector.h" +#include "src/Core/products/GeneralMatrixMatrix.h" +#include "src/Core/SolveTriangular.h" +#include "src/Core/products/GeneralMatrixMatrixTriangular.h" +#include "src/Core/products/SelfadjointMatrixVector.h" +#include "src/Core/products/SelfadjointMatrixMatrix.h" +#include "src/Core/products/SelfadjointProduct.h" +#include "src/Core/products/SelfadjointRank2Update.h" +#include "src/Core/products/TriangularMatrixVector.h" +#include "src/Core/products/TriangularMatrixMatrix.h" +#include "src/Core/products/TriangularSolverMatrix.h" +#include "src/Core/products/TriangularSolverVector.h" +#include "src/Core/BandMatrix.h" +#include "src/Core/CoreIterators.h" +#include "src/Core/ConditionEstimator.h" + +#if defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) + #include "src/Core/arch/AltiVec/MatrixProduct.h" +#elif defined EIGEN_VECTORIZE_NEON + #include "src/Core/arch/NEON/GeneralBlockPanelKernel.h" +#endif + +#include "src/Core/BooleanRedux.h" +#include "src/Core/Select.h" +#include "src/Core/VectorwiseOp.h" +#include "src/Core/PartialReduxEvaluator.h" +#include "src/Core/Random.h" +#include "src/Core/Replicate.h" +#include "src/Core/Reverse.h" +#include "src/Core/ArrayWrapper.h" +#include "src/Core/StlIterators.h" + +#ifdef EIGEN_USE_BLAS +#include "src/Core/products/GeneralMatrixMatrix_BLAS.h" +#include "src/Core/products/GeneralMatrixVector_BLAS.h" +#include "src/Core/products/GeneralMatrixMatrixTriangular_BLAS.h" +#include "src/Core/products/SelfadjointMatrixMatrix_BLAS.h" +#include "src/Core/products/SelfadjointMatrixVector_BLAS.h" +#include "src/Core/products/TriangularMatrixMatrix_BLAS.h" +#include "src/Core/products/TriangularMatrixVector_BLAS.h" +#include "src/Core/products/TriangularSolverMatrix_BLAS.h" +#endif // EIGEN_USE_BLAS + +#ifdef EIGEN_USE_MKL_VML +#include "src/Core/Assign_MKL.h" +#endif + +#include "src/Core/GlobalFunctions.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CORE_H diff --git a/vendor/eigen/include/eigen3/Eigen/Dense b/vendor/eigen/include/eigen3/Eigen/Dense new file mode 100644 index 0000000000000000000000000000000000000000..5768910bd88c43f0761f2f345c6f0e3b46a4d8ec --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Dense @@ -0,0 +1,7 @@ +#include "Core" +#include "LU" +#include "Cholesky" +#include "QR" +#include "SVD" +#include "Geometry" +#include "Eigenvalues" diff --git a/vendor/eigen/include/eigen3/Eigen/Eigen b/vendor/eigen/include/eigen3/Eigen/Eigen new file mode 100644 index 0000000000000000000000000000000000000000..654c8dc6380f7bb21d3ba1a9ce916006043552aa --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Eigen @@ -0,0 +1,2 @@ +#include "Dense" +#include "Sparse" diff --git a/vendor/eigen/include/eigen3/Eigen/Eigenvalues b/vendor/eigen/include/eigen3/Eigen/Eigenvalues new file mode 100644 index 0000000000000000000000000000000000000000..5467a2e7b3ecf40c3e544bb29717a66c83f7eaa1 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Eigenvalues @@ -0,0 +1,60 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EIGENVALUES_MODULE_H +#define EIGEN_EIGENVALUES_MODULE_H + +#include "Core" + +#include "Cholesky" +#include "Jacobi" +#include "Householder" +#include "LU" +#include "Geometry" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Eigenvalues_Module Eigenvalues module + * + * + * + * This module mainly provides various eigenvalue solvers. + * This module also provides some MatrixBase methods, including: + * - MatrixBase::eigenvalues(), + * - MatrixBase::operatorNorm() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/RealSvd2x2.h" +#include "src/Eigenvalues/Tridiagonalization.h" +#include "src/Eigenvalues/RealSchur.h" +#include "src/Eigenvalues/EigenSolver.h" +#include "src/Eigenvalues/SelfAdjointEigenSolver.h" +#include "src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h" +#include "src/Eigenvalues/HessenbergDecomposition.h" +#include "src/Eigenvalues/ComplexSchur.h" +#include "src/Eigenvalues/ComplexEigenSolver.h" +#include "src/Eigenvalues/RealQZ.h" +#include "src/Eigenvalues/GeneralizedEigenSolver.h" +#include "src/Eigenvalues/MatrixBaseEigenvalues.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/Eigenvalues/RealSchur_LAPACKE.h" +#include "src/Eigenvalues/ComplexSchur_LAPACKE.h" +#include "src/Eigenvalues/SelfAdjointEigenSolver_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_EIGENVALUES_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/Geometry b/vendor/eigen/include/eigen3/Eigen/Geometry new file mode 100644 index 0000000000000000000000000000000000000000..bc78110a846693fa45caa0780cf29d7285695f08 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Geometry @@ -0,0 +1,59 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GEOMETRY_MODULE_H +#define EIGEN_GEOMETRY_MODULE_H + +#include "Core" + +#include "SVD" +#include "LU" +#include + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Geometry_Module Geometry module + * + * This module provides support for: + * - fixed-size homogeneous transformations + * - translation, scaling, 2D and 3D rotations + * - \link Quaternion quaternions \endlink + * - cross products (\ref MatrixBase::cross, \ref MatrixBase::cross3) + * - orthognal vector generation (\ref MatrixBase::unitOrthogonal) + * - some linear components: \link ParametrizedLine parametrized-lines \endlink and \link Hyperplane hyperplanes \endlink + * - \link AlignedBox axis aligned bounding boxes \endlink + * - \link umeyama least-square transformation fitting \endlink + * + * \code + * #include + * \endcode + */ + +#include "src/Geometry/OrthoMethods.h" +#include "src/Geometry/EulerAngles.h" + +#include "src/Geometry/Homogeneous.h" +#include "src/Geometry/RotationBase.h" +#include "src/Geometry/Rotation2D.h" +#include "src/Geometry/Quaternion.h" +#include "src/Geometry/AngleAxis.h" +#include "src/Geometry/Transform.h" +#include "src/Geometry/Translation.h" +#include "src/Geometry/Scaling.h" +#include "src/Geometry/Hyperplane.h" +#include "src/Geometry/ParametrizedLine.h" +#include "src/Geometry/AlignedBox.h" +#include "src/Geometry/Umeyama.h" + +// Use the SSE optimized version whenever possible. +#if (defined EIGEN_VECTORIZE_SSE) || (defined EIGEN_VECTORIZE_NEON) +#include "src/Geometry/arch/Geometry_SIMD.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_GEOMETRY_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/Householder b/vendor/eigen/include/eigen3/Eigen/Householder new file mode 100644 index 0000000000000000000000000000000000000000..f2fa79969c96339bd317d157a37c72ec71b4024b --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Householder @@ -0,0 +1,29 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_HOUSEHOLDER_MODULE_H +#define EIGEN_HOUSEHOLDER_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Householder_Module Householder module + * This module provides Householder transformations. + * + * \code + * #include + * \endcode + */ + +#include "src/Householder/Householder.h" +#include "src/Householder/HouseholderSequence.h" +#include "src/Householder/BlockHouseholder.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_HOUSEHOLDER_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/IterativeLinearSolvers b/vendor/eigen/include/eigen3/Eigen/IterativeLinearSolvers new file mode 100644 index 0000000000000000000000000000000000000000..957d5750b2cd6f9a429c7140335487a4d8b87b25 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/IterativeLinearSolvers @@ -0,0 +1,48 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ITERATIVELINEARSOLVERS_MODULE_H +#define EIGEN_ITERATIVELINEARSOLVERS_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup IterativeLinearSolvers_Module IterativeLinearSolvers module + * + * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a squared matrix, usually very large and sparse. + * Those solvers are accessible via the following classes: + * - ConjugateGradient for selfadjoint (hermitian) matrices, + * - LeastSquaresConjugateGradient for rectangular least-square problems, + * - BiCGSTAB for general square matrices. + * + * These iterative solvers are associated with some preconditioners: + * - IdentityPreconditioner - not really useful + * - DiagonalPreconditioner - also called Jacobi preconditioner, work very well on diagonal dominant matrices. + * - IncompleteLUT - incomplete LU factorization with dual thresholding + * + * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, UmfPackSupport, SuperLUSupport. + * + \code + #include + \endcode + */ + +#include "src/IterativeLinearSolvers/SolveWithGuess.h" +#include "src/IterativeLinearSolvers/IterativeSolverBase.h" +#include "src/IterativeLinearSolvers/BasicPreconditioners.h" +#include "src/IterativeLinearSolvers/ConjugateGradient.h" +#include "src/IterativeLinearSolvers/LeastSquareConjugateGradient.h" +#include "src/IterativeLinearSolvers/BiCGSTAB.h" +#include "src/IterativeLinearSolvers/IncompleteLUT.h" +#include "src/IterativeLinearSolvers/IncompleteCholesky.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/Jacobi b/vendor/eigen/include/eigen3/Eigen/Jacobi new file mode 100644 index 0000000000000000000000000000000000000000..43edc7a1946edaa8c30c8715c50ebcf8d817fa3a --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Jacobi @@ -0,0 +1,32 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_JACOBI_MODULE_H +#define EIGEN_JACOBI_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Jacobi_Module Jacobi module + * This module provides Jacobi and Givens rotations. + * + * \code + * #include + * \endcode + * + * In addition to listed classes, it defines the two following MatrixBase methods to apply a Jacobi or Givens rotation: + * - MatrixBase::applyOnTheLeft() + * - MatrixBase::applyOnTheRight(). + */ + +#include "src/Jacobi/Jacobi.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_JACOBI_MODULE_H + diff --git a/vendor/eigen/include/eigen3/Eigen/KLUSupport b/vendor/eigen/include/eigen3/Eigen/KLUSupport new file mode 100644 index 0000000000000000000000000000000000000000..b23d905351566cb425a803cba5868ea43338f9a6 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/KLUSupport @@ -0,0 +1,41 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_KLUSUPPORT_MODULE_H +#define EIGEN_KLUSUPPORT_MODULE_H + +#include + +#include + +extern "C" { +#include +#include + } + +/** \ingroup Support_modules + * \defgroup KLUSupport_Module KLUSupport module + * + * This module provides an interface to the KLU library which is part of the suitesparse package. + * It provides the following factorization class: + * - class KLU: a sparse LU factorization, well-suited for circuit simulation. + * + * \code + * #include + * \endcode + * + * In order to use this module, the klu and btf headers must be accessible from the include paths, and your binary must be linked to the klu library and its dependencies. + * The dependencies depend on how umfpack has been compiled. + * For a cmake based project, you can use our FindKLU.cmake module to help you in this task. + * + */ + +#include "src/KLUSupport/KLUSupport.h" + +#include + +#endif // EIGEN_KLUSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/LU b/vendor/eigen/include/eigen3/Eigen/LU new file mode 100644 index 0000000000000000000000000000000000000000..1236ceb04676f5e180b589f8ca70c3d9362710cf --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/LU @@ -0,0 +1,47 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LU_MODULE_H +#define EIGEN_LU_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup LU_Module LU module + * This module includes %LU decomposition and related notions such as matrix inversion and determinant. + * This module defines the following MatrixBase methods: + * - MatrixBase::inverse() + * - MatrixBase::determinant() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/Kernel.h" +#include "src/misc/Image.h" +#include "src/LU/FullPivLU.h" +#include "src/LU/PartialPivLU.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/LU/PartialPivLU_LAPACKE.h" +#endif +#include "src/LU/Determinant.h" +#include "src/LU/InverseImpl.h" + +#if defined EIGEN_VECTORIZE_SSE || defined EIGEN_VECTORIZE_NEON + #include "src/LU/arch/InverseSize4.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_LU_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/MetisSupport b/vendor/eigen/include/eigen3/Eigen/MetisSupport new file mode 100644 index 0000000000000000000000000000000000000000..85c41bf340013e4583e505c496dfb567dc6ae80a --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/MetisSupport @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_METISSUPPORT_MODULE_H +#define EIGEN_METISSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +} + + +/** \ingroup Support_modules + * \defgroup MetisSupport_Module MetisSupport module + * + * \code + * #include + * \endcode + * This module defines an interface to the METIS reordering package (http://glaros.dtc.umn.edu/gkhome/views/metis). + * It can be used just as any other built-in method as explained in \link OrderingMethods_Module here. \endlink + */ + + +#include "src/MetisSupport/MetisSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_METISSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/OrderingMethods b/vendor/eigen/include/eigen3/Eigen/OrderingMethods new file mode 100644 index 0000000000000000000000000000000000000000..29691a62b44d4956a660a677233c7bce3fd05dce --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/OrderingMethods @@ -0,0 +1,70 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ORDERINGMETHODS_MODULE_H +#define EIGEN_ORDERINGMETHODS_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup OrderingMethods_Module OrderingMethods module + * + * This module is currently for internal use only + * + * It defines various built-in and external ordering methods for sparse matrices. + * They are typically used to reduce the number of elements during + * the sparse matrix decomposition (LLT, LU, QR). + * Precisely, in a preprocessing step, a permutation matrix P is computed using + * those ordering methods and applied to the columns of the matrix. + * Using for instance the sparse Cholesky decomposition, it is expected that + * the nonzeros elements in LLT(A*P) will be much smaller than that in LLT(A). + * + * + * Usage : + * \code + * #include + * \endcode + * + * A simple usage is as a template parameter in the sparse decomposition classes : + * + * \code + * SparseLU > solver; + * \endcode + * + * \code + * SparseQR > solver; + * \endcode + * + * It is possible as well to call directly a particular ordering method for your own purpose, + * \code + * AMDOrdering ordering; + * PermutationMatrix perm; + * SparseMatrix A; + * //Fill the matrix ... + * + * ordering(A, perm); // Call AMD + * \endcode + * + * \note Some of these methods (like AMD or METIS), need the sparsity pattern + * of the input matrix to be symmetric. When the matrix is structurally unsymmetric, + * Eigen computes internally the pattern of \f$A^T*A\f$ before calling the method. + * If your matrix is already symmetric (at leat in structure), you can avoid that + * by calling the method with a SelfAdjointView type. + * + * \code + * // Call the ordering on the pattern of the lower triangular matrix A + * ordering(A.selfadjointView(), perm); + * \endcode + */ + +#include "src/OrderingMethods/Amd.h" +#include "src/OrderingMethods/Ordering.h" +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ORDERINGMETHODS_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/PaStiXSupport b/vendor/eigen/include/eigen3/Eigen/PaStiXSupport new file mode 100644 index 0000000000000000000000000000000000000000..234619accee0e875a418eda983f870b25255c17e --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/PaStiXSupport @@ -0,0 +1,49 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PASTIXSUPPORT_MODULE_H +#define EIGEN_PASTIXSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +#include +} + +#ifdef complex +#undef complex +#endif + +/** \ingroup Support_modules + * \defgroup PaStiXSupport_Module PaStiXSupport module + * + * This module provides an interface to the PaSTiX library. + * PaSTiX is a general \b supernodal, \b parallel and \b opensource sparse solver. + * It provides the two following main factorization classes: + * - class PastixLLT : a supernodal, parallel LLt Cholesky factorization. + * - class PastixLDLT: a supernodal, parallel LDLt Cholesky factorization. + * - class PastixLU : a supernodal, parallel LU factorization (optimized for a symmetric pattern). + * + * \code + * #include + * \endcode + * + * In order to use this module, the PaSTiX headers must be accessible from the include paths, and your binary must be linked to the PaSTiX library and its dependencies. + * This wrapper resuires PaStiX version 5.x compiled without MPI support. + * The dependencies depend on how PaSTiX has been compiled. + * For a cmake based project, you can use our FindPaSTiX.cmake module to help you in this task. + * + */ + +#include "src/PaStiXSupport/PaStiXSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_PASTIXSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/PardisoSupport b/vendor/eigen/include/eigen3/Eigen/PardisoSupport new file mode 100644 index 0000000000000000000000000000000000000000..340edf51fe2d678294bef93f4cc413a95af0075d --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/PardisoSupport @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PARDISOSUPPORT_MODULE_H +#define EIGEN_PARDISOSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include + +/** \ingroup Support_modules + * \defgroup PardisoSupport_Module PardisoSupport module + * + * This module brings support for the Intel(R) MKL PARDISO direct sparse solvers. + * + * \code + * #include + * \endcode + * + * In order to use this module, the MKL headers must be accessible from the include paths, and your binary must be linked to the MKL library and its dependencies. + * See this \ref TopicUsingIntelMKL "page" for more information on MKL-Eigen integration. + * + */ + +#include "src/PardisoSupport/PardisoSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_PARDISOSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/QR b/vendor/eigen/include/eigen3/Eigen/QR new file mode 100644 index 0000000000000000000000000000000000000000..8465b62ceee1aadf915660451142fa2d800db550 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/QR @@ -0,0 +1,50 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_QR_MODULE_H +#define EIGEN_QR_MODULE_H + +#include "Core" + +#include "Cholesky" +#include "Jacobi" +#include "Householder" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup QR_Module QR module + * + * + * + * This module provides various QR decompositions + * This module also provides some MatrixBase methods, including: + * - MatrixBase::householderQr() + * - MatrixBase::colPivHouseholderQr() + * - MatrixBase::fullPivHouseholderQr() + * + * \code + * #include + * \endcode + */ + +#include "src/QR/HouseholderQR.h" +#include "src/QR/FullPivHouseholderQR.h" +#include "src/QR/ColPivHouseholderQR.h" +#include "src/QR/CompleteOrthogonalDecomposition.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/QR/HouseholderQR_LAPACKE.h" +#include "src/QR/ColPivHouseholderQR_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_QR_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/QtAlignedMalloc b/vendor/eigen/include/eigen3/Eigen/QtAlignedMalloc new file mode 100644 index 0000000000000000000000000000000000000000..6fe82374a5ebdb0dbc17fa6e0119b1a399f126e3 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/QtAlignedMalloc @@ -0,0 +1,39 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_QTMALLOC_MODULE_H +#define EIGEN_QTMALLOC_MODULE_H + +#include "Core" + +#if (!EIGEN_MALLOC_ALREADY_ALIGNED) + +#include "src/Core/util/DisableStupidWarnings.h" + +void *qMalloc(std::size_t size) +{ + return Eigen::internal::aligned_malloc(size); +} + +void qFree(void *ptr) +{ + Eigen::internal::aligned_free(ptr); +} + +void *qRealloc(void *ptr, std::size_t size) +{ + void* newPtr = Eigen::internal::aligned_malloc(size); + std::memcpy(newPtr, ptr, size); + Eigen::internal::aligned_free(ptr); + return newPtr; +} + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif + +#endif // EIGEN_QTMALLOC_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/SPQRSupport b/vendor/eigen/include/eigen3/Eigen/SPQRSupport new file mode 100644 index 0000000000000000000000000000000000000000..f70390c17661f10d87eafd69784af67368247dae --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SPQRSupport @@ -0,0 +1,34 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPQRSUPPORT_MODULE_H +#define EIGEN_SPQRSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "SuiteSparseQR.hpp" + +/** \ingroup Support_modules + * \defgroup SPQRSupport_Module SuiteSparseQR module + * + * This module provides an interface to the SPQR library, which is part of the suitesparse package. + * + * \code + * #include + * \endcode + * + * In order to use this module, the SPQR headers must be accessible from the include paths, and your binary must be linked to the SPQR library and its dependencies (Cholmod, AMD, COLAMD,...). + * For a cmake based project, you can use our FindSPQR.cmake and FindCholmod.Cmake modules + * + */ + +#include "src/CholmodSupport/CholmodSupport.h" +#include "src/SPQRSupport/SuiteSparseQRSupport.h" + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/SVD b/vendor/eigen/include/eigen3/Eigen/SVD new file mode 100644 index 0000000000000000000000000000000000000000..34517949632099aea944db49f84c4eb8f630ac5c --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SVD @@ -0,0 +1,50 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SVD_MODULE_H +#define EIGEN_SVD_MODULE_H + +#include "QR" +#include "Householder" +#include "Jacobi" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup SVD_Module SVD module + * + * + * + * This module provides SVD decomposition for matrices (both real and complex). + * Two decomposition algorithms are provided: + * - JacobiSVD implementing two-sided Jacobi iterations is numerically very accurate, fast for small matrices, but very slow for larger ones. + * - BDCSVD implementing a recursive divide & conquer strategy on top of an upper-bidiagonalization which remains fast for large problems. + * These decompositions are accessible via the respective classes and following MatrixBase methods: + * - MatrixBase::jacobiSvd() + * - MatrixBase::bdcSvd() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/RealSvd2x2.h" +#include "src/SVD/UpperBidiagonalization.h" +#include "src/SVD/SVDBase.h" +#include "src/SVD/JacobiSVD.h" +#include "src/SVD/BDCSVD.h" +#if defined(EIGEN_USE_LAPACKE) && !defined(EIGEN_USE_LAPACKE_STRICT) +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/SVD/JacobiSVD_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SVD_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/Sparse b/vendor/eigen/include/eigen3/Eigen/Sparse new file mode 100644 index 0000000000000000000000000000000000000000..a2ef7a66526812617c782f76dea260f04593ea58 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/Sparse @@ -0,0 +1,34 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_MODULE_H +#define EIGEN_SPARSE_MODULE_H + +/** \defgroup Sparse_Module Sparse meta-module + * + * Meta-module including all related modules: + * - \ref SparseCore_Module + * - \ref OrderingMethods_Module + * - \ref SparseCholesky_Module + * - \ref SparseLU_Module + * - \ref SparseQR_Module + * - \ref IterativeLinearSolvers_Module + * + \code + #include + \endcode + */ + +#include "SparseCore" +#include "OrderingMethods" +#include "SparseCholesky" +#include "SparseLU" +#include "SparseQR" +#include "IterativeLinearSolvers" + +#endif // EIGEN_SPARSE_MODULE_H + diff --git a/vendor/eigen/include/eigen3/Eigen/SparseCholesky b/vendor/eigen/include/eigen3/Eigen/SparseCholesky new file mode 100644 index 0000000000000000000000000000000000000000..d2b1f1276da5192664ba0ba39bbb9a00c18dc225 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SparseCholesky @@ -0,0 +1,37 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2013 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSECHOLESKY_MODULE_H +#define EIGEN_SPARSECHOLESKY_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup SparseCholesky_Module SparseCholesky module + * + * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) matrices. + * Those decompositions are accessible via the following classes: + * - SimplicialLLt, + * - SimplicialLDLt + * + * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module. + * + * \code + * #include + * \endcode + */ + +#include "src/SparseCholesky/SimplicialCholesky.h" +#include "src/SparseCholesky/SimplicialCholesky_impl.h" +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSECHOLESKY_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/SparseCore b/vendor/eigen/include/eigen3/Eigen/SparseCore new file mode 100644 index 0000000000000000000000000000000000000000..76966c4c4cb12da2ad59e0fdd7672b052baab6e3 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SparseCore @@ -0,0 +1,69 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSECORE_MODULE_H +#define EIGEN_SPARSECORE_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include +#include +#include +#include +#include + +/** + * \defgroup SparseCore_Module SparseCore module + * + * This module provides a sparse matrix representation, and basic associated matrix manipulations + * and operations. + * + * See the \ref TutorialSparse "Sparse tutorial" + * + * \code + * #include + * \endcode + * + * This module depends on: Core. + */ + +#include "src/SparseCore/SparseUtil.h" +#include "src/SparseCore/SparseMatrixBase.h" +#include "src/SparseCore/SparseAssign.h" +#include "src/SparseCore/CompressedStorage.h" +#include "src/SparseCore/AmbiVector.h" +#include "src/SparseCore/SparseCompressedBase.h" +#include "src/SparseCore/SparseMatrix.h" +#include "src/SparseCore/SparseMap.h" +#include "src/SparseCore/MappedSparseMatrix.h" +#include "src/SparseCore/SparseVector.h" +#include "src/SparseCore/SparseRef.h" +#include "src/SparseCore/SparseCwiseUnaryOp.h" +#include "src/SparseCore/SparseCwiseBinaryOp.h" +#include "src/SparseCore/SparseTranspose.h" +#include "src/SparseCore/SparseBlock.h" +#include "src/SparseCore/SparseDot.h" +#include "src/SparseCore/SparseRedux.h" +#include "src/SparseCore/SparseView.h" +#include "src/SparseCore/SparseDiagonalProduct.h" +#include "src/SparseCore/ConservativeSparseSparseProduct.h" +#include "src/SparseCore/SparseSparseProductWithPruning.h" +#include "src/SparseCore/SparseProduct.h" +#include "src/SparseCore/SparseDenseProduct.h" +#include "src/SparseCore/SparseSelfAdjointView.h" +#include "src/SparseCore/SparseTriangularView.h" +#include "src/SparseCore/TriangularSolver.h" +#include "src/SparseCore/SparsePermutation.h" +#include "src/SparseCore/SparseFuzzy.h" +#include "src/SparseCore/SparseSolverBase.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSECORE_MODULE_H + diff --git a/vendor/eigen/include/eigen3/Eigen/SparseLU b/vendor/eigen/include/eigen3/Eigen/SparseLU new file mode 100644 index 0000000000000000000000000000000000000000..37c4a5c5a8b305add93e2aae0eb7eac624f3ce68 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SparseLU @@ -0,0 +1,50 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSELU_MODULE_H +#define EIGEN_SPARSELU_MODULE_H + +#include "SparseCore" + +/** + * \defgroup SparseLU_Module SparseLU module + * This module defines a supernodal factorization of general sparse matrices. + * The code is fully optimized for supernode-panel updates with specialized kernels. + * Please, see the documentation of the SparseLU class for more details. + */ + +// Ordering interface +#include "OrderingMethods" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "src/SparseLU/SparseLU_gemm_kernel.h" + +#include "src/SparseLU/SparseLU_Structs.h" +#include "src/SparseLU/SparseLU_SupernodalMatrix.h" +#include "src/SparseLU/SparseLUImpl.h" +#include "src/SparseCore/SparseColEtree.h" +#include "src/SparseLU/SparseLU_Memory.h" +#include "src/SparseLU/SparseLU_heap_relax_snode.h" +#include "src/SparseLU/SparseLU_relax_snode.h" +#include "src/SparseLU/SparseLU_pivotL.h" +#include "src/SparseLU/SparseLU_panel_dfs.h" +#include "src/SparseLU/SparseLU_kernel_bmod.h" +#include "src/SparseLU/SparseLU_panel_bmod.h" +#include "src/SparseLU/SparseLU_column_dfs.h" +#include "src/SparseLU/SparseLU_column_bmod.h" +#include "src/SparseLU/SparseLU_copy_to_ucol.h" +#include "src/SparseLU/SparseLU_pruneL.h" +#include "src/SparseLU/SparseLU_Utils.h" +#include "src/SparseLU/SparseLU.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSELU_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/SparseQR b/vendor/eigen/include/eigen3/Eigen/SparseQR new file mode 100644 index 0000000000000000000000000000000000000000..f5fc5fa7feea7350788513081232d764ed32541b --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SparseQR @@ -0,0 +1,36 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEQR_MODULE_H +#define EIGEN_SPARSEQR_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup SparseQR_Module SparseQR module + * \brief Provides QR decomposition for sparse matrices + * + * This module provides a simplicial version of the left-looking Sparse QR decomposition. + * The columns of the input matrix should be reordered to limit the fill-in during the + * decomposition. Built-in methods (COLAMD, AMD) or external methods (METIS) can be used to this end. + * See the \link OrderingMethods_Module OrderingMethods\endlink module for the list + * of built-in and external ordering methods. + * + * \code + * #include + * \endcode + * + * + */ + +#include "src/SparseCore/SparseColEtree.h" +#include "src/SparseQR/SparseQR.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/StdDeque b/vendor/eigen/include/eigen3/Eigen/StdDeque new file mode 100644 index 0000000000000000000000000000000000000000..bc68397be259fa9666c2a59f4bdb1b9dd8ab0ce6 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/StdDeque @@ -0,0 +1,27 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDDEQUE_MODULE_H +#define EIGEN_STDDEQUE_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdDeque.h" + +#endif + +#endif // EIGEN_STDDEQUE_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/StdList b/vendor/eigen/include/eigen3/Eigen/StdList new file mode 100644 index 0000000000000000000000000000000000000000..4c6262c08cc26bcc70d4e21e83027b9533a7e36c --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/StdList @@ -0,0 +1,26 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDLIST_MODULE_H +#define EIGEN_STDLIST_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_LIST_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdList.h" + +#endif + +#endif // EIGEN_STDLIST_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/StdVector b/vendor/eigen/include/eigen3/Eigen/StdVector new file mode 100644 index 0000000000000000000000000000000000000000..0c4697ad5bed5868d793ba7d94bb9dc3fb9bed4c --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/StdVector @@ -0,0 +1,27 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDVECTOR_MODULE_H +#define EIGEN_STDVECTOR_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdVector.h" + +#endif + +#endif // EIGEN_STDVECTOR_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/SuperLUSupport b/vendor/eigen/include/eigen3/Eigen/SuperLUSupport new file mode 100644 index 0000000000000000000000000000000000000000..59312a82db0703389e21ae6e1b703b261802eadf --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/SuperLUSupport @@ -0,0 +1,64 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SUPERLUSUPPORT_MODULE_H +#define EIGEN_SUPERLUSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#ifdef EMPTY +#define EIGEN_EMPTY_WAS_ALREADY_DEFINED +#endif + +typedef int int_t; +#include +#include +#include + +// slu_util.h defines a preprocessor token named EMPTY which is really polluting, +// so we remove it in favor of a SUPERLU_EMPTY token. +// If EMPTY was already defined then we don't undef it. + +#if defined(EIGEN_EMPTY_WAS_ALREADY_DEFINED) +# undef EIGEN_EMPTY_WAS_ALREADY_DEFINED +#elif defined(EMPTY) +# undef EMPTY +#endif + +#define SUPERLU_EMPTY (-1) + +namespace Eigen { struct SluMatrix; } + +/** \ingroup Support_modules + * \defgroup SuperLUSupport_Module SuperLUSupport module + * + * This module provides an interface to the SuperLU library. + * It provides the following factorization class: + * - class SuperLU: a supernodal sequential LU factorization. + * - class SuperILU: a supernodal sequential incomplete LU factorization (to be used as a preconditioner for iterative methods). + * + * \warning This wrapper requires at least versions 4.0 of SuperLU. The 3.x versions are not supported. + * + * \warning When including this module, you have to use SUPERLU_EMPTY instead of EMPTY which is no longer defined because it is too polluting. + * + * \code + * #include + * \endcode + * + * In order to use this module, the superlu headers must be accessible from the include paths, and your binary must be linked to the superlu library and its dependencies. + * The dependencies depend on how superlu has been compiled. + * For a cmake based project, you can use our FindSuperLU.cmake module to help you in this task. + * + */ + +#include "src/SuperLUSupport/SuperLUSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SUPERLUSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/UmfPackSupport b/vendor/eigen/include/eigen3/Eigen/UmfPackSupport new file mode 100644 index 0000000000000000000000000000000000000000..00eec80875fcb209de0f6f746d0f4d299cd2ce8e --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/UmfPackSupport @@ -0,0 +1,40 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_UMFPACKSUPPORT_MODULE_H +#define EIGEN_UMFPACKSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +} + +/** \ingroup Support_modules + * \defgroup UmfPackSupport_Module UmfPackSupport module + * + * This module provides an interface to the UmfPack library which is part of the suitesparse package. + * It provides the following factorization class: + * - class UmfPackLU: a multifrontal sequential LU factorization. + * + * \code + * #include + * \endcode + * + * In order to use this module, the umfpack headers must be accessible from the include paths, and your binary must be linked to the umfpack library and its dependencies. + * The dependencies depend on how umfpack has been compiled. + * For a cmake based project, you can use our FindUmfPack.cmake module to help you in this task. + * + */ + +#include "src/UmfPackSupport/UmfPackSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_UMFPACKSUPPORT_MODULE_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h b/vendor/eigen/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..adaf52858e4ccf4ae5cd1f3c233257a0f1859e63 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h @@ -0,0 +1,682 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLMODSUPPORT_H +#define EIGEN_CHOLMODSUPPORT_H + +namespace Eigen { + +namespace internal { + +template struct cholmod_configure_matrix; + +template<> struct cholmod_configure_matrix { + template + static void run(CholmodType& mat) { + mat.xtype = CHOLMOD_REAL; + mat.dtype = CHOLMOD_DOUBLE; + } +}; + +template<> struct cholmod_configure_matrix > { + template + static void run(CholmodType& mat) { + mat.xtype = CHOLMOD_COMPLEX; + mat.dtype = CHOLMOD_DOUBLE; + } +}; + +// Other scalar types are not yet supported by Cholmod +// template<> struct cholmod_configure_matrix { +// template +// static void run(CholmodType& mat) { +// mat.xtype = CHOLMOD_REAL; +// mat.dtype = CHOLMOD_SINGLE; +// } +// }; +// +// template<> struct cholmod_configure_matrix > { +// template +// static void run(CholmodType& mat) { +// mat.xtype = CHOLMOD_COMPLEX; +// mat.dtype = CHOLMOD_SINGLE; +// } +// }; + +} // namespace internal + +/** Wraps the Eigen sparse matrix \a mat into a Cholmod sparse matrix object. + * Note that the data are shared. + */ +template +cholmod_sparse viewAsCholmod(Ref > mat) +{ + cholmod_sparse res; + res.nzmax = mat.nonZeros(); + res.nrow = mat.rows(); + res.ncol = mat.cols(); + res.p = mat.outerIndexPtr(); + res.i = mat.innerIndexPtr(); + res.x = mat.valuePtr(); + res.z = 0; + res.sorted = 1; + if(mat.isCompressed()) + { + res.packed = 1; + res.nz = 0; + } + else + { + res.packed = 0; + res.nz = mat.innerNonZeroPtr(); + } + + res.dtype = 0; + res.stype = -1; + + if (internal::is_same<_StorageIndex,int>::value) + { + res.itype = CHOLMOD_INT; + } + else if (internal::is_same<_StorageIndex,SuiteSparse_long>::value) + { + res.itype = CHOLMOD_LONG; + } + else + { + eigen_assert(false && "Index type not supported yet"); + } + + // setup res.xtype + internal::cholmod_configure_matrix<_Scalar>::run(res); + + res.stype = 0; + + return res; +} + +template +const cholmod_sparse viewAsCholmod(const SparseMatrix<_Scalar,_Options,_Index>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.const_cast_derived())); + return res; +} + +template +const cholmod_sparse viewAsCholmod(const SparseVector<_Scalar,_Options,_Index>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.const_cast_derived())); + return res; +} + +/** Returns a view of the Eigen sparse matrix \a mat as Cholmod sparse matrix. + * The data are not copied but shared. */ +template +cholmod_sparse viewAsCholmod(const SparseSelfAdjointView, UpLo>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.matrix().const_cast_derived())); + + if(UpLo==Upper) res.stype = 1; + if(UpLo==Lower) res.stype = -1; + // swap stype for rowmajor matrices (only works for real matrices) + EIGEN_STATIC_ASSERT((_Options & RowMajorBit) == 0 || NumTraits<_Scalar>::IsComplex == 0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + if(_Options & RowMajorBit) res.stype *=-1; + + return res; +} + +/** Returns a view of the Eigen \b dense matrix \a mat as Cholmod dense matrix. + * The data are not copied but shared. */ +template +cholmod_dense viewAsCholmod(MatrixBase& mat) +{ + EIGEN_STATIC_ASSERT((internal::traits::Flags&RowMajorBit)==0,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + typedef typename Derived::Scalar Scalar; + + cholmod_dense res; + res.nrow = mat.rows(); + res.ncol = mat.cols(); + res.nzmax = res.nrow * res.ncol; + res.d = Derived::IsVectorAtCompileTime ? mat.derived().size() : mat.derived().outerStride(); + res.x = (void*)(mat.derived().data()); + res.z = 0; + + internal::cholmod_configure_matrix::run(res); + + return res; +} + +/** Returns a view of the Cholmod sparse matrix \a cm as an Eigen sparse matrix. + * The data are not copied but shared. */ +template +MappedSparseMatrix viewAsEigen(cholmod_sparse& cm) +{ + return MappedSparseMatrix + (cm.nrow, cm.ncol, static_cast(cm.p)[cm.ncol], + static_cast(cm.p), static_cast(cm.i),static_cast(cm.x) ); +} + +namespace internal { + +// template specializations for int and long that call the correct cholmod method + +#define EIGEN_CHOLMOD_SPECIALIZE0(ret, name) \ + template inline ret cm_ ## name (cholmod_common &Common) { return cholmod_ ## name (&Common); } \ + template<> inline ret cm_ ## name (cholmod_common &Common) { return cholmod_l_ ## name (&Common); } + +#define EIGEN_CHOLMOD_SPECIALIZE1(ret, name, t1, a1) \ + template inline ret cm_ ## name (t1& a1, cholmod_common &Common) { return cholmod_ ## name (&a1, &Common); } \ + template<> inline ret cm_ ## name (t1& a1, cholmod_common &Common) { return cholmod_l_ ## name (&a1, &Common); } + +EIGEN_CHOLMOD_SPECIALIZE0(int, start) +EIGEN_CHOLMOD_SPECIALIZE0(int, finish) + +EIGEN_CHOLMOD_SPECIALIZE1(int, free_factor, cholmod_factor*, L) +EIGEN_CHOLMOD_SPECIALIZE1(int, free_dense, cholmod_dense*, X) +EIGEN_CHOLMOD_SPECIALIZE1(int, free_sparse, cholmod_sparse*, A) + +EIGEN_CHOLMOD_SPECIALIZE1(cholmod_factor*, analyze, cholmod_sparse, A) + +template inline cholmod_dense* cm_solve (int sys, cholmod_factor& L, cholmod_dense& B, cholmod_common &Common) { return cholmod_solve (sys, &L, &B, &Common); } +template<> inline cholmod_dense* cm_solve (int sys, cholmod_factor& L, cholmod_dense& B, cholmod_common &Common) { return cholmod_l_solve (sys, &L, &B, &Common); } + +template inline cholmod_sparse* cm_spsolve (int sys, cholmod_factor& L, cholmod_sparse& B, cholmod_common &Common) { return cholmod_spsolve (sys, &L, &B, &Common); } +template<> inline cholmod_sparse* cm_spsolve (int sys, cholmod_factor& L, cholmod_sparse& B, cholmod_common &Common) { return cholmod_l_spsolve (sys, &L, &B, &Common); } + +template +inline int cm_factorize_p (cholmod_sparse* A, double beta[2], _StorageIndex* fset, std::size_t fsize, cholmod_factor* L, cholmod_common &Common) { return cholmod_factorize_p (A, beta, fset, fsize, L, &Common); } +template<> +inline int cm_factorize_p (cholmod_sparse* A, double beta[2], SuiteSparse_long* fset, std::size_t fsize, cholmod_factor* L, cholmod_common &Common) { return cholmod_l_factorize_p (A, beta, fset, fsize, L, &Common); } + +#undef EIGEN_CHOLMOD_SPECIALIZE0 +#undef EIGEN_CHOLMOD_SPECIALIZE1 + +} // namespace internal + + +enum CholmodMode { + CholmodAuto, CholmodSimplicialLLt, CholmodSupernodalLLt, CholmodLDLt +}; + + +/** \ingroup CholmodSupport_Module + * \class CholmodBase + * \brief The base class for the direct Cholesky factorization of Cholmod + * \sa class CholmodSupernodalLLT, class CholmodSimplicialLDLT, class CholmodSimplicialLLT + */ +template +class CholmodBase : public SparseSolverBase +{ + protected: + typedef SparseSolverBase Base; + using Base::derived; + using Base::m_isInitialized; + public: + typedef _MatrixType MatrixType; + enum { UpLo = _UpLo }; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef MatrixType CholMatrixType; + typedef typename MatrixType::StorageIndex StorageIndex; + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + CholmodBase() + : m_cholmodFactor(0), m_info(Success), m_factorizationIsOk(false), m_analysisIsOk(false) + { + EIGEN_STATIC_ASSERT((internal::is_same::value), CHOLMOD_SUPPORTS_DOUBLE_PRECISION_ONLY); + m_shiftOffset[0] = m_shiftOffset[1] = 0.0; + internal::cm_start(m_cholmod); + } + + explicit CholmodBase(const MatrixType& matrix) + : m_cholmodFactor(0), m_info(Success), m_factorizationIsOk(false), m_analysisIsOk(false) + { + EIGEN_STATIC_ASSERT((internal::is_same::value), CHOLMOD_SUPPORTS_DOUBLE_PRECISION_ONLY); + m_shiftOffset[0] = m_shiftOffset[1] = 0.0; + internal::cm_start(m_cholmod); + compute(matrix); + } + + ~CholmodBase() + { + if(m_cholmodFactor) + internal::cm_free_factor(m_cholmodFactor, m_cholmod); + internal::cm_finish(m_cholmod); + } + + inline StorageIndex cols() const { return internal::convert_index(m_cholmodFactor->n); } + inline StorageIndex rows() const { return internal::convert_index(m_cholmodFactor->n); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + /** Computes the sparse Cholesky decomposition of \a matrix */ + Derived& compute(const MatrixType& matrix) + { + analyzePattern(matrix); + factorize(matrix); + return derived(); + } + + /** Performs a symbolic decomposition on the sparsity pattern of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + void analyzePattern(const MatrixType& matrix) + { + if(m_cholmodFactor) + { + internal::cm_free_factor(m_cholmodFactor, m_cholmod); + m_cholmodFactor = 0; + } + cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView()); + m_cholmodFactor = internal::cm_analyze(A, m_cholmod); + + this->m_isInitialized = true; + this->m_info = Success; + m_analysisIsOk = true; + m_factorizationIsOk = false; + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must have the same sparsity pattern as the matrix on which the symbolic decomposition has been performed. + * + * \sa analyzePattern() + */ + void factorize(const MatrixType& matrix) + { + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView()); + internal::cm_factorize_p(&A, m_shiftOffset, 0, 0, m_cholmodFactor, m_cholmod); + + // If the factorization failed, minor is the column at which it did. On success minor == n. + this->m_info = (m_cholmodFactor->minor == m_cholmodFactor->n ? Success : NumericalIssue); + m_factorizationIsOk = true; + } + + /** Returns a reference to the Cholmod's configuration structure to get a full control over the performed operations. + * See the Cholmod user guide for details. */ + cholmod_common& cholmod() { return m_cholmod; } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal */ + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const + { + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + const Index size = m_cholmodFactor->n; + EIGEN_UNUSED_VARIABLE(size); + eigen_assert(size==b.rows()); + + // Cholmod needs column-major storage without inner-stride, which corresponds to the default behavior of Ref. + Ref > b_ref(b.derived()); + + cholmod_dense b_cd = viewAsCholmod(b_ref); + cholmod_dense* x_cd = internal::cm_solve(CHOLMOD_A, *m_cholmodFactor, b_cd, m_cholmod); + if(!x_cd) + { + this->m_info = NumericalIssue; + return; + } + // TODO optimize this copy by swapping when possible (be careful with alignment, etc.) + // NOTE Actually, the copy can be avoided by calling cholmod_solve2 instead of cholmod_solve + dest = Matrix::Map(reinterpret_cast(x_cd->x),b.rows(),b.cols()); + internal::cm_free_dense(x_cd, m_cholmod); + } + + /** \internal */ + template + void _solve_impl(const SparseMatrixBase &b, SparseMatrixBase &dest) const + { + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + const Index size = m_cholmodFactor->n; + EIGEN_UNUSED_VARIABLE(size); + eigen_assert(size==b.rows()); + + // note: cs stands for Cholmod Sparse + Ref > b_ref(b.const_cast_derived()); + cholmod_sparse b_cs = viewAsCholmod(b_ref); + cholmod_sparse* x_cs = internal::cm_spsolve(CHOLMOD_A, *m_cholmodFactor, b_cs, m_cholmod); + if(!x_cs) + { + this->m_info = NumericalIssue; + return; + } + // TODO optimize this copy by swapping when possible (be careful with alignment, etc.) + // NOTE cholmod_spsolve in fact just calls the dense solver for blocks of 4 columns at a time (similar to Eigen's sparse solver) + dest.derived() = viewAsEigen(*x_cs); + internal::cm_free_sparse(x_cs, m_cholmod); + } + #endif // EIGEN_PARSED_BY_DOXYGEN + + + /** Sets the shift parameter that will be used to adjust the diagonal coefficients during the numerical factorization. + * + * During the numerical factorization, an offset term is added to the diagonal coefficients:\n + * \c d_ii = \a offset + \c d_ii + * + * The default is \a offset=0. + * + * \returns a reference to \c *this. + */ + Derived& setShift(const RealScalar& offset) + { + m_shiftOffset[0] = double(offset); + return derived(); + } + + /** \returns the determinant of the underlying matrix from the current factorization */ + Scalar determinant() const + { + using std::exp; + return exp(logDeterminant()); + } + + /** \returns the log determinant of the underlying matrix from the current factorization */ + Scalar logDeterminant() const + { + using std::log; + using numext::real; + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + + RealScalar logDet = 0; + Scalar *x = static_cast(m_cholmodFactor->x); + if (m_cholmodFactor->is_super) + { + // Supernodal factorization stored as a packed list of dense column-major blocs, + // as described by the following structure: + + // super[k] == index of the first column of the j-th super node + StorageIndex *super = static_cast(m_cholmodFactor->super); + // pi[k] == offset to the description of row indices + StorageIndex *pi = static_cast(m_cholmodFactor->pi); + // px[k] == offset to the respective dense block + StorageIndex *px = static_cast(m_cholmodFactor->px); + + Index nb_super_nodes = m_cholmodFactor->nsuper; + for (Index k=0; k < nb_super_nodes; ++k) + { + StorageIndex ncols = super[k + 1] - super[k]; + StorageIndex nrows = pi[k + 1] - pi[k]; + + Map, 0, InnerStride<> > sk(x + px[k], ncols, InnerStride<>(nrows+1)); + logDet += sk.real().log().sum(); + } + } + else + { + // Simplicial factorization stored as standard CSC matrix. + StorageIndex *p = static_cast(m_cholmodFactor->p); + Index size = m_cholmodFactor->n; + for (Index k=0; kis_ll) + logDet *= 2.0; + return logDet; + }; + + template + void dumpMemory(Stream& /*s*/) + {} + + protected: + mutable cholmod_common m_cholmod; + cholmod_factor* m_cholmodFactor; + double m_shiftOffset[2]; + mutable ComputationInfo m_info; + int m_factorizationIsOk; + int m_analysisIsOk; +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodSimplicialLLT + * \brief A simplicial direct Cholesky (LLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a simplicial LL^T Cholesky factorization + * using the Cholmod library. + * This simplicial variant is equivalent to Eigen's built-in SimplicialLLT class. Therefore, it has little practical interest. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept, class CholmodSupernodalLLT, class SimplicialLLT + */ +template +class CholmodSimplicialLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSimplicialLLT() : Base() { init(); } + + CholmodSimplicialLLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSimplicialLLT() {} + protected: + void init() + { + m_cholmod.final_asis = 0; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + m_cholmod.final_ll = 1; + } +}; + + +/** \ingroup CholmodSupport_Module + * \class CholmodSimplicialLDLT + * \brief A simplicial direct Cholesky (LDLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a simplicial LDL^T Cholesky factorization + * using the Cholmod library. + * This simplicial variant is equivalent to Eigen's built-in SimplicialLDLT class. Therefore, it has little practical interest. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept, class CholmodSupernodalLLT, class SimplicialLDLT + */ +template +class CholmodSimplicialLDLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSimplicialLDLT() : Base() { init(); } + + CholmodSimplicialLDLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSimplicialLDLT() {} + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + } +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodSupernodalLLT + * \brief A supernodal Cholesky (LLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a supernodal LL^T Cholesky factorization + * using the Cholmod library. + * This supernodal variant performs best on dense enough problems, e.g., 3D FEM, or very high order 2D FEM. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept + */ +template +class CholmodSupernodalLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSupernodalLLT() : Base() { init(); } + + CholmodSupernodalLLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSupernodalLLT() {} + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SUPERNODAL; + } +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodDecomposition + * \brief A general Cholesky factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a LL^T or LDL^T Cholesky factorization + * using the Cholmod library. The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * This variant permits to change the underlying Cholesky method at runtime. + * On the other hand, it does not provide access to the result of the factorization. + * The default is to let Cholmod automatically choose between a simplicial and supernodal factorization. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept + */ +template +class CholmodDecomposition : public CholmodBase<_MatrixType, _UpLo, CholmodDecomposition<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodDecomposition> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodDecomposition() : Base() { init(); } + + CholmodDecomposition(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodDecomposition() {} + + void setMode(CholmodMode mode) + { + switch(mode) + { + case CholmodAuto: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_AUTO; + break; + case CholmodSimplicialLLt: + m_cholmod.final_asis = 0; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + m_cholmod.final_ll = 1; + break; + case CholmodSupernodalLLt: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SUPERNODAL; + break; + case CholmodLDLt: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + break; + default: + break; + } + } + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_AUTO; + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CHOLMODSUPPORT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/Householder/BlockHouseholder.h b/vendor/eigen/include/eigen3/Eigen/src/Householder/BlockHouseholder.h new file mode 100644 index 0000000000000000000000000000000000000000..39ce1c2a0efa24f1a86866dd699c4a7216728f47 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/Householder/BlockHouseholder.h @@ -0,0 +1,110 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Vincent Lejeune +// Copyright (C) 2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BLOCK_HOUSEHOLDER_H +#define EIGEN_BLOCK_HOUSEHOLDER_H + +// This file contains some helper function to deal with block householder reflectors + +namespace Eigen { + +namespace internal { + +/** \internal */ +// template +// void make_block_householder_triangular_factor(TriangularFactorType& triFactor, const VectorsType& vectors, const CoeffsType& hCoeffs) +// { +// typedef typename VectorsType::Scalar Scalar; +// const Index nbVecs = vectors.cols(); +// eigen_assert(triFactor.rows() == nbVecs && triFactor.cols() == nbVecs && vectors.rows()>=nbVecs); +// +// for(Index i = 0; i < nbVecs; i++) +// { +// Index rs = vectors.rows() - i; +// // Warning, note that hCoeffs may alias with vectors. +// // It is then necessary to copy it before modifying vectors(i,i). +// typename CoeffsType::Scalar h = hCoeffs(i); +// // This hack permits to pass trough nested Block<> and Transpose<> expressions. +// Scalar *Vii_ptr = const_cast(vectors.data() + vectors.outerStride()*i + vectors.innerStride()*i); +// Scalar Vii = *Vii_ptr; +// *Vii_ptr = Scalar(1); +// triFactor.col(i).head(i).noalias() = -h * vectors.block(i, 0, rs, i).adjoint() +// * vectors.col(i).tail(rs); +// *Vii_ptr = Vii; +// // FIXME add .noalias() once the triangular product can work inplace +// triFactor.col(i).head(i) = triFactor.block(0,0,i,i).template triangularView() +// * triFactor.col(i).head(i); +// triFactor(i,i) = hCoeffs(i); +// } +// } + +/** \internal */ +// This variant avoid modifications in vectors +template +void make_block_householder_triangular_factor(TriangularFactorType& triFactor, const VectorsType& vectors, const CoeffsType& hCoeffs) +{ + const Index nbVecs = vectors.cols(); + eigen_assert(triFactor.rows() == nbVecs && triFactor.cols() == nbVecs && vectors.rows()>=nbVecs); + + for(Index i = nbVecs-1; i >=0 ; --i) + { + Index rs = vectors.rows() - i - 1; + Index rt = nbVecs-i-1; + + if(rt>0) + { + triFactor.row(i).tail(rt).noalias() = -hCoeffs(i) * vectors.col(i).tail(rs).adjoint() + * vectors.bottomRightCorner(rs, rt).template triangularView(); + + // FIXME use the following line with .noalias() once the triangular product can work inplace + // triFactor.row(i).tail(rt) = triFactor.row(i).tail(rt) * triFactor.bottomRightCorner(rt,rt).template triangularView(); + for(Index j=nbVecs-1; j>i; --j) + { + typename TriangularFactorType::Scalar z = triFactor(i,j); + triFactor(i,j) = z * triFactor(j,j); + if(nbVecs-j-1>0) + triFactor.row(i).tail(nbVecs-j-1) += z * triFactor.row(j).tail(nbVecs-j-1); + } + + } + triFactor(i,i) = hCoeffs(i); + } +} + +/** \internal + * if forward then perform mat = H0 * H1 * H2 * mat + * otherwise perform mat = H2 * H1 * H0 * mat + */ +template +void apply_block_householder_on_the_left(MatrixType& mat, const VectorsType& vectors, const CoeffsType& hCoeffs, bool forward) +{ + enum { TFactorSize = MatrixType::ColsAtCompileTime }; + Index nbVecs = vectors.cols(); + Matrix T(nbVecs,nbVecs); + + if(forward) make_block_householder_triangular_factor(T, vectors, hCoeffs); + else make_block_householder_triangular_factor(T, vectors, hCoeffs.conjugate()); + const TriangularView V(vectors); + + // A -= V T V^* A + Matrix tmp = V.adjoint() * mat; + // FIXME add .noalias() once the triangular product can work inplace + if(forward) tmp = T.template triangularView() * tmp; + else tmp = T.template triangularView().adjoint() * tmp; + mat.noalias() -= V * tmp; +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_BLOCK_HOUSEHOLDER_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/Householder/Householder.h b/vendor/eigen/include/eigen3/Eigen/src/Householder/Householder.h new file mode 100644 index 0000000000000000000000000000000000000000..5bc037f00d18c992606fed9fef11f989fec373d5 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/Householder/Householder.h @@ -0,0 +1,176 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Benoit Jacob +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_HOUSEHOLDER_H +#define EIGEN_HOUSEHOLDER_H + +namespace Eigen { + +namespace internal { +template struct decrement_size +{ + enum { + ret = n==Dynamic ? n : n-1 + }; +}; +} + +/** Computes the elementary reflector H such that: + * \f$ H *this = [ beta 0 ... 0]^T \f$ + * where the transformation H is: + * \f$ H = I - tau v v^*\f$ + * and the vector v is: + * \f$ v^T = [1 essential^T] \f$ + * + * The essential part of the vector \c v is stored in *this. + * + * On output: + * \param tau the scaling factor of the Householder transformation + * \param beta the result of H * \c *this + * + * \sa MatrixBase::makeHouseholder(), MatrixBase::applyHouseholderOnTheLeft(), + * MatrixBase::applyHouseholderOnTheRight() + */ +template +EIGEN_DEVICE_FUNC +void MatrixBase::makeHouseholderInPlace(Scalar& tau, RealScalar& beta) +{ + VectorBlock::ret> essentialPart(derived(), 1, size()-1); + makeHouseholder(essentialPart, tau, beta); +} + +/** Computes the elementary reflector H such that: + * \f$ H *this = [ beta 0 ... 0]^T \f$ + * where the transformation H is: + * \f$ H = I - tau v v^*\f$ + * and the vector v is: + * \f$ v^T = [1 essential^T] \f$ + * + * On output: + * \param essential the essential part of the vector \c v + * \param tau the scaling factor of the Householder transformation + * \param beta the result of H * \c *this + * + * \sa MatrixBase::makeHouseholderInPlace(), MatrixBase::applyHouseholderOnTheLeft(), + * MatrixBase::applyHouseholderOnTheRight() + */ +template +template +EIGEN_DEVICE_FUNC +void MatrixBase::makeHouseholder( + EssentialPart& essential, + Scalar& tau, + RealScalar& beta) const +{ + using std::sqrt; + using numext::conj; + + EIGEN_STATIC_ASSERT_VECTOR_ONLY(EssentialPart) + VectorBlock tail(derived(), 1, size()-1); + + RealScalar tailSqNorm = size()==1 ? RealScalar(0) : tail.squaredNorm(); + Scalar c0 = coeff(0); + const RealScalar tol = (std::numeric_limits::min)(); + + if(tailSqNorm <= tol && numext::abs2(numext::imag(c0))<=tol) + { + tau = RealScalar(0); + beta = numext::real(c0); + essential.setZero(); + } + else + { + beta = sqrt(numext::abs2(c0) + tailSqNorm); + if (numext::real(c0)>=RealScalar(0)) + beta = -beta; + essential = tail / (c0 - beta); + tau = conj((beta - c0) / beta); + } +} + +/** Apply the elementary reflector H given by + * \f$ H = I - tau v v^*\f$ + * with + * \f$ v^T = [1 essential^T] \f$ + * from the left to a vector or matrix. + * + * On input: + * \param essential the essential part of the vector \c v + * \param tau the scaling factor of the Householder transformation + * \param workspace a pointer to working space with at least + * this->cols() entries + * + * \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(), + * MatrixBase::applyHouseholderOnTheRight() + */ +template +template +EIGEN_DEVICE_FUNC +void MatrixBase::applyHouseholderOnTheLeft( + const EssentialPart& essential, + const Scalar& tau, + Scalar* workspace) +{ + if(rows() == 1) + { + *this *= Scalar(1)-tau; + } + else if(tau!=Scalar(0)) + { + Map::type> tmp(workspace,cols()); + Block bottom(derived(), 1, 0, rows()-1, cols()); + tmp.noalias() = essential.adjoint() * bottom; + tmp += this->row(0); + this->row(0) -= tau * tmp; + bottom.noalias() -= tau * essential * tmp; + } +} + +/** Apply the elementary reflector H given by + * \f$ H = I - tau v v^*\f$ + * with + * \f$ v^T = [1 essential^T] \f$ + * from the right to a vector or matrix. + * + * On input: + * \param essential the essential part of the vector \c v + * \param tau the scaling factor of the Householder transformation + * \param workspace a pointer to working space with at least + * this->rows() entries + * + * \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(), + * MatrixBase::applyHouseholderOnTheLeft() + */ +template +template +EIGEN_DEVICE_FUNC +void MatrixBase::applyHouseholderOnTheRight( + const EssentialPart& essential, + const Scalar& tau, + Scalar* workspace) +{ + if(cols() == 1) + { + *this *= Scalar(1)-tau; + } + else if(tau!=Scalar(0)) + { + Map::type> tmp(workspace,rows()); + Block right(derived(), 0, 1, rows(), cols()-1); + tmp.noalias() = right * essential; + tmp += this->col(0); + this->col(0) -= tau * tmp; + right.noalias() -= tau * tmp * essential.adjoint(); + } +} + +} // end namespace Eigen + +#endif // EIGEN_HOUSEHOLDER_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/Householder/HouseholderSequence.h b/vendor/eigen/include/eigen3/Eigen/src/Householder/HouseholderSequence.h new file mode 100644 index 0000000000000000000000000000000000000000..022f6c3dba8e45e97f68753809eef1708daf5537 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/Householder/HouseholderSequence.h @@ -0,0 +1,545 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_HOUSEHOLDER_SEQUENCE_H +#define EIGEN_HOUSEHOLDER_SEQUENCE_H + +namespace Eigen { + +/** \ingroup Householder_Module + * \householder_module + * \class HouseholderSequence + * \brief Sequence of Householder reflections acting on subspaces with decreasing size + * \tparam VectorsType type of matrix containing the Householder vectors + * \tparam CoeffsType type of vector containing the Householder coefficients + * \tparam Side either OnTheLeft (the default) or OnTheRight + * + * This class represents a product sequence of Householder reflections where the first Householder reflection + * acts on the whole space, the second Householder reflection leaves the one-dimensional subspace spanned by + * the first unit vector invariant, the third Householder reflection leaves the two-dimensional subspace + * spanned by the first two unit vectors invariant, and so on up to the last reflection which leaves all but + * one dimensions invariant and acts only on the last dimension. Such sequences of Householder reflections + * are used in several algorithms to zero out certain parts of a matrix. Indeed, the methods + * HessenbergDecomposition::matrixQ(), Tridiagonalization::matrixQ(), HouseholderQR::householderQ(), + * and ColPivHouseholderQR::householderQ() all return a %HouseholderSequence. + * + * More precisely, the class %HouseholderSequence represents an \f$ n \times n \f$ matrix \f$ H \f$ of the + * form \f$ H = \prod_{i=0}^{n-1} H_i \f$ where the i-th Householder reflection is \f$ H_i = I - h_i v_i + * v_i^* \f$. The i-th Householder coefficient \f$ h_i \f$ is a scalar and the i-th Householder vector \f$ + * v_i \f$ is a vector of the form + * \f[ + * v_i = [\underbrace{0, \ldots, 0}_{i-1\mbox{ zeros}}, 1, \underbrace{*, \ldots,*}_{n-i\mbox{ arbitrary entries}} ]. + * \f] + * The last \f$ n-i \f$ entries of \f$ v_i \f$ are called the essential part of the Householder vector. + * + * Typical usages are listed below, where H is a HouseholderSequence: + * \code + * A.applyOnTheRight(H); // A = A * H + * A.applyOnTheLeft(H); // A = H * A + * A.applyOnTheRight(H.adjoint()); // A = A * H^* + * A.applyOnTheLeft(H.adjoint()); // A = H^* * A + * MatrixXd Q = H; // conversion to a dense matrix + * \endcode + * In addition to the adjoint, you can also apply the inverse (=adjoint), the transpose, and the conjugate operators. + * + * See the documentation for HouseholderSequence(const VectorsType&, const CoeffsType&) for an example. + * + * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight() + */ + +namespace internal { + +template +struct traits > +{ + typedef typename VectorsType::Scalar Scalar; + typedef typename VectorsType::StorageIndex StorageIndex; + typedef typename VectorsType::StorageKind StorageKind; + enum { + RowsAtCompileTime = Side==OnTheLeft ? traits::RowsAtCompileTime + : traits::ColsAtCompileTime, + ColsAtCompileTime = RowsAtCompileTime, + MaxRowsAtCompileTime = Side==OnTheLeft ? traits::MaxRowsAtCompileTime + : traits::MaxColsAtCompileTime, + MaxColsAtCompileTime = MaxRowsAtCompileTime, + Flags = 0 + }; +}; + +struct HouseholderSequenceShape {}; + +template +struct evaluator_traits > + : public evaluator_traits_base > +{ + typedef HouseholderSequenceShape Shape; +}; + +template +struct hseq_side_dependent_impl +{ + typedef Block EssentialVectorType; + typedef HouseholderSequence HouseholderSequenceType; + static EIGEN_DEVICE_FUNC inline const EssentialVectorType essentialVector(const HouseholderSequenceType& h, Index k) + { + Index start = k+1+h.m_shift; + return Block(h.m_vectors, start, k, h.rows()-start, 1); + } +}; + +template +struct hseq_side_dependent_impl +{ + typedef Transpose > EssentialVectorType; + typedef HouseholderSequence HouseholderSequenceType; + static inline const EssentialVectorType essentialVector(const HouseholderSequenceType& h, Index k) + { + Index start = k+1+h.m_shift; + return Block(h.m_vectors, k, start, 1, h.rows()-start).transpose(); + } +}; + +template struct matrix_type_times_scalar_type +{ + typedef typename ScalarBinaryOpTraits::ReturnType + ResultScalar; + typedef Matrix Type; +}; + +} // end namespace internal + +template class HouseholderSequence + : public EigenBase > +{ + typedef typename internal::hseq_side_dependent_impl::EssentialVectorType EssentialVectorType; + + public: + enum { + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime + }; + typedef typename internal::traits::Scalar Scalar; + + typedef HouseholderSequence< + typename internal::conditional::IsComplex, + typename internal::remove_all::type, + VectorsType>::type, + typename internal::conditional::IsComplex, + typename internal::remove_all::type, + CoeffsType>::type, + Side + > ConjugateReturnType; + + typedef HouseholderSequence< + VectorsType, + typename internal::conditional::IsComplex, + typename internal::remove_all::type, + CoeffsType>::type, + Side + > AdjointReturnType; + + typedef HouseholderSequence< + typename internal::conditional::IsComplex, + typename internal::remove_all::type, + VectorsType>::type, + CoeffsType, + Side + > TransposeReturnType; + + typedef HouseholderSequence< + typename internal::add_const::type, + typename internal::add_const::type, + Side + > ConstHouseholderSequence; + + /** \brief Constructor. + * \param[in] v %Matrix containing the essential parts of the Householder vectors + * \param[in] h Vector containing the Householder coefficients + * + * Constructs the Householder sequence with coefficients given by \p h and vectors given by \p v. The + * i-th Householder coefficient \f$ h_i \f$ is given by \p h(i) and the essential part of the i-th + * Householder vector \f$ v_i \f$ is given by \p v(k,i) with \p k > \p i (the subdiagonal part of the + * i-th column). If \p v has fewer columns than rows, then the Householder sequence contains as many + * Householder reflections as there are columns. + * + * \note The %HouseholderSequence object stores \p v and \p h by reference. + * + * Example: \include HouseholderSequence_HouseholderSequence.cpp + * Output: \verbinclude HouseholderSequence_HouseholderSequence.out + * + * \sa setLength(), setShift() + */ + EIGEN_DEVICE_FUNC + HouseholderSequence(const VectorsType& v, const CoeffsType& h) + : m_vectors(v), m_coeffs(h), m_reverse(false), m_length(v.diagonalSize()), + m_shift(0) + { + } + + /** \brief Copy constructor. */ + EIGEN_DEVICE_FUNC + HouseholderSequence(const HouseholderSequence& other) + : m_vectors(other.m_vectors), + m_coeffs(other.m_coeffs), + m_reverse(other.m_reverse), + m_length(other.m_length), + m_shift(other.m_shift) + { + } + + /** \brief Number of rows of transformation viewed as a matrix. + * \returns Number of rows + * \details This equals the dimension of the space that the transformation acts on. + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR + Index rows() const EIGEN_NOEXCEPT { return Side==OnTheLeft ? m_vectors.rows() : m_vectors.cols(); } + + /** \brief Number of columns of transformation viewed as a matrix. + * \returns Number of columns + * \details This equals the dimension of the space that the transformation acts on. + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR + Index cols() const EIGEN_NOEXCEPT { return rows(); } + + /** \brief Essential part of a Householder vector. + * \param[in] k Index of Householder reflection + * \returns Vector containing non-trivial entries of k-th Householder vector + * + * This function returns the essential part of the Householder vector \f$ v_i \f$. This is a vector of + * length \f$ n-i \f$ containing the last \f$ n-i \f$ entries of the vector + * \f[ + * v_i = [\underbrace{0, \ldots, 0}_{i-1\mbox{ zeros}}, 1, \underbrace{*, \ldots,*}_{n-i\mbox{ arbitrary entries}} ]. + * \f] + * The index \f$ i \f$ equals \p k + shift(), corresponding to the k-th column of the matrix \p v + * passed to the constructor. + * + * \sa setShift(), shift() + */ + EIGEN_DEVICE_FUNC + const EssentialVectorType essentialVector(Index k) const + { + eigen_assert(k >= 0 && k < m_length); + return internal::hseq_side_dependent_impl::essentialVector(*this, k); + } + + /** \brief %Transpose of the Householder sequence. */ + TransposeReturnType transpose() const + { + return TransposeReturnType(m_vectors.conjugate(), m_coeffs) + .setReverseFlag(!m_reverse) + .setLength(m_length) + .setShift(m_shift); + } + + /** \brief Complex conjugate of the Householder sequence. */ + ConjugateReturnType conjugate() const + { + return ConjugateReturnType(m_vectors.conjugate(), m_coeffs.conjugate()) + .setReverseFlag(m_reverse) + .setLength(m_length) + .setShift(m_shift); + } + + /** \returns an expression of the complex conjugate of \c *this if Cond==true, + * returns \c *this otherwise. + */ + template + EIGEN_DEVICE_FUNC + inline typename internal::conditional::type + conjugateIf() const + { + typedef typename internal::conditional::type ReturnType; + return ReturnType(m_vectors.template conjugateIf(), m_coeffs.template conjugateIf()); + } + + /** \brief Adjoint (conjugate transpose) of the Householder sequence. */ + AdjointReturnType adjoint() const + { + return AdjointReturnType(m_vectors, m_coeffs.conjugate()) + .setReverseFlag(!m_reverse) + .setLength(m_length) + .setShift(m_shift); + } + + /** \brief Inverse of the Householder sequence (equals the adjoint). */ + AdjointReturnType inverse() const { return adjoint(); } + + /** \internal */ + template + inline EIGEN_DEVICE_FUNC + void evalTo(DestType& dst) const + { + Matrix workspace(rows()); + evalTo(dst, workspace); + } + + /** \internal */ + template + EIGEN_DEVICE_FUNC + void evalTo(Dest& dst, Workspace& workspace) const + { + workspace.resize(rows()); + Index vecs = m_length; + if(internal::is_same_dense(dst,m_vectors)) + { + // in-place + dst.diagonal().setOnes(); + dst.template triangularView().setZero(); + for(Index k = vecs-1; k >= 0; --k) + { + Index cornerSize = rows() - k - m_shift; + if(m_reverse) + dst.bottomRightCorner(cornerSize, cornerSize) + .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), workspace.data()); + else + dst.bottomRightCorner(cornerSize, cornerSize) + .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), workspace.data()); + + // clear the off diagonal vector + dst.col(k).tail(rows()-k-1).setZero(); + } + // clear the remaining columns if needed + for(Index k = 0; kBlockSize) + { + dst.setIdentity(rows(), rows()); + if(m_reverse) + applyThisOnTheLeft(dst,workspace,true); + else + applyThisOnTheLeft(dst,workspace,true); + } + else + { + dst.setIdentity(rows(), rows()); + for(Index k = vecs-1; k >= 0; --k) + { + Index cornerSize = rows() - k - m_shift; + if(m_reverse) + dst.bottomRightCorner(cornerSize, cornerSize) + .applyHouseholderOnTheRight(essentialVector(k), m_coeffs.coeff(k), workspace.data()); + else + dst.bottomRightCorner(cornerSize, cornerSize) + .applyHouseholderOnTheLeft(essentialVector(k), m_coeffs.coeff(k), workspace.data()); + } + } + } + + /** \internal */ + template inline void applyThisOnTheRight(Dest& dst) const + { + Matrix workspace(dst.rows()); + applyThisOnTheRight(dst, workspace); + } + + /** \internal */ + template + inline void applyThisOnTheRight(Dest& dst, Workspace& workspace) const + { + workspace.resize(dst.rows()); + for(Index k = 0; k < m_length; ++k) + { + Index actual_k = m_reverse ? m_length-k-1 : k; + dst.rightCols(rows()-m_shift-actual_k) + .applyHouseholderOnTheRight(essentialVector(actual_k), m_coeffs.coeff(actual_k), workspace.data()); + } + } + + /** \internal */ + template inline void applyThisOnTheLeft(Dest& dst, bool inputIsIdentity = false) const + { + Matrix workspace; + applyThisOnTheLeft(dst, workspace, inputIsIdentity); + } + + /** \internal */ + template + inline void applyThisOnTheLeft(Dest& dst, Workspace& workspace, bool inputIsIdentity = false) const + { + if(inputIsIdentity && m_reverse) + inputIsIdentity = false; + // if the entries are large enough, then apply the reflectors by block + if(m_length>=BlockSize && dst.cols()>1) + { + // Make sure we have at least 2 useful blocks, otherwise it is point-less: + Index blockSize = m_length::type,Dynamic,Dynamic> SubVectorsType; + SubVectorsType sub_vecs1(m_vectors.const_cast_derived(), Side==OnTheRight ? k : start, + Side==OnTheRight ? start : k, + Side==OnTheRight ? bs : m_vectors.rows()-start, + Side==OnTheRight ? m_vectors.cols()-start : bs); + typename internal::conditional, SubVectorsType&>::type sub_vecs(sub_vecs1); + + Index dstStart = dst.rows()-rows()+m_shift+k; + Index dstRows = rows()-m_shift-k; + Block sub_dst(dst, + dstStart, + inputIsIdentity ? dstStart : 0, + dstRows, + inputIsIdentity ? dstRows : dst.cols()); + apply_block_householder_on_the_left(sub_dst, sub_vecs, m_coeffs.segment(k, bs), !m_reverse); + } + } + else + { + workspace.resize(dst.cols()); + for(Index k = 0; k < m_length; ++k) + { + Index actual_k = m_reverse ? k : m_length-k-1; + Index dstStart = rows()-m_shift-actual_k; + dst.bottomRightCorner(dstStart, inputIsIdentity ? dstStart : dst.cols()) + .applyHouseholderOnTheLeft(essentialVector(actual_k), m_coeffs.coeff(actual_k), workspace.data()); + } + } + } + + /** \brief Computes the product of a Householder sequence with a matrix. + * \param[in] other %Matrix being multiplied. + * \returns Expression object representing the product. + * + * This function computes \f$ HM \f$ where \f$ H \f$ is the Householder sequence represented by \p *this + * and \f$ M \f$ is the matrix \p other. + */ + template + typename internal::matrix_type_times_scalar_type::Type operator*(const MatrixBase& other) const + { + typename internal::matrix_type_times_scalar_type::Type + res(other.template cast::ResultScalar>()); + applyThisOnTheLeft(res, internal::is_identity::value && res.rows()==res.cols()); + return res; + } + + template friend struct internal::hseq_side_dependent_impl; + + /** \brief Sets the length of the Householder sequence. + * \param [in] length New value for the length. + * + * By default, the length \f$ n \f$ of the Householder sequence \f$ H = H_0 H_1 \ldots H_{n-1} \f$ is set + * to the number of columns of the matrix \p v passed to the constructor, or the number of rows if that + * is smaller. After this function is called, the length equals \p length. + * + * \sa length() + */ + EIGEN_DEVICE_FUNC + HouseholderSequence& setLength(Index length) + { + m_length = length; + return *this; + } + + /** \brief Sets the shift of the Householder sequence. + * \param [in] shift New value for the shift. + * + * By default, a %HouseholderSequence object represents \f$ H = H_0 H_1 \ldots H_{n-1} \f$ and the i-th + * column of the matrix \p v passed to the constructor corresponds to the i-th Householder + * reflection. After this function is called, the object represents \f$ H = H_{\mathrm{shift}} + * H_{\mathrm{shift}+1} \ldots H_{n-1} \f$ and the i-th column of \p v corresponds to the (shift+i)-th + * Householder reflection. + * + * \sa shift() + */ + EIGEN_DEVICE_FUNC + HouseholderSequence& setShift(Index shift) + { + m_shift = shift; + return *this; + } + + EIGEN_DEVICE_FUNC + Index length() const { return m_length; } /**< \brief Returns the length of the Householder sequence. */ + + EIGEN_DEVICE_FUNC + Index shift() const { return m_shift; } /**< \brief Returns the shift of the Householder sequence. */ + + /* Necessary for .adjoint() and .conjugate() */ + template friend class HouseholderSequence; + + protected: + + /** \internal + * \brief Sets the reverse flag. + * \param [in] reverse New value of the reverse flag. + * + * By default, the reverse flag is not set. If the reverse flag is set, then this object represents + * \f$ H^r = H_{n-1} \ldots H_1 H_0 \f$ instead of \f$ H = H_0 H_1 \ldots H_{n-1} \f$. + * \note For real valued HouseholderSequence this is equivalent to transposing \f$ H \f$. + * + * \sa reverseFlag(), transpose(), adjoint() + */ + HouseholderSequence& setReverseFlag(bool reverse) + { + m_reverse = reverse; + return *this; + } + + bool reverseFlag() const { return m_reverse; } /**< \internal \brief Returns the reverse flag. */ + + typename VectorsType::Nested m_vectors; + typename CoeffsType::Nested m_coeffs; + bool m_reverse; + Index m_length; + Index m_shift; + enum { BlockSize = 48 }; +}; + +/** \brief Computes the product of a matrix with a Householder sequence. + * \param[in] other %Matrix being multiplied. + * \param[in] h %HouseholderSequence being multiplied. + * \returns Expression object representing the product. + * + * This function computes \f$ MH \f$ where \f$ M \f$ is the matrix \p other and \f$ H \f$ is the + * Householder sequence represented by \p h. + */ +template +typename internal::matrix_type_times_scalar_type::Type operator*(const MatrixBase& other, const HouseholderSequence& h) +{ + typename internal::matrix_type_times_scalar_type::Type + res(other.template cast::ResultScalar>()); + h.applyThisOnTheRight(res); + return res; +} + +/** \ingroup Householder_Module \householder_module + * \brief Convenience function for constructing a Householder sequence. + * \returns A HouseholderSequence constructed from the specified arguments. + */ +template +HouseholderSequence householderSequence(const VectorsType& v, const CoeffsType& h) +{ + return HouseholderSequence(v, h); +} + +/** \ingroup Householder_Module \householder_module + * \brief Convenience function for constructing a Householder sequence. + * \returns A HouseholderSequence constructed from the specified arguments. + * \details This function differs from householderSequence() in that the template argument \p OnTheSide of + * the constructed HouseholderSequence is set to OnTheRight, instead of the default OnTheLeft. + */ +template +HouseholderSequence rightHouseholderSequence(const VectorsType& v, const CoeffsType& h) +{ + return HouseholderSequence(v, h); +} + +} // end namespace Eigen + +#endif // EIGEN_HOUSEHOLDER_SEQUENCE_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h new file mode 100644 index 0000000000000000000000000000000000000000..a117fc1551920de7e36ea6e33cbf959a0e62b4ab --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h @@ -0,0 +1,226 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BASIC_PRECONDITIONERS_H +#define EIGEN_BASIC_PRECONDITIONERS_H + +namespace Eigen { + +/** \ingroup IterativeLinearSolvers_Module + * \brief A preconditioner based on the digonal entries + * + * This class allows to approximately solve for A.x = b problems assuming A is a diagonal matrix. + * In other words, this preconditioner neglects all off diagonal entries and, in Eigen's language, solves for: + \code + A.diagonal().asDiagonal() . x = b + \endcode + * + * \tparam _Scalar the type of the scalar. + * + * \implsparsesolverconcept + * + * This preconditioner is suitable for both selfadjoint and general problems. + * The diagonal entries are pre-inverted and stored into a dense vector. + * + * \note A variant that has yet to be implemented would attempt to preserve the norm of each column. + * + * \sa class LeastSquareDiagonalPreconditioner, class ConjugateGradient + */ +template +class DiagonalPreconditioner +{ + typedef _Scalar Scalar; + typedef Matrix Vector; + public: + typedef typename Vector::StorageIndex StorageIndex; + enum { + ColsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic + }; + + DiagonalPreconditioner() : m_isInitialized(false) {} + + template + explicit DiagonalPreconditioner(const MatType& mat) : m_invdiag(mat.cols()) + { + compute(mat); + } + + EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_invdiag.size(); } + EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_invdiag.size(); } + + template + DiagonalPreconditioner& analyzePattern(const MatType& ) + { + return *this; + } + + template + DiagonalPreconditioner& factorize(const MatType& mat) + { + m_invdiag.resize(mat.cols()); + for(int j=0; j + DiagonalPreconditioner& compute(const MatType& mat) + { + return factorize(mat); + } + + /** \internal */ + template + void _solve_impl(const Rhs& b, Dest& x) const + { + x = m_invdiag.array() * b.array() ; + } + + template inline const Solve + solve(const MatrixBase& b) const + { + eigen_assert(m_isInitialized && "DiagonalPreconditioner is not initialized."); + eigen_assert(m_invdiag.size()==b.rows() + && "DiagonalPreconditioner::solve(): invalid number of rows of the right hand side matrix b"); + return Solve(*this, b.derived()); + } + + ComputationInfo info() { return Success; } + + protected: + Vector m_invdiag; + bool m_isInitialized; +}; + +/** \ingroup IterativeLinearSolvers_Module + * \brief Jacobi preconditioner for LeastSquaresConjugateGradient + * + * This class allows to approximately solve for A' A x = A' b problems assuming A' A is a diagonal matrix. + * In other words, this preconditioner neglects all off diagonal entries and, in Eigen's language, solves for: + \code + (A.adjoint() * A).diagonal().asDiagonal() * x = b + \endcode + * + * \tparam _Scalar the type of the scalar. + * + * \implsparsesolverconcept + * + * The diagonal entries are pre-inverted and stored into a dense vector. + * + * \sa class LeastSquaresConjugateGradient, class DiagonalPreconditioner + */ +template +class LeastSquareDiagonalPreconditioner : public DiagonalPreconditioner<_Scalar> +{ + typedef _Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef DiagonalPreconditioner<_Scalar> Base; + using Base::m_invdiag; + public: + + LeastSquareDiagonalPreconditioner() : Base() {} + + template + explicit LeastSquareDiagonalPreconditioner(const MatType& mat) : Base() + { + compute(mat); + } + + template + LeastSquareDiagonalPreconditioner& analyzePattern(const MatType& ) + { + return *this; + } + + template + LeastSquareDiagonalPreconditioner& factorize(const MatType& mat) + { + // Compute the inverse squared-norm of each column of mat + m_invdiag.resize(mat.cols()); + if(MatType::IsRowMajor) + { + m_invdiag.setZero(); + for(Index j=0; jRealScalar(0)) + m_invdiag(j) = RealScalar(1)/numext::real(m_invdiag(j)); + } + else + { + for(Index j=0; jRealScalar(0)) + m_invdiag(j) = RealScalar(1)/sum; + else + m_invdiag(j) = RealScalar(1); + } + } + Base::m_isInitialized = true; + return *this; + } + + template + LeastSquareDiagonalPreconditioner& compute(const MatType& mat) + { + return factorize(mat); + } + + ComputationInfo info() { return Success; } + + protected: +}; + +/** \ingroup IterativeLinearSolvers_Module + * \brief A naive preconditioner which approximates any matrix as the identity matrix + * + * \implsparsesolverconcept + * + * \sa class DiagonalPreconditioner + */ +class IdentityPreconditioner +{ + public: + + IdentityPreconditioner() {} + + template + explicit IdentityPreconditioner(const MatrixType& ) {} + + template + IdentityPreconditioner& analyzePattern(const MatrixType& ) { return *this; } + + template + IdentityPreconditioner& factorize(const MatrixType& ) { return *this; } + + template + IdentityPreconditioner& compute(const MatrixType& ) { return *this; } + + template + inline const Rhs& solve(const Rhs& b) const { return b; } + + ComputationInfo info() { return Success; } +}; + +} // end namespace Eigen + +#endif // EIGEN_BASIC_PRECONDITIONERS_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h new file mode 100644 index 0000000000000000000000000000000000000000..153acef65ba921c1ecec39ff670ba2c32b1dfef6 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h @@ -0,0 +1,212 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011-2014 Gael Guennebaud +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BICGSTAB_H +#define EIGEN_BICGSTAB_H + +namespace Eigen { + +namespace internal { + +/** \internal Low-level bi conjugate gradient stabilized algorithm + * \param mat The matrix A + * \param rhs The right hand side vector b + * \param x On input and initial solution, on output the computed solution. + * \param precond A preconditioner being able to efficiently solve for an + * approximation of Ax=b (regardless of b) + * \param iters On input the max number of iteration, on output the number of performed iterations. + * \param tol_error On input the tolerance error, on output an estimation of the relative error. + * \return false in the case of numerical issue, for example a break down of BiCGSTAB. + */ +template +bool bicgstab(const MatrixType& mat, const Rhs& rhs, Dest& x, + const Preconditioner& precond, Index& iters, + typename Dest::RealScalar& tol_error) +{ + using std::sqrt; + using std::abs; + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix VectorType; + RealScalar tol = tol_error; + Index maxIters = iters; + + Index n = mat.cols(); + VectorType r = rhs - mat * x; + VectorType r0 = r; + + RealScalar r0_sqnorm = r0.squaredNorm(); + RealScalar rhs_sqnorm = rhs.squaredNorm(); + if(rhs_sqnorm == 0) + { + x.setZero(); + return true; + } + Scalar rho = 1; + Scalar alpha = 1; + Scalar w = 1; + + VectorType v = VectorType::Zero(n), p = VectorType::Zero(n); + VectorType y(n), z(n); + VectorType kt(n), ks(n); + + VectorType s(n), t(n); + + RealScalar tol2 = tol*tol*rhs_sqnorm; + RealScalar eps2 = NumTraits::epsilon()*NumTraits::epsilon(); + Index i = 0; + Index restarts = 0; + + while ( r.squaredNorm() > tol2 && iRealScalar(0)) + w = t.dot(s) / tmp; + else + w = Scalar(0); + x += alpha * y + w * z; + r = s - w * t; + ++i; + } + tol_error = sqrt(r.squaredNorm()/rhs_sqnorm); + iters = i; + return true; +} + +} + +template< typename _MatrixType, + typename _Preconditioner = DiagonalPreconditioner > +class BiCGSTAB; + +namespace internal { + +template< typename _MatrixType, typename _Preconditioner> +struct traits > +{ + typedef _MatrixType MatrixType; + typedef _Preconditioner Preconditioner; +}; + +} + +/** \ingroup IterativeLinearSolvers_Module + * \brief A bi conjugate gradient stabilized solver for sparse square problems + * + * This class allows to solve for A.x = b sparse linear problems using a bi conjugate gradient + * stabilized algorithm. The vectors x and b can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, can be a dense or a sparse matrix. + * \tparam _Preconditioner the type of the preconditioner. Default is DiagonalPreconditioner + * + * \implsparsesolverconcept + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * The tolerance corresponds to the relative residual error: |Ax-b|/|b| + * + * \b Performance: when using sparse matrices, best performance is achied for a row-major sparse matrix format. + * Moreover, in this case multi-threading can be exploited if the user code is compiled with OpenMP enabled. + * See \ref TopicMultiThreading for details. + * + * This class can be used as the direct solver classes. Here is a typical usage example: + * \include BiCGSTAB_simple.cpp + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * BiCGSTAB can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ +template< typename _MatrixType, typename _Preconditioner> +class BiCGSTAB : public IterativeSolverBase > +{ + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; +public: + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef _Preconditioner Preconditioner; + +public: + + /** Default constructor. */ + BiCGSTAB() : Base() {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit BiCGSTAB(const EigenBase& A) : Base(A.derived()) {} + + ~BiCGSTAB() {} + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + + bool ret = internal::bicgstab(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error); + + m_info = (!ret) ? NumericalIssue + : m_error <= Base::m_tolerance ? Success + : NoConvergence; + } + +protected: + +}; + +} // end namespace Eigen + +#endif // EIGEN_BICGSTAB_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h new file mode 100644 index 0000000000000000000000000000000000000000..5d8c6b4339ee592b24f6092cfa67a53c51a2a0da --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h @@ -0,0 +1,229 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CONJUGATE_GRADIENT_H +#define EIGEN_CONJUGATE_GRADIENT_H + +namespace Eigen { + +namespace internal { + +/** \internal Low-level conjugate gradient algorithm + * \param mat The matrix A + * \param rhs The right hand side vector b + * \param x On input and initial solution, on output the computed solution. + * \param precond A preconditioner being able to efficiently solve for an + * approximation of Ax=b (regardless of b) + * \param iters On input the max number of iteration, on output the number of performed iterations. + * \param tol_error On input the tolerance error, on output an estimation of the relative error. + */ +template +EIGEN_DONT_INLINE +void conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x, + const Preconditioner& precond, Index& iters, + typename Dest::RealScalar& tol_error) +{ + using std::sqrt; + using std::abs; + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix VectorType; + + RealScalar tol = tol_error; + Index maxIters = iters; + + Index n = mat.cols(); + + VectorType residual = rhs - mat * x; //initial residual + + RealScalar rhsNorm2 = rhs.squaredNorm(); + if(rhsNorm2 == 0) + { + x.setZero(); + iters = 0; + tol_error = 0; + return; + } + const RealScalar considerAsZero = (std::numeric_limits::min)(); + RealScalar threshold = numext::maxi(RealScalar(tol*tol*rhsNorm2),considerAsZero); + RealScalar residualNorm2 = residual.squaredNorm(); + if (residualNorm2 < threshold) + { + iters = 0; + tol_error = sqrt(residualNorm2 / rhsNorm2); + return; + } + + VectorType p(n); + p = precond.solve(residual); // initial search direction + + VectorType z(n), tmp(n); + RealScalar absNew = numext::real(residual.dot(p)); // the square of the absolute value of r scaled by invM + Index i = 0; + while(i < maxIters) + { + tmp.noalias() = mat * p; // the bottleneck of the algorithm + + Scalar alpha = absNew / p.dot(tmp); // the amount we travel on dir + x += alpha * p; // update solution + residual -= alpha * tmp; // update residual + + residualNorm2 = residual.squaredNorm(); + if(residualNorm2 < threshold) + break; + + z = precond.solve(residual); // approximately solve for "A z = residual" + + RealScalar absOld = absNew; + absNew = numext::real(residual.dot(z)); // update the absolute value of r + RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction + p = z + beta * p; // update search direction + i++; + } + tol_error = sqrt(residualNorm2 / rhsNorm2); + iters = i; +} + +} + +template< typename _MatrixType, int _UpLo=Lower, + typename _Preconditioner = DiagonalPreconditioner > +class ConjugateGradient; + +namespace internal { + +template< typename _MatrixType, int _UpLo, typename _Preconditioner> +struct traits > +{ + typedef _MatrixType MatrixType; + typedef _Preconditioner Preconditioner; +}; + +} + +/** \ingroup IterativeLinearSolvers_Module + * \brief A conjugate gradient solver for sparse (or dense) self-adjoint problems + * + * This class allows to solve for A.x = b linear problems using an iterative conjugate gradient algorithm. + * The matrix A must be selfadjoint. The matrix A and the vectors x and b can be either dense or sparse. + * + * \tparam _MatrixType the type of the matrix A, can be a dense or a sparse matrix. + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower, + * \c Upper, or \c Lower|Upper in which the full matrix entries will be considered. + * Default is \c Lower, best performance is \c Lower|Upper. + * \tparam _Preconditioner the type of the preconditioner. Default is DiagonalPreconditioner + * + * \implsparsesolverconcept + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * The tolerance corresponds to the relative residual error: |Ax-b|/|b| + * + * \b Performance: Even though the default value of \c _UpLo is \c Lower, significantly higher performance is + * achieved when using a complete matrix and \b Lower|Upper as the \a _UpLo template parameter. Moreover, in this + * case multi-threading can be exploited if the user code is compiled with OpenMP enabled. + * See \ref TopicMultiThreading for details. + * + * This class can be used as the direct solver classes. Here is a typical usage example: + \code + int n = 10000; + VectorXd x(n), b(n); + SparseMatrix A(n,n); + // fill A and b + ConjugateGradient, Lower|Upper> cg; + cg.compute(A); + x = cg.solve(b); + std::cout << "#iterations: " << cg.iterations() << std::endl; + std::cout << "estimated error: " << cg.error() << std::endl; + // update b, and solve again + x = cg.solve(b); + \endcode + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * ConjugateGradient can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * \sa class LeastSquaresConjugateGradient, class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ +template< typename _MatrixType, int _UpLo, typename _Preconditioner> +class ConjugateGradient : public IterativeSolverBase > +{ + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; +public: + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef _Preconditioner Preconditioner; + + enum { + UpLo = _UpLo + }; + +public: + + /** Default constructor. */ + ConjugateGradient() : Base() {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit ConjugateGradient(const EigenBase& A) : Base(A.derived()) {} + + ~ConjugateGradient() {} + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + typedef typename Base::MatrixWrapper MatrixWrapper; + typedef typename Base::ActualMatrixType ActualMatrixType; + enum { + TransposeInput = (!MatrixWrapper::MatrixFree) + && (UpLo==(Lower|Upper)) + && (!MatrixType::IsRowMajor) + && (!NumTraits::IsComplex) + }; + typedef typename internal::conditional, ActualMatrixType const&>::type RowMajorWrapper; + EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(MatrixWrapper::MatrixFree,UpLo==(Lower|Upper)),MATRIX_FREE_CONJUGATE_GRADIENT_IS_COMPATIBLE_WITH_UPPER_UNION_LOWER_MODE_ONLY); + typedef typename internal::conditional::Type + >::type SelfAdjointWrapper; + + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + + RowMajorWrapper row_mat(matrix()); + internal::conjugate_gradient(SelfAdjointWrapper(row_mat), b, x, Base::m_preconditioner, m_iterations, m_error); + m_info = m_error <= Base::m_tolerance ? Success : NoConvergence; + } + +protected: + +}; + +} // end namespace Eigen + +#endif // EIGEN_CONJUGATE_GRADIENT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h new file mode 100644 index 0000000000000000000000000000000000000000..cdcf709eb63e0c5785d314db3855c813b8f4e3f3 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h @@ -0,0 +1,453 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_INCOMPLETE_LUT_H +#define EIGEN_INCOMPLETE_LUT_H + + +namespace Eigen { + +namespace internal { + +/** \internal + * Compute a quick-sort split of a vector + * On output, the vector row is permuted such that its elements satisfy + * abs(row(i)) >= abs(row(ncut)) if incut + * \param row The vector of values + * \param ind The array of index for the elements in @p row + * \param ncut The number of largest elements to keep + **/ +template +Index QuickSplit(VectorV &row, VectorI &ind, Index ncut) +{ + typedef typename VectorV::RealScalar RealScalar; + using std::swap; + using std::abs; + Index mid; + Index n = row.size(); /* length of the vector */ + Index first, last ; + + ncut--; /* to fit the zero-based indices */ + first = 0; + last = n-1; + if (ncut < first || ncut > last ) return 0; + + do { + mid = first; + RealScalar abskey = abs(row(mid)); + for (Index j = first + 1; j <= last; j++) { + if ( abs(row(j)) > abskey) { + ++mid; + swap(row(mid), row(j)); + swap(ind(mid), ind(j)); + } + } + /* Interchange for the pivot element */ + swap(row(mid), row(first)); + swap(ind(mid), ind(first)); + + if (mid > ncut) last = mid - 1; + else if (mid < ncut ) first = mid + 1; + } while (mid != ncut ); + + return 0; /* mid is equal to ncut */ +} + +}// end namespace internal + +/** \ingroup IterativeLinearSolvers_Module + * \class IncompleteLUT + * \brief Incomplete LU factorization with dual-threshold strategy + * + * \implsparsesolverconcept + * + * During the numerical factorization, two dropping rules are used : + * 1) any element whose magnitude is less than some tolerance is dropped. + * This tolerance is obtained by multiplying the input tolerance @p droptol + * by the average magnitude of all the original elements in the current row. + * 2) After the elimination of the row, only the @p fill largest elements in + * the L part and the @p fill largest elements in the U part are kept + * (in addition to the diagonal element ). Note that @p fill is computed from + * the input parameter @p fillfactor which is used the ratio to control the fill_in + * relatively to the initial number of nonzero elements. + * + * The two extreme cases are when @p droptol=0 (to keep all the @p fill*2 largest elements) + * and when @p fill=n/2 with @p droptol being different to zero. + * + * References : Yousef Saad, ILUT: A dual threshold incomplete LU factorization, + * Numerical Linear Algebra with Applications, 1(4), pp 387-402, 1994. + * + * NOTE : The following implementation is derived from the ILUT implementation + * in the SPARSKIT package, Copyright (C) 2005, the Regents of the University of Minnesota + * released under the terms of the GNU LGPL: + * http://www-users.cs.umn.edu/~saad/software/SPARSKIT/README + * However, Yousef Saad gave us permission to relicense his ILUT code to MPL2. + * See the Eigen mailing list archive, thread: ILUT, date: July 8, 2012: + * http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2012/07/msg00064.html + * alternatively, on GMANE: + * http://comments.gmane.org/gmane.comp.lib.eigen/3302 + */ +template +class IncompleteLUT : public SparseSolverBase > +{ + protected: + typedef SparseSolverBase Base; + using Base::m_isInitialized; + public: + typedef _Scalar Scalar; + typedef _StorageIndex StorageIndex; + typedef typename NumTraits::Real RealScalar; + typedef Matrix Vector; + typedef Matrix VectorI; + typedef SparseMatrix FactorType; + + enum { + ColsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic + }; + + public: + + IncompleteLUT() + : m_droptol(NumTraits::dummy_precision()), m_fillfactor(10), + m_analysisIsOk(false), m_factorizationIsOk(false) + {} + + template + explicit IncompleteLUT(const MatrixType& mat, const RealScalar& droptol=NumTraits::dummy_precision(), int fillfactor = 10) + : m_droptol(droptol),m_fillfactor(fillfactor), + m_analysisIsOk(false),m_factorizationIsOk(false) + { + eigen_assert(fillfactor != 0); + compute(mat); + } + + EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_lu.rows(); } + + EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_lu.cols(); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "IncompleteLUT is not initialized."); + return m_info; + } + + template + void analyzePattern(const MatrixType& amat); + + template + void factorize(const MatrixType& amat); + + /** + * Compute an incomplete LU factorization with dual threshold on the matrix mat + * No pivoting is done in this version + * + **/ + template + IncompleteLUT& compute(const MatrixType& amat) + { + analyzePattern(amat); + factorize(amat); + return *this; + } + + void setDroptol(const RealScalar& droptol); + void setFillfactor(int fillfactor); + + template + void _solve_impl(const Rhs& b, Dest& x) const + { + x = m_Pinv * b; + x = m_lu.template triangularView().solve(x); + x = m_lu.template triangularView().solve(x); + x = m_P * x; + } + +protected: + + /** keeps off-diagonal entries; drops diagonal entries */ + struct keep_diag { + inline bool operator() (const Index& row, const Index& col, const Scalar&) const + { + return row!=col; + } + }; + +protected: + + FactorType m_lu; + RealScalar m_droptol; + int m_fillfactor; + bool m_analysisIsOk; + bool m_factorizationIsOk; + ComputationInfo m_info; + PermutationMatrix m_P; // Fill-reducing permutation + PermutationMatrix m_Pinv; // Inverse permutation +}; + +/** + * Set control parameter droptol + * \param droptol Drop any element whose magnitude is less than this tolerance + **/ +template +void IncompleteLUT::setDroptol(const RealScalar& droptol) +{ + this->m_droptol = droptol; +} + +/** + * Set control parameter fillfactor + * \param fillfactor This is used to compute the number @p fill_in of largest elements to keep on each row. + **/ +template +void IncompleteLUT::setFillfactor(int fillfactor) +{ + this->m_fillfactor = fillfactor; +} + +template +template +void IncompleteLUT::analyzePattern(const _MatrixType& amat) +{ + // Compute the Fill-reducing permutation + // Since ILUT does not perform any numerical pivoting, + // it is highly preferable to keep the diagonal through symmetric permutations. + // To this end, let's symmetrize the pattern and perform AMD on it. + SparseMatrix mat1 = amat; + SparseMatrix mat2 = amat.transpose(); + // FIXME for a matrix with nearly symmetric pattern, mat2+mat1 is the appropriate choice. + // on the other hand for a really non-symmetric pattern, mat2*mat1 should be preferred... + SparseMatrix AtA = mat2 + mat1; + AMDOrdering ordering; + ordering(AtA,m_P); + m_Pinv = m_P.inverse(); // cache the inverse permutation + m_analysisIsOk = true; + m_factorizationIsOk = false; + m_isInitialized = true; +} + +template +template +void IncompleteLUT::factorize(const _MatrixType& amat) +{ + using std::sqrt; + using std::swap; + using std::abs; + using internal::convert_index; + + eigen_assert((amat.rows() == amat.cols()) && "The factorization should be done on a square matrix"); + Index n = amat.cols(); // Size of the matrix + m_lu.resize(n,n); + // Declare Working vectors and variables + Vector u(n) ; // real values of the row -- maximum size is n -- + VectorI ju(n); // column position of the values in u -- maximum size is n + VectorI jr(n); // Indicate the position of the nonzero elements in the vector u -- A zero location is indicated by -1 + + // Apply the fill-reducing permutation + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + SparseMatrix mat; + mat = amat.twistedBy(m_Pinv); + + // Initialization + jr.fill(-1); + ju.fill(0); + u.fill(0); + + // number of largest elements to keep in each row: + Index fill_in = (amat.nonZeros()*m_fillfactor)/n + 1; + if (fill_in > n) fill_in = n; + + // number of largest nonzero elements to keep in the L and the U part of the current row: + Index nnzL = fill_in/2; + Index nnzU = nnzL; + m_lu.reserve(n * (nnzL + nnzU + 1)); + + // global loop over the rows of the sparse matrix + for (Index ii = 0; ii < n; ii++) + { + // 1 - copy the lower and the upper part of the row i of mat in the working vector u + + Index sizeu = 1; // number of nonzero elements in the upper part of the current row + Index sizel = 0; // number of nonzero elements in the lower part of the current row + ju(ii) = convert_index(ii); + u(ii) = 0; + jr(ii) = convert_index(ii); + RealScalar rownorm = 0; + + typename FactorType::InnerIterator j_it(mat, ii); // Iterate through the current row ii + for (; j_it; ++j_it) + { + Index k = j_it.index(); + if (k < ii) + { + // copy the lower part + ju(sizel) = convert_index(k); + u(sizel) = j_it.value(); + jr(k) = convert_index(sizel); + ++sizel; + } + else if (k == ii) + { + u(ii) = j_it.value(); + } + else + { + // copy the upper part + Index jpos = ii + sizeu; + ju(jpos) = convert_index(k); + u(jpos) = j_it.value(); + jr(k) = convert_index(jpos); + ++sizeu; + } + rownorm += numext::abs2(j_it.value()); + } + + // 2 - detect possible zero row + if(rownorm==0) + { + m_info = NumericalIssue; + return; + } + // Take the 2-norm of the current row as a relative tolerance + rownorm = sqrt(rownorm); + + // 3 - eliminate the previous nonzero rows + Index jj = 0; + Index len = 0; + while (jj < sizel) + { + // In order to eliminate in the correct order, + // we must select first the smallest column index among ju(jj:sizel) + Index k; + Index minrow = ju.segment(jj,sizel-jj).minCoeff(&k); // k is relative to the segment + k += jj; + if (minrow != ju(jj)) + { + // swap the two locations + Index j = ju(jj); + swap(ju(jj), ju(k)); + jr(minrow) = convert_index(jj); + jr(j) = convert_index(k); + swap(u(jj), u(k)); + } + // Reset this location + jr(minrow) = -1; + + // Start elimination + typename FactorType::InnerIterator ki_it(m_lu, minrow); + while (ki_it && ki_it.index() < minrow) ++ki_it; + eigen_internal_assert(ki_it && ki_it.col()==minrow); + Scalar fact = u(jj) / ki_it.value(); + + // drop too small elements + if(abs(fact) <= m_droptol) + { + jj++; + continue; + } + + // linear combination of the current row ii and the row minrow + ++ki_it; + for (; ki_it; ++ki_it) + { + Scalar prod = fact * ki_it.value(); + Index j = ki_it.index(); + Index jpos = jr(j); + if (jpos == -1) // fill-in element + { + Index newpos; + if (j >= ii) // dealing with the upper part + { + newpos = ii + sizeu; + sizeu++; + eigen_internal_assert(sizeu<=n); + } + else // dealing with the lower part + { + newpos = sizel; + sizel++; + eigen_internal_assert(sizel<=ii); + } + ju(newpos) = convert_index(j); + u(newpos) = -prod; + jr(j) = convert_index(newpos); + } + else + u(jpos) -= prod; + } + // store the pivot element + u(len) = fact; + ju(len) = convert_index(minrow); + ++len; + + jj++; + } // end of the elimination on the row ii + + // reset the upper part of the pointer jr to zero + for(Index k = 0; k m_droptol * rownorm ) + { + ++len; + u(ii + len) = u(ii + k); + ju(ii + len) = ju(ii + k); + } + } + sizeu = len + 1; // +1 to take into account the diagonal element + len = (std::min)(sizeu, nnzU); + typename Vector::SegmentReturnType uu(u.segment(ii+1, sizeu-1)); + typename VectorI::SegmentReturnType juu(ju.segment(ii+1, sizeu-1)); + internal::QuickSplit(uu, juu, len); + + // store the largest elements of the U part + for(Index k = ii + 1; k < ii + len; k++) + m_lu.insertBackByOuterInnerUnordered(ii,ju(k)) = u(k); + } + m_lu.finalize(); + m_lu.makeCompressed(); + + m_factorizationIsOk = true; + m_info = Success; +} + +} // end namespace Eigen + +#endif // EIGEN_INCOMPLETE_LUT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h new file mode 100644 index 0000000000000000000000000000000000000000..28a0c5109e9fef44e1db80d742988f015d00b604 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h @@ -0,0 +1,444 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ITERATIVE_SOLVER_BASE_H +#define EIGEN_ITERATIVE_SOLVER_BASE_H + +namespace Eigen { + +namespace internal { + +template +struct is_ref_compatible_impl +{ +private: + template + struct any_conversion + { + template any_conversion(const volatile T&); + template any_conversion(T&); + }; + struct yes {int a[1];}; + struct no {int a[2];}; + + template + static yes test(const Ref&, int); + template + static no test(any_conversion, ...); + +public: + static MatrixType ms_from; + enum { value = sizeof(test(ms_from, 0))==sizeof(yes) }; +}; + +template +struct is_ref_compatible +{ + enum { value = is_ref_compatible_impl::type>::value }; +}; + +template::value> +class generic_matrix_wrapper; + +// We have an explicit matrix at hand, compatible with Ref<> +template +class generic_matrix_wrapper +{ +public: + typedef Ref ActualMatrixType; + template struct ConstSelfAdjointViewReturnType { + typedef typename ActualMatrixType::template ConstSelfAdjointViewReturnType::Type Type; + }; + + enum { + MatrixFree = false + }; + + generic_matrix_wrapper() + : m_dummy(0,0), m_matrix(m_dummy) + {} + + template + generic_matrix_wrapper(const InputType &mat) + : m_matrix(mat) + {} + + const ActualMatrixType& matrix() const + { + return m_matrix; + } + + template + void grab(const EigenBase &mat) + { + m_matrix.~Ref(); + ::new (&m_matrix) Ref(mat.derived()); + } + + void grab(const Ref &mat) + { + if(&(mat.derived()) != &m_matrix) + { + m_matrix.~Ref(); + ::new (&m_matrix) Ref(mat); + } + } + +protected: + MatrixType m_dummy; // used to default initialize the Ref<> object + ActualMatrixType m_matrix; +}; + +// MatrixType is not compatible with Ref<> -> matrix-free wrapper +template +class generic_matrix_wrapper +{ +public: + typedef MatrixType ActualMatrixType; + template struct ConstSelfAdjointViewReturnType + { + typedef ActualMatrixType Type; + }; + + enum { + MatrixFree = true + }; + + generic_matrix_wrapper() + : mp_matrix(0) + {} + + generic_matrix_wrapper(const MatrixType &mat) + : mp_matrix(&mat) + {} + + const ActualMatrixType& matrix() const + { + return *mp_matrix; + } + + void grab(const MatrixType &mat) + { + mp_matrix = &mat; + } + +protected: + const ActualMatrixType *mp_matrix; +}; + +} + +/** \ingroup IterativeLinearSolvers_Module + * \brief Base class for linear iterative solvers + * + * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ +template< typename Derived> +class IterativeSolverBase : public SparseSolverBase +{ +protected: + typedef SparseSolverBase Base; + using Base::m_isInitialized; + +public: + typedef typename internal::traits::MatrixType MatrixType; + typedef typename internal::traits::Preconditioner Preconditioner; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef typename MatrixType::RealScalar RealScalar; + + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + +public: + + using Base::derived; + + /** Default constructor. */ + IterativeSolverBase() + { + init(); + } + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit IterativeSolverBase(const EigenBase& A) + : m_matrixWrapper(A.derived()) + { + init(); + compute(matrix()); + } + + ~IterativeSolverBase() {} + + /** Initializes the iterative solver for the sparsity pattern of the matrix \a A for further solving \c Ax=b problems. + * + * Currently, this function mostly calls analyzePattern on the preconditioner. In the future + * we might, for instance, implement column reordering for faster matrix vector products. + */ + template + Derived& analyzePattern(const EigenBase& A) + { + grab(A.derived()); + m_preconditioner.analyzePattern(matrix()); + m_isInitialized = true; + m_analysisIsOk = true; + m_info = m_preconditioner.info(); + return derived(); + } + + /** Initializes the iterative solver with the numerical values of the matrix \a A for further solving \c Ax=b problems. + * + * Currently, this function mostly calls factorize on the preconditioner. + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + Derived& factorize(const EigenBase& A) + { + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + grab(A.derived()); + m_preconditioner.factorize(matrix()); + m_factorizationIsOk = true; + m_info = m_preconditioner.info(); + return derived(); + } + + /** Initializes the iterative solver with the matrix \a A for further solving \c Ax=b problems. + * + * Currently, this function mostly initializes/computes the preconditioner. In the future + * we might, for instance, implement column reordering for faster matrix vector products. + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + Derived& compute(const EigenBase& A) + { + grab(A.derived()); + m_preconditioner.compute(matrix()); + m_isInitialized = true; + m_analysisIsOk = true; + m_factorizationIsOk = true; + m_info = m_preconditioner.info(); + return derived(); + } + + /** \internal */ + EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return matrix().rows(); } + + /** \internal */ + EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return matrix().cols(); } + + /** \returns the tolerance threshold used by the stopping criteria. + * \sa setTolerance() + */ + RealScalar tolerance() const { return m_tolerance; } + + /** Sets the tolerance threshold used by the stopping criteria. + * + * This value is used as an upper bound to the relative residual error: |Ax-b|/|b|. + * The default value is the machine precision given by NumTraits::epsilon() + */ + Derived& setTolerance(const RealScalar& tolerance) + { + m_tolerance = tolerance; + return derived(); + } + + /** \returns a read-write reference to the preconditioner for custom configuration. */ + Preconditioner& preconditioner() { return m_preconditioner; } + + /** \returns a read-only reference to the preconditioner. */ + const Preconditioner& preconditioner() const { return m_preconditioner; } + + /** \returns the max number of iterations. + * It is either the value set by setMaxIterations or, by default, + * twice the number of columns of the matrix. + */ + Index maxIterations() const + { + return (m_maxIterations<0) ? 2*matrix().cols() : m_maxIterations; + } + + /** Sets the max number of iterations. + * Default is twice the number of columns of the matrix. + */ + Derived& setMaxIterations(Index maxIters) + { + m_maxIterations = maxIters; + return derived(); + } + + /** \returns the number of iterations performed during the last solve */ + Index iterations() const + { + eigen_assert(m_isInitialized && "ConjugateGradient is not initialized."); + return m_iterations; + } + + /** \returns the tolerance error reached during the last solve. + * It is a close approximation of the true relative residual error |Ax-b|/|b|. + */ + RealScalar error() const + { + eigen_assert(m_isInitialized && "ConjugateGradient is not initialized."); + return m_error; + } + + /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A + * and \a x0 as an initial solution. + * + * \sa solve(), compute() + */ + template + inline const SolveWithGuess + solveWithGuess(const MatrixBase& b, const Guess& x0) const + { + eigen_assert(m_isInitialized && "Solver is not initialized."); + eigen_assert(derived().rows()==b.rows() && "solve(): invalid number of rows of the right hand side matrix b"); + return SolveWithGuess(derived(), b.derived(), x0); + } + + /** \returns Success if the iterations converged, and NoConvergence otherwise. */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized."); + return m_info; + } + + /** \internal */ + template + void _solve_with_guess_impl(const Rhs& b, SparseMatrixBase &aDest) const + { + eigen_assert(rows()==b.rows()); + + Index rhsCols = b.cols(); + Index size = b.rows(); + DestDerived& dest(aDest.derived()); + typedef typename DestDerived::Scalar DestScalar; + Eigen::Matrix tb(size); + Eigen::Matrix tx(cols()); + // We do not directly fill dest because sparse expressions have to be free of aliasing issue. + // For non square least-square problems, b and dest might not have the same size whereas they might alias each-other. + typename DestDerived::PlainObject tmp(cols(),rhsCols); + ComputationInfo global_info = Success; + for(Index k=0; k + typename internal::enable_if::type + _solve_with_guess_impl(const Rhs& b, MatrixBase &aDest) const + { + eigen_assert(rows()==b.rows()); + + Index rhsCols = b.cols(); + DestDerived& dest(aDest.derived()); + ComputationInfo global_info = Success; + for(Index k=0; k + typename internal::enable_if::type + _solve_with_guess_impl(const Rhs& b, MatrixBase &dest) const + { + derived()._solve_vector_with_guess_impl(b,dest.derived()); + } + + /** \internal default initial guess = 0 */ + template + void _solve_impl(const Rhs& b, Dest& x) const + { + x.setZero(); + derived()._solve_with_guess_impl(b,x); + } + +protected: + void init() + { + m_isInitialized = false; + m_analysisIsOk = false; + m_factorizationIsOk = false; + m_maxIterations = -1; + m_tolerance = NumTraits::epsilon(); + } + + typedef internal::generic_matrix_wrapper MatrixWrapper; + typedef typename MatrixWrapper::ActualMatrixType ActualMatrixType; + + const ActualMatrixType& matrix() const + { + return m_matrixWrapper.matrix(); + } + + template + void grab(const InputType &A) + { + m_matrixWrapper.grab(A); + } + + MatrixWrapper m_matrixWrapper; + Preconditioner m_preconditioner; + + Index m_maxIterations; + RealScalar m_tolerance; + + mutable RealScalar m_error; + mutable Index m_iterations; + mutable ComputationInfo m_info; + mutable bool m_analysisIsOk, m_factorizationIsOk; +}; + +} // end namespace Eigen + +#endif // EIGEN_ITERATIVE_SOLVER_BASE_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/LeastSquareConjugateGradient.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/LeastSquareConjugateGradient.h new file mode 100644 index 0000000000000000000000000000000000000000..203fd0ec63f5979870fb66546e6bd991335b8801 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/LeastSquareConjugateGradient.h @@ -0,0 +1,198 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H +#define EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H + +namespace Eigen { + +namespace internal { + +/** \internal Low-level conjugate gradient algorithm for least-square problems + * \param mat The matrix A + * \param rhs The right hand side vector b + * \param x On input and initial solution, on output the computed solution. + * \param precond A preconditioner being able to efficiently solve for an + * approximation of A'Ax=b (regardless of b) + * \param iters On input the max number of iteration, on output the number of performed iterations. + * \param tol_error On input the tolerance error, on output an estimation of the relative error. + */ +template +EIGEN_DONT_INLINE +void least_square_conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x, + const Preconditioner& precond, Index& iters, + typename Dest::RealScalar& tol_error) +{ + using std::sqrt; + using std::abs; + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix VectorType; + + RealScalar tol = tol_error; + Index maxIters = iters; + + Index m = mat.rows(), n = mat.cols(); + + VectorType residual = rhs - mat * x; + VectorType normal_residual = mat.adjoint() * residual; + + RealScalar rhsNorm2 = (mat.adjoint()*rhs).squaredNorm(); + if(rhsNorm2 == 0) + { + x.setZero(); + iters = 0; + tol_error = 0; + return; + } + RealScalar threshold = tol*tol*rhsNorm2; + RealScalar residualNorm2 = normal_residual.squaredNorm(); + if (residualNorm2 < threshold) + { + iters = 0; + tol_error = sqrt(residualNorm2 / rhsNorm2); + return; + } + + VectorType p(n); + p = precond.solve(normal_residual); // initial search direction + + VectorType z(n), tmp(m); + RealScalar absNew = numext::real(normal_residual.dot(p)); // the square of the absolute value of r scaled by invM + Index i = 0; + while(i < maxIters) + { + tmp.noalias() = mat * p; + + Scalar alpha = absNew / tmp.squaredNorm(); // the amount we travel on dir + x += alpha * p; // update solution + residual -= alpha * tmp; // update residual + normal_residual = mat.adjoint() * residual; // update residual of the normal equation + + residualNorm2 = normal_residual.squaredNorm(); + if(residualNorm2 < threshold) + break; + + z = precond.solve(normal_residual); // approximately solve for "A'A z = normal_residual" + + RealScalar absOld = absNew; + absNew = numext::real(normal_residual.dot(z)); // update the absolute value of r + RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction + p = z + beta * p; // update search direction + i++; + } + tol_error = sqrt(residualNorm2 / rhsNorm2); + iters = i; +} + +} + +template< typename _MatrixType, + typename _Preconditioner = LeastSquareDiagonalPreconditioner > +class LeastSquaresConjugateGradient; + +namespace internal { + +template< typename _MatrixType, typename _Preconditioner> +struct traits > +{ + typedef _MatrixType MatrixType; + typedef _Preconditioner Preconditioner; +}; + +} + +/** \ingroup IterativeLinearSolvers_Module + * \brief A conjugate gradient solver for sparse (or dense) least-square problems + * + * This class allows to solve for A x = b linear problems using an iterative conjugate gradient algorithm. + * The matrix A can be non symmetric and rectangular, but the matrix A' A should be positive-definite to guaranty stability. + * Otherwise, the SparseLU or SparseQR classes might be preferable. + * The matrix A and the vectors x and b can be either dense or sparse. + * + * \tparam _MatrixType the type of the matrix A, can be a dense or a sparse matrix. + * \tparam _Preconditioner the type of the preconditioner. Default is LeastSquareDiagonalPreconditioner + * + * \implsparsesolverconcept + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * This class can be used as the direct solver classes. Here is a typical usage example: + \code + int m=1000000, n = 10000; + VectorXd x(n), b(m); + SparseMatrix A(m,n); + // fill A and b + LeastSquaresConjugateGradient > lscg; + lscg.compute(A); + x = lscg.solve(b); + std::cout << "#iterations: " << lscg.iterations() << std::endl; + std::cout << "estimated error: " << lscg.error() << std::endl; + // update b, and solve again + x = lscg.solve(b); + \endcode + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * \sa class ConjugateGradient, SparseLU, SparseQR + */ +template< typename _MatrixType, typename _Preconditioner> +class LeastSquaresConjugateGradient : public IterativeSolverBase > +{ + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; +public: + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef _Preconditioner Preconditioner; + +public: + + /** Default constructor. */ + LeastSquaresConjugateGradient() : Base() {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit LeastSquaresConjugateGradient(const EigenBase& A) : Base(A.derived()) {} + + ~LeastSquaresConjugateGradient() {} + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + + internal::least_square_conjugate_gradient(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error); + m_info = m_error <= Base::m_tolerance ? Success : NoConvergence; + } + +}; + +} // end namespace Eigen + +#endif // EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/SolveWithGuess.h b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/SolveWithGuess.h new file mode 100644 index 0000000000000000000000000000000000000000..7b896575428056e83c36fcfd2cf11672696d685e --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/IterativeLinearSolvers/SolveWithGuess.h @@ -0,0 +1,117 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SOLVEWITHGUESS_H +#define EIGEN_SOLVEWITHGUESS_H + +namespace Eigen { + +template class SolveWithGuess; + +/** \class SolveWithGuess + * \ingroup IterativeLinearSolvers_Module + * + * \brief Pseudo expression representing a solving operation + * + * \tparam Decomposition the type of the matrix or decomposion object + * \tparam Rhstype the type of the right-hand side + * + * This class represents an expression of A.solve(B) + * and most of the time this is the only way it is used. + * + */ +namespace internal { + + +template +struct traits > + : traits > +{}; + +} + + +template +class SolveWithGuess : public internal::generic_xpr_base, MatrixXpr, typename internal::traits::StorageKind>::type +{ +public: + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::PlainObject PlainObject; + typedef typename internal::generic_xpr_base, MatrixXpr, typename internal::traits::StorageKind>::type Base; + typedef typename internal::ref_selector::type Nested; + + SolveWithGuess(const Decomposition &dec, const RhsType &rhs, const GuessType &guess) + : m_dec(dec), m_rhs(rhs), m_guess(guess) + {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR + Index rows() const EIGEN_NOEXCEPT { return m_dec.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR + Index cols() const EIGEN_NOEXCEPT { return m_rhs.cols(); } + + EIGEN_DEVICE_FUNC const Decomposition& dec() const { return m_dec; } + EIGEN_DEVICE_FUNC const RhsType& rhs() const { return m_rhs; } + EIGEN_DEVICE_FUNC const GuessType& guess() const { return m_guess; } + +protected: + const Decomposition &m_dec; + const RhsType &m_rhs; + const GuessType &m_guess; + +private: + Scalar coeff(Index row, Index col) const; + Scalar coeff(Index i) const; +}; + +namespace internal { + +// Evaluator of SolveWithGuess -> eval into a temporary +template +struct evaluator > + : public evaluator::PlainObject> +{ + typedef SolveWithGuess SolveType; + typedef typename SolveType::PlainObject PlainObject; + typedef evaluator Base; + + evaluator(const SolveType& solve) + : m_result(solve.rows(), solve.cols()) + { + ::new (static_cast(this)) Base(m_result); + m_result = solve.guess(); + solve.dec()._solve_with_guess_impl(solve.rhs(), m_result); + } + +protected: + PlainObject m_result; +}; + +// Specialization for "dst = dec.solveWithGuess(rhs)" +// NOTE we need to specialize it for Dense2Dense to avoid ambiguous specialization error and a Sparse2Sparse specialization must exist somewhere +template +struct Assignment, internal::assign_op, Dense2Dense> +{ + typedef SolveWithGuess SrcXprType; + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + dst = src.guess(); + src.dec()._solve_with_guess_impl(src.rhs(), dst/*, src.guess()*/); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SOLVEWITHGUESS_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/Jacobi/Jacobi.h b/vendor/eigen/include/eigen3/Eigen/src/Jacobi/Jacobi.h new file mode 100644 index 0000000000000000000000000000000000000000..76668a574aee62f2a52e434fd4b7ebc7d5a952ee --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/Jacobi/Jacobi.h @@ -0,0 +1,483 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Benoit Jacob +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_JACOBI_H +#define EIGEN_JACOBI_H + +namespace Eigen { + +/** \ingroup Jacobi_Module + * \jacobi_module + * \class JacobiRotation + * \brief Rotation given by a cosine-sine pair. + * + * This class represents a Jacobi or Givens rotation. + * This is a 2D rotation in the plane \c J of angle \f$ \theta \f$ defined by + * its cosine \c c and sine \c s as follow: + * \f$ J = \left ( \begin{array}{cc} c & \overline s \\ -s & \overline c \end{array} \right ) \f$ + * + * You can apply the respective counter-clockwise rotation to a column vector \c v by + * applying its adjoint on the left: \f$ v = J^* v \f$ that translates to the following Eigen code: + * \code + * v.applyOnTheLeft(J.adjoint()); + * \endcode + * + * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight() + */ +template class JacobiRotation +{ + public: + typedef typename NumTraits::Real RealScalar; + + /** Default constructor without any initialization. */ + EIGEN_DEVICE_FUNC + JacobiRotation() {} + + /** Construct a planar rotation from a cosine-sine pair (\a c, \c s). */ + EIGEN_DEVICE_FUNC + JacobiRotation(const Scalar& c, const Scalar& s) : m_c(c), m_s(s) {} + + EIGEN_DEVICE_FUNC Scalar& c() { return m_c; } + EIGEN_DEVICE_FUNC Scalar c() const { return m_c; } + EIGEN_DEVICE_FUNC Scalar& s() { return m_s; } + EIGEN_DEVICE_FUNC Scalar s() const { return m_s; } + + /** Concatenates two planar rotation */ + EIGEN_DEVICE_FUNC + JacobiRotation operator*(const JacobiRotation& other) + { + using numext::conj; + return JacobiRotation(m_c * other.m_c - conj(m_s) * other.m_s, + conj(m_c * conj(other.m_s) + conj(m_s) * conj(other.m_c))); + } + + /** Returns the transposed transformation */ + EIGEN_DEVICE_FUNC + JacobiRotation transpose() const { using numext::conj; return JacobiRotation(m_c, -conj(m_s)); } + + /** Returns the adjoint transformation */ + EIGEN_DEVICE_FUNC + JacobiRotation adjoint() const { using numext::conj; return JacobiRotation(conj(m_c), -m_s); } + + template + EIGEN_DEVICE_FUNC + bool makeJacobi(const MatrixBase&, Index p, Index q); + EIGEN_DEVICE_FUNC + bool makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z); + + EIGEN_DEVICE_FUNC + void makeGivens(const Scalar& p, const Scalar& q, Scalar* r=0); + + protected: + EIGEN_DEVICE_FUNC + void makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::true_type); + EIGEN_DEVICE_FUNC + void makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::false_type); + + Scalar m_c, m_s; +}; + +/** Makes \c *this as a Jacobi rotation \a J such that applying \a J on both the right and left sides of the selfadjoint 2x2 matrix + * \f$ B = \left ( \begin{array}{cc} x & y \\ \overline y & z \end{array} \right )\f$ yields a diagonal matrix \f$ A = J^* B J \f$ + * + * \sa MatrixBase::makeJacobi(const MatrixBase&, Index, Index), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight() + */ +template +EIGEN_DEVICE_FUNC +bool JacobiRotation::makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z) +{ + using std::sqrt; + using std::abs; + + RealScalar deno = RealScalar(2)*abs(y); + if(deno < (std::numeric_limits::min)()) + { + m_c = Scalar(1); + m_s = Scalar(0); + return false; + } + else + { + RealScalar tau = (x-z)/deno; + RealScalar w = sqrt(numext::abs2(tau) + RealScalar(1)); + RealScalar t; + if(tau>RealScalar(0)) + { + t = RealScalar(1) / (tau + w); + } + else + { + t = RealScalar(1) / (tau - w); + } + RealScalar sign_t = t > RealScalar(0) ? RealScalar(1) : RealScalar(-1); + RealScalar n = RealScalar(1) / sqrt(numext::abs2(t)+RealScalar(1)); + m_s = - sign_t * (numext::conj(y) / abs(y)) * abs(t) * n; + m_c = n; + return true; + } +} + +/** Makes \c *this as a Jacobi rotation \c J such that applying \a J on both the right and left sides of the 2x2 selfadjoint matrix + * \f$ B = \left ( \begin{array}{cc} \text{this}_{pp} & \text{this}_{pq} \\ (\text{this}_{pq})^* & \text{this}_{qq} \end{array} \right )\f$ yields + * a diagonal matrix \f$ A = J^* B J \f$ + * + * Example: \include Jacobi_makeJacobi.cpp + * Output: \verbinclude Jacobi_makeJacobi.out + * + * \sa JacobiRotation::makeJacobi(RealScalar, Scalar, RealScalar), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight() + */ +template +template +EIGEN_DEVICE_FUNC +inline bool JacobiRotation::makeJacobi(const MatrixBase& m, Index p, Index q) +{ + return makeJacobi(numext::real(m.coeff(p,p)), m.coeff(p,q), numext::real(m.coeff(q,q))); +} + +/** Makes \c *this as a Givens rotation \c G such that applying \f$ G^* \f$ to the left of the vector + * \f$ V = \left ( \begin{array}{c} p \\ q \end{array} \right )\f$ yields: + * \f$ G^* V = \left ( \begin{array}{c} r \\ 0 \end{array} \right )\f$. + * + * The value of \a r is returned if \a r is not null (the default is null). + * Also note that G is built such that the cosine is always real. + * + * Example: \include Jacobi_makeGivens.cpp + * Output: \verbinclude Jacobi_makeGivens.out + * + * This function implements the continuous Givens rotation generation algorithm + * found in Anderson (2000), Discontinuous Plane Rotations and the Symmetric Eigenvalue Problem. + * LAPACK Working Note 150, University of Tennessee, UT-CS-00-454, December 4, 2000. + * + * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight() + */ +template +EIGEN_DEVICE_FUNC +void JacobiRotation::makeGivens(const Scalar& p, const Scalar& q, Scalar* r) +{ + makeGivens(p, q, r, typename internal::conditional::IsComplex, internal::true_type, internal::false_type>::type()); +} + + +// specialization for complexes +template +EIGEN_DEVICE_FUNC +void JacobiRotation::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::true_type) +{ + using std::sqrt; + using std::abs; + using numext::conj; + + if(q==Scalar(0)) + { + m_c = numext::real(p)<0 ? Scalar(-1) : Scalar(1); + m_s = 0; + if(r) *r = m_c * p; + } + else if(p==Scalar(0)) + { + m_c = 0; + m_s = -q/abs(q); + if(r) *r = abs(q); + } + else + { + RealScalar p1 = numext::norm1(p); + RealScalar q1 = numext::norm1(q); + if(p1>=q1) + { + Scalar ps = p / p1; + RealScalar p2 = numext::abs2(ps); + Scalar qs = q / p1; + RealScalar q2 = numext::abs2(qs); + + RealScalar u = sqrt(RealScalar(1) + q2/p2); + if(numext::real(p) +EIGEN_DEVICE_FUNC +void JacobiRotation::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::false_type) +{ + using std::sqrt; + using std::abs; + if(q==Scalar(0)) + { + m_c = p abs(q)) + { + Scalar t = q/p; + Scalar u = sqrt(Scalar(1) + numext::abs2(t)); + if(p +EIGEN_DEVICE_FUNC +void apply_rotation_in_the_plane(DenseBase& xpr_x, DenseBase& xpr_y, const JacobiRotation& j); +} + +/** \jacobi_module + * Applies the rotation in the plane \a j to the rows \a p and \a q of \c *this, i.e., it computes B = J * B, + * with \f$ B = \left ( \begin{array}{cc} \text{*this.row}(p) \\ \text{*this.row}(q) \end{array} \right ) \f$. + * + * \sa class JacobiRotation, MatrixBase::applyOnTheRight(), internal::apply_rotation_in_the_plane() + */ +template +template +EIGEN_DEVICE_FUNC +inline void MatrixBase::applyOnTheLeft(Index p, Index q, const JacobiRotation& j) +{ + RowXpr x(this->row(p)); + RowXpr y(this->row(q)); + internal::apply_rotation_in_the_plane(x, y, j); +} + +/** \ingroup Jacobi_Module + * Applies the rotation in the plane \a j to the columns \a p and \a q of \c *this, i.e., it computes B = B * J + * with \f$ B = \left ( \begin{array}{cc} \text{*this.col}(p) & \text{*this.col}(q) \end{array} \right ) \f$. + * + * \sa class JacobiRotation, MatrixBase::applyOnTheLeft(), internal::apply_rotation_in_the_plane() + */ +template +template +EIGEN_DEVICE_FUNC +inline void MatrixBase::applyOnTheRight(Index p, Index q, const JacobiRotation& j) +{ + ColXpr x(this->col(p)); + ColXpr y(this->col(q)); + internal::apply_rotation_in_the_plane(x, y, j.transpose()); +} + +namespace internal { + +template +struct apply_rotation_in_the_plane_selector +{ + static EIGEN_DEVICE_FUNC + inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s) + { + for(Index i=0; i +struct apply_rotation_in_the_plane_selector +{ + static inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s) + { + enum { + PacketSize = packet_traits::size, + OtherPacketSize = packet_traits::size + }; + typedef typename packet_traits::type Packet; + typedef typename packet_traits::type OtherPacket; + + /*** dynamic-size vectorized paths ***/ + if(SizeAtCompileTime == Dynamic && ((incrx==1 && incry==1) || PacketSize == 1)) + { + // both vectors are sequentially stored in memory => vectorization + enum { Peeling = 2 }; + + Index alignedStart = internal::first_default_aligned(y, size); + Index alignedEnd = alignedStart + ((size-alignedStart)/PacketSize)*PacketSize; + + const OtherPacket pc = pset1(c); + const OtherPacket ps = pset1(s); + conj_helper::IsComplex,false> pcj; + conj_helper pm; + + for(Index i=0; i(px); + Packet yi = pload(py); + pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi))); + pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi))); + px += PacketSize; + py += PacketSize; + } + } + else + { + Index peelingEnd = alignedStart + ((size-alignedStart)/(Peeling*PacketSize))*(Peeling*PacketSize); + for(Index i=alignedStart; i(px); + Packet xi1 = ploadu(px+PacketSize); + Packet yi = pload (py); + Packet yi1 = pload (py+PacketSize); + pstoreu(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi))); + pstoreu(px+PacketSize, padd(pm.pmul(pc,xi1),pcj.pmul(ps,yi1))); + pstore (py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi))); + pstore (py+PacketSize, psub(pcj.pmul(pc,yi1),pm.pmul(ps,xi1))); + px += Peeling*PacketSize; + py += Peeling*PacketSize; + } + if(alignedEnd!=peelingEnd) + { + Packet xi = ploadu(x+peelingEnd); + Packet yi = pload (y+peelingEnd); + pstoreu(x+peelingEnd, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi))); + pstore (y+peelingEnd, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi))); + } + } + + for(Index i=alignedEnd; i0) // FIXME should be compared to the required alignment + { + const OtherPacket pc = pset1(c); + const OtherPacket ps = pset1(s); + conj_helper::IsComplex,false> pcj; + conj_helper pm; + Scalar* EIGEN_RESTRICT px = x; + Scalar* EIGEN_RESTRICT py = y; + for(Index i=0; i(px); + Packet yi = pload(py); + pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi))); + pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi))); + px += PacketSize; + py += PacketSize; + } + } + + /*** non-vectorized path ***/ + else + { + apply_rotation_in_the_plane_selector::run(x,incrx,y,incry,size,c,s); + } + } +}; + +template +EIGEN_DEVICE_FUNC +void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(DenseBase& xpr_x, DenseBase& xpr_y, const JacobiRotation& j) +{ + typedef typename VectorX::Scalar Scalar; + const bool Vectorizable = (int(VectorX::Flags) & int(VectorY::Flags) & PacketAccessBit) + && (int(packet_traits::size) == int(packet_traits::size)); + + eigen_assert(xpr_x.size() == xpr_y.size()); + Index size = xpr_x.size(); + Index incrx = xpr_x.derived().innerStride(); + Index incry = xpr_y.derived().innerStride(); + + Scalar* EIGEN_RESTRICT x = &xpr_x.derived().coeffRef(0); + Scalar* EIGEN_RESTRICT y = &xpr_y.derived().coeffRef(0); + + OtherScalar c = j.c(); + OtherScalar s = j.s(); + if (c==OtherScalar(1) && s==OtherScalar(0)) + return; + + apply_rotation_in_the_plane_selector< + Scalar,OtherScalar, + VectorX::SizeAtCompileTime, + EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, evaluator::Alignment), + Vectorizable>::run(x,incrx,y,incry,size,c,s); +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_JACOBI_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/KLUSupport/KLUSupport.h b/vendor/eigen/include/eigen3/Eigen/src/KLUSupport/KLUSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..215db35b03f3019df6f15df235f58e2486042c06 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/KLUSupport/KLUSupport.h @@ -0,0 +1,358 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2017 Kyle Macfarlan +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_KLUSUPPORT_H +#define EIGEN_KLUSUPPORT_H + +namespace Eigen { + +/* TODO extract L, extract U, compute det, etc... */ + +/** \ingroup KLUSupport_Module + * \brief A sparse LU factorization and solver based on KLU + * + * This class allows to solve for A.X = B sparse linear problems via a LU factorization + * using the KLU library. The sparse matrix A must be squared and full rank. + * The vectors or matrices X and B can be either dense or sparse. + * + * \warning The input matrix A should be in a \b compressed and \b column-major form. + * Otherwise an expensive copy will be made. You can call the inexpensive makeCompressed() to get a compressed matrix. + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class UmfPackLU, class SparseLU + */ + + +inline int klu_solve(klu_symbolic *Symbolic, klu_numeric *Numeric, Index ldim, Index nrhs, double B [ ], klu_common *Common, double) { + return klu_solve(Symbolic, Numeric, internal::convert_index(ldim), internal::convert_index(nrhs), B, Common); +} + +inline int klu_solve(klu_symbolic *Symbolic, klu_numeric *Numeric, Index ldim, Index nrhs, std::complexB[], klu_common *Common, std::complex) { + return klu_z_solve(Symbolic, Numeric, internal::convert_index(ldim), internal::convert_index(nrhs), &numext::real_ref(B[0]), Common); +} + +inline int klu_tsolve(klu_symbolic *Symbolic, klu_numeric *Numeric, Index ldim, Index nrhs, double B[], klu_common *Common, double) { + return klu_tsolve(Symbolic, Numeric, internal::convert_index(ldim), internal::convert_index(nrhs), B, Common); +} + +inline int klu_tsolve(klu_symbolic *Symbolic, klu_numeric *Numeric, Index ldim, Index nrhs, std::complexB[], klu_common *Common, std::complex) { + return klu_z_tsolve(Symbolic, Numeric, internal::convert_index(ldim), internal::convert_index(nrhs), &numext::real_ref(B[0]), 0, Common); +} + +inline klu_numeric* klu_factor(int Ap [ ], int Ai [ ], double Ax [ ], klu_symbolic *Symbolic, klu_common *Common, double) { + return klu_factor(Ap, Ai, Ax, Symbolic, Common); +} + +inline klu_numeric* klu_factor(int Ap[], int Ai[], std::complex Ax[], klu_symbolic *Symbolic, klu_common *Common, std::complex) { + return klu_z_factor(Ap, Ai, &numext::real_ref(Ax[0]), Symbolic, Common); +} + + +template +class KLU : public SparseSolverBase > +{ + protected: + typedef SparseSolverBase > Base; + using Base::m_isInitialized; + public: + using Base::_solve_impl; + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef Matrix Vector; + typedef Matrix IntRowVectorType; + typedef Matrix IntColVectorType; + typedef SparseMatrix LUMatrixType; + typedef SparseMatrix KLUMatrixType; + typedef Ref KLUMatrixRef; + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + KLU() + : m_dummy(0,0), mp_matrix(m_dummy) + { + init(); + } + + template + explicit KLU(const InputMatrixType& matrix) + : mp_matrix(matrix) + { + init(); + compute(matrix); + } + + ~KLU() + { + if(m_symbolic) klu_free_symbolic(&m_symbolic,&m_common); + if(m_numeric) klu_free_numeric(&m_numeric,&m_common); + } + + EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return mp_matrix.rows(); } + EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return mp_matrix.cols(); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } +#if 0 // not implemented yet + inline const LUMatrixType& matrixL() const + { + if (m_extractedDataAreDirty) extractData(); + return m_l; + } + + inline const LUMatrixType& matrixU() const + { + if (m_extractedDataAreDirty) extractData(); + return m_u; + } + + inline const IntColVectorType& permutationP() const + { + if (m_extractedDataAreDirty) extractData(); + return m_p; + } + + inline const IntRowVectorType& permutationQ() const + { + if (m_extractedDataAreDirty) extractData(); + return m_q; + } +#endif + /** Computes the sparse Cholesky decomposition of \a matrix + * Note that the matrix should be column-major, and in compressed format for best performance. + * \sa SparseMatrix::makeCompressed(). + */ + template + void compute(const InputMatrixType& matrix) + { + if(m_symbolic) klu_free_symbolic(&m_symbolic, &m_common); + if(m_numeric) klu_free_numeric(&m_numeric, &m_common); + grab(matrix.derived()); + analyzePattern_impl(); + factorize_impl(); + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize(), compute() + */ + template + void analyzePattern(const InputMatrixType& matrix) + { + if(m_symbolic) klu_free_symbolic(&m_symbolic, &m_common); + if(m_numeric) klu_free_numeric(&m_numeric, &m_common); + + grab(matrix.derived()); + + analyzePattern_impl(); + } + + + /** Provides access to the control settings array used by KLU. + * + * See KLU documentation for details. + */ + inline const klu_common& kluCommon() const + { + return m_common; + } + + /** Provides access to the control settings array used by UmfPack. + * + * If this array contains NaN's, the default values are used. + * + * See KLU documentation for details. + */ + inline klu_common& kluCommon() + { + return m_common; + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must has the same sparcity than the matrix on which the pattern anylysis has been performed. + * + * \sa analyzePattern(), compute() + */ + template + void factorize(const InputMatrixType& matrix) + { + eigen_assert(m_analysisIsOk && "KLU: you must first call analyzePattern()"); + if(m_numeric) + klu_free_numeric(&m_numeric,&m_common); + + grab(matrix.derived()); + + factorize_impl(); + } + + /** \internal */ + template + bool _solve_impl(const MatrixBase &b, MatrixBase &x) const; + +#if 0 // not implemented yet + Scalar determinant() const; + + void extractData() const; +#endif + + protected: + + void init() + { + m_info = InvalidInput; + m_isInitialized = false; + m_numeric = 0; + m_symbolic = 0; + m_extractedDataAreDirty = true; + + klu_defaults(&m_common); + } + + void analyzePattern_impl() + { + m_info = InvalidInput; + m_analysisIsOk = false; + m_factorizationIsOk = false; + m_symbolic = klu_analyze(internal::convert_index(mp_matrix.rows()), + const_cast(mp_matrix.outerIndexPtr()), const_cast(mp_matrix.innerIndexPtr()), + &m_common); + if (m_symbolic) { + m_isInitialized = true; + m_info = Success; + m_analysisIsOk = true; + m_extractedDataAreDirty = true; + } + } + + void factorize_impl() + { + + m_numeric = klu_factor(const_cast(mp_matrix.outerIndexPtr()), const_cast(mp_matrix.innerIndexPtr()), const_cast(mp_matrix.valuePtr()), + m_symbolic, &m_common, Scalar()); + + + m_info = m_numeric ? Success : NumericalIssue; + m_factorizationIsOk = m_numeric ? 1 : 0; + m_extractedDataAreDirty = true; + } + + template + void grab(const EigenBase &A) + { + mp_matrix.~KLUMatrixRef(); + ::new (&mp_matrix) KLUMatrixRef(A.derived()); + } + + void grab(const KLUMatrixRef &A) + { + if(&(A.derived()) != &mp_matrix) + { + mp_matrix.~KLUMatrixRef(); + ::new (&mp_matrix) KLUMatrixRef(A); + } + } + + // cached data to reduce reallocation, etc. +#if 0 // not implemented yet + mutable LUMatrixType m_l; + mutable LUMatrixType m_u; + mutable IntColVectorType m_p; + mutable IntRowVectorType m_q; +#endif + + KLUMatrixType m_dummy; + KLUMatrixRef mp_matrix; + + klu_numeric* m_numeric; + klu_symbolic* m_symbolic; + klu_common m_common; + mutable ComputationInfo m_info; + int m_factorizationIsOk; + int m_analysisIsOk; + mutable bool m_extractedDataAreDirty; + + private: + KLU(const KLU& ) { } +}; + +#if 0 // not implemented yet +template +void KLU::extractData() const +{ + if (m_extractedDataAreDirty) + { + eigen_assert(false && "KLU: extractData Not Yet Implemented"); + + // get size of the data + int lnz, unz, rows, cols, nz_udiag; + umfpack_get_lunz(&lnz, &unz, &rows, &cols, &nz_udiag, m_numeric, Scalar()); + + // allocate data + m_l.resize(rows,(std::min)(rows,cols)); + m_l.resizeNonZeros(lnz); + + m_u.resize((std::min)(rows,cols),cols); + m_u.resizeNonZeros(unz); + + m_p.resize(rows); + m_q.resize(cols); + + // extract + umfpack_get_numeric(m_l.outerIndexPtr(), m_l.innerIndexPtr(), m_l.valuePtr(), + m_u.outerIndexPtr(), m_u.innerIndexPtr(), m_u.valuePtr(), + m_p.data(), m_q.data(), 0, 0, 0, m_numeric); + + m_extractedDataAreDirty = false; + } +} + +template +typename KLU::Scalar KLU::determinant() const +{ + eigen_assert(false && "KLU: extractData Not Yet Implemented"); + return Scalar(); +} +#endif + +template +template +bool KLU::_solve_impl(const MatrixBase &b, MatrixBase &x) const +{ + Index rhsCols = b.cols(); + EIGEN_STATIC_ASSERT((XDerived::Flags&RowMajorBit)==0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or analyzePattern()/factorize()"); + + x = b; + int info = klu_solve(m_symbolic, m_numeric, b.rows(), rhsCols, x.const_cast_derived().data(), const_cast(&m_common), Scalar()); + + m_info = info!=0 ? Success : NumericalIssue; + return true; +} + +} // end namespace Eigen + +#endif // EIGEN_KLUSUPPORT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/MetisSupport/MetisSupport.h b/vendor/eigen/include/eigen3/Eigen/src/MetisSupport/MetisSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..4c15304ad636d97b469b1effdbba1b5ddc34e5f8 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/MetisSupport/MetisSupport.h @@ -0,0 +1,137 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +#ifndef METIS_SUPPORT_H +#define METIS_SUPPORT_H + +namespace Eigen { +/** + * Get the fill-reducing ordering from the METIS package + * + * If A is the original matrix and Ap is the permuted matrix, + * the fill-reducing permutation is defined as follows : + * Row (column) i of A is the matperm(i) row (column) of Ap. + * WARNING: As computed by METIS, this corresponds to the vector iperm (instead of perm) + */ +template +class MetisOrdering +{ +public: + typedef PermutationMatrix PermutationType; + typedef Matrix IndexVector; + + template + void get_symmetrized_graph(const MatrixType& A) + { + Index m = A.cols(); + eigen_assert((A.rows() == A.cols()) && "ONLY FOR SQUARED MATRICES"); + // Get the transpose of the input matrix + MatrixType At = A.transpose(); + // Get the number of nonzeros elements in each row/col of At+A + Index TotNz = 0; + IndexVector visited(m); + visited.setConstant(-1); + for (StorageIndex j = 0; j < m; j++) + { + // Compute the union structure of of A(j,:) and At(j,:) + visited(j) = j; // Do not include the diagonal element + // Get the nonzeros in row/column j of A + for (typename MatrixType::InnerIterator it(A, j); it; ++it) + { + Index idx = it.index(); // Get the row index (for column major) or column index (for row major) + if (visited(idx) != j ) + { + visited(idx) = j; + ++TotNz; + } + } + //Get the nonzeros in row/column j of At + for (typename MatrixType::InnerIterator it(At, j); it; ++it) + { + Index idx = it.index(); + if(visited(idx) != j) + { + visited(idx) = j; + ++TotNz; + } + } + } + // Reserve place for A + At + m_indexPtr.resize(m+1); + m_innerIndices.resize(TotNz); + + // Now compute the real adjacency list of each column/row + visited.setConstant(-1); + StorageIndex CurNz = 0; + for (StorageIndex j = 0; j < m; j++) + { + m_indexPtr(j) = CurNz; + + visited(j) = j; // Do not include the diagonal element + // Add the pattern of row/column j of A to A+At + for (typename MatrixType::InnerIterator it(A,j); it; ++it) + { + StorageIndex idx = it.index(); // Get the row index (for column major) or column index (for row major) + if (visited(idx) != j ) + { + visited(idx) = j; + m_innerIndices(CurNz) = idx; + CurNz++; + } + } + //Add the pattern of row/column j of At to A+At + for (typename MatrixType::InnerIterator it(At, j); it; ++it) + { + StorageIndex idx = it.index(); + if(visited(idx) != j) + { + visited(idx) = j; + m_innerIndices(CurNz) = idx; + ++CurNz; + } + } + } + m_indexPtr(m) = CurNz; + } + + template + void operator() (const MatrixType& A, PermutationType& matperm) + { + StorageIndex m = internal::convert_index(A.cols()); // must be StorageIndex, because it is passed by address to METIS + IndexVector perm(m),iperm(m); + // First, symmetrize the matrix graph. + get_symmetrized_graph(A); + int output_error; + + // Call the fill-reducing routine from METIS + output_error = METIS_NodeND(&m, m_indexPtr.data(), m_innerIndices.data(), NULL, NULL, perm.data(), iperm.data()); + + if(output_error != METIS_OK) + { + //FIXME The ordering interface should define a class of possible errors + std::cerr << "ERROR WHILE CALLING THE METIS PACKAGE \n"; + return; + } + + // Get the fill-reducing permutation + //NOTE: If Ap is the permuted matrix then perm and iperm vectors are defined as follows + // Row (column) i of Ap is the perm(i) row(column) of A, and row (column) i of A is the iperm(i) row(column) of Ap + + matperm.resize(m); + for (int j = 0; j < m; j++) + matperm.indices()(iperm(j)) = j; + + } + + protected: + IndexVector m_indexPtr; // Pointer to the adjacenccy list of each row/column + IndexVector m_innerIndices; // Adjacency list +}; + +}// end namespace eigen +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Amd.h b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Amd.h new file mode 100644 index 0000000000000000000000000000000000000000..7ca3f33b12f61258819d7bd2bf8fe3222397aace --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Amd.h @@ -0,0 +1,435 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* +NOTE: this routine has been adapted from the CSparse library: + +Copyright (c) 2006, Timothy A. Davis. +http://www.suitesparse.com + +The author of CSparse, Timothy A. Davis., has executed a license with Google LLC +to permit distribution of this code and derivative works as part of Eigen under +the Mozilla Public License v. 2.0, as stated at the top of this file. +*/ + +#ifndef EIGEN_SPARSE_AMD_H +#define EIGEN_SPARSE_AMD_H + +namespace Eigen { + +namespace internal { + +template inline T amd_flip(const T& i) { return -i-2; } +template inline T amd_unflip(const T& i) { return i<0 ? amd_flip(i) : i; } +template inline bool amd_marked(const T0* w, const T1& j) { return w[j]<0; } +template inline void amd_mark(const T0* w, const T1& j) { return w[j] = amd_flip(w[j]); } + +/* clear w */ +template +static StorageIndex cs_wclear (StorageIndex mark, StorageIndex lemax, StorageIndex *w, StorageIndex n) +{ + StorageIndex k; + if(mark < 2 || (mark + lemax < 0)) + { + for(k = 0; k < n; k++) + if(w[k] != 0) + w[k] = 1; + mark = 2; + } + return (mark); /* at this point, w[0..n-1] < mark holds */ +} + +/* depth-first search and postorder of a tree rooted at node j */ +template +StorageIndex cs_tdfs(StorageIndex j, StorageIndex k, StorageIndex *head, const StorageIndex *next, StorageIndex *post, StorageIndex *stack) +{ + StorageIndex i, p, top = 0; + if(!head || !next || !post || !stack) return (-1); /* check inputs */ + stack[0] = j; /* place j on the stack */ + while (top >= 0) /* while (stack is not empty) */ + { + p = stack[top]; /* p = top of stack */ + i = head[p]; /* i = youngest child of p */ + if(i == -1) + { + top--; /* p has no unordered children left */ + post[k++] = p; /* node p is the kth postordered node */ + } + else + { + head[p] = next[i]; /* remove i from children of p */ + stack[++top] = i; /* start dfs on child node i */ + } + } + return k; +} + + +/** \internal + * \ingroup OrderingMethods_Module + * Approximate minimum degree ordering algorithm. + * + * \param[in] C the input selfadjoint matrix stored in compressed column major format. + * \param[out] perm the permutation P reducing the fill-in of the input matrix \a C + * + * Note that the input matrix \a C must be complete, that is both the upper and lower parts have to be stored, as well as the diagonal entries. + * On exit the values of C are destroyed */ +template +void minimum_degree_ordering(SparseMatrix& C, PermutationMatrix& perm) +{ + using std::sqrt; + + StorageIndex d, dk, dext, lemax = 0, e, elenk, eln, i, j, k, k1, + k2, k3, jlast, ln, dense, nzmax, mindeg = 0, nvi, nvj, nvk, mark, wnvi, + ok, nel = 0, p, p1, p2, p3, p4, pj, pk, pk1, pk2, pn, q, t, h; + + StorageIndex n = StorageIndex(C.cols()); + dense = std::max (16, StorageIndex(10 * sqrt(double(n)))); /* find dense threshold */ + dense = (std::min)(n-2, dense); + + StorageIndex cnz = StorageIndex(C.nonZeros()); + perm.resize(n+1); + t = cnz + cnz/5 + 2*n; /* add elbow room to C */ + C.resizeNonZeros(t); + + // get workspace + ei_declare_aligned_stack_constructed_variable(StorageIndex,W,8*(n+1),0); + StorageIndex* len = W; + StorageIndex* nv = W + (n+1); + StorageIndex* next = W + 2*(n+1); + StorageIndex* head = W + 3*(n+1); + StorageIndex* elen = W + 4*(n+1); + StorageIndex* degree = W + 5*(n+1); + StorageIndex* w = W + 6*(n+1); + StorageIndex* hhead = W + 7*(n+1); + StorageIndex* last = perm.indices().data(); /* use P as workspace for last */ + + /* --- Initialize quotient graph ---------------------------------------- */ + StorageIndex* Cp = C.outerIndexPtr(); + StorageIndex* Ci = C.innerIndexPtr(); + for(k = 0; k < n; k++) + len[k] = Cp[k+1] - Cp[k]; + len[n] = 0; + nzmax = t; + + for(i = 0; i <= n; i++) + { + head[i] = -1; // degree list i is empty + last[i] = -1; + next[i] = -1; + hhead[i] = -1; // hash list i is empty + nv[i] = 1; // node i is just one node + w[i] = 1; // node i is alive + elen[i] = 0; // Ek of node i is empty + degree[i] = len[i]; // degree of node i + } + mark = internal::cs_wclear(0, 0, w, n); /* clear w */ + + /* --- Initialize degree lists ------------------------------------------ */ + for(i = 0; i < n; i++) + { + bool has_diag = false; + for(p = Cp[i]; p dense || !has_diag) /* node i is dense or has no structural diagonal element */ + { + nv[i] = 0; /* absorb i into element n */ + elen[i] = -1; /* node i is dead */ + nel++; + Cp[i] = amd_flip (n); + nv[n]++; + } + else + { + if(head[d] != -1) last[head[d]] = i; + next[i] = head[d]; /* put node i in degree list d */ + head[d] = i; + } + } + + elen[n] = -2; /* n is a dead element */ + Cp[n] = -1; /* n is a root of assembly tree */ + w[n] = 0; /* n is a dead element */ + + while (nel < n) /* while (selecting pivots) do */ + { + /* --- Select node of minimum approximate degree -------------------- */ + for(k = -1; mindeg < n && (k = head[mindeg]) == -1; mindeg++) {} + if(next[k] != -1) last[next[k]] = -1; + head[mindeg] = next[k]; /* remove k from degree list */ + elenk = elen[k]; /* elenk = |Ek| */ + nvk = nv[k]; /* # of nodes k represents */ + nel += nvk; /* nv[k] nodes of A eliminated */ + + /* --- Garbage collection ------------------------------------------- */ + if(elenk > 0 && cnz + mindeg >= nzmax) + { + for(j = 0; j < n; j++) + { + if((p = Cp[j]) >= 0) /* j is a live node or element */ + { + Cp[j] = Ci[p]; /* save first entry of object */ + Ci[p] = amd_flip (j); /* first entry is now amd_flip(j) */ + } + } + for(q = 0, p = 0; p < cnz; ) /* scan all of memory */ + { + if((j = amd_flip (Ci[p++])) >= 0) /* found object j */ + { + Ci[q] = Cp[j]; /* restore first entry of object */ + Cp[j] = q++; /* new pointer to object j */ + for(k3 = 0; k3 < len[j]-1; k3++) Ci[q++] = Ci[p++]; + } + } + cnz = q; /* Ci[cnz...nzmax-1] now free */ + } + + /* --- Construct new element ---------------------------------------- */ + dk = 0; + nv[k] = -nvk; /* flag k as in Lk */ + p = Cp[k]; + pk1 = (elenk == 0) ? p : cnz; /* do in place if elen[k] == 0 */ + pk2 = pk1; + for(k1 = 1; k1 <= elenk + 1; k1++) + { + if(k1 > elenk) + { + e = k; /* search the nodes in k */ + pj = p; /* list of nodes starts at Ci[pj]*/ + ln = len[k] - elenk; /* length of list of nodes in k */ + } + else + { + e = Ci[p++]; /* search the nodes in e */ + pj = Cp[e]; + ln = len[e]; /* length of list of nodes in e */ + } + for(k2 = 1; k2 <= ln; k2++) + { + i = Ci[pj++]; + if((nvi = nv[i]) <= 0) continue; /* node i dead, or seen */ + dk += nvi; /* degree[Lk] += size of node i */ + nv[i] = -nvi; /* negate nv[i] to denote i in Lk*/ + Ci[pk2++] = i; /* place i in Lk */ + if(next[i] != -1) last[next[i]] = last[i]; + if(last[i] != -1) /* remove i from degree list */ + { + next[last[i]] = next[i]; + } + else + { + head[degree[i]] = next[i]; + } + } + if(e != k) + { + Cp[e] = amd_flip (k); /* absorb e into k */ + w[e] = 0; /* e is now a dead element */ + } + } + if(elenk != 0) cnz = pk2; /* Ci[cnz...nzmax] is free */ + degree[k] = dk; /* external degree of k - |Lk\i| */ + Cp[k] = pk1; /* element k is in Ci[pk1..pk2-1] */ + len[k] = pk2 - pk1; + elen[k] = -2; /* k is now an element */ + + /* --- Find set differences ----------------------------------------- */ + mark = internal::cs_wclear(mark, lemax, w, n); /* clear w if necessary */ + for(pk = pk1; pk < pk2; pk++) /* scan 1: find |Le\Lk| */ + { + i = Ci[pk]; + if((eln = elen[i]) <= 0) continue;/* skip if elen[i] empty */ + nvi = -nv[i]; /* nv[i] was negated */ + wnvi = mark - nvi; + for(p = Cp[i]; p <= Cp[i] + eln - 1; p++) /* scan Ei */ + { + e = Ci[p]; + if(w[e] >= mark) + { + w[e] -= nvi; /* decrement |Le\Lk| */ + } + else if(w[e] != 0) /* ensure e is a live element */ + { + w[e] = degree[e] + wnvi; /* 1st time e seen in scan 1 */ + } + } + } + + /* --- Degree update ------------------------------------------------ */ + for(pk = pk1; pk < pk2; pk++) /* scan2: degree update */ + { + i = Ci[pk]; /* consider node i in Lk */ + p1 = Cp[i]; + p2 = p1 + elen[i] - 1; + pn = p1; + for(h = 0, d = 0, p = p1; p <= p2; p++) /* scan Ei */ + { + e = Ci[p]; + if(w[e] != 0) /* e is an unabsorbed element */ + { + dext = w[e] - mark; /* dext = |Le\Lk| */ + if(dext > 0) + { + d += dext; /* sum up the set differences */ + Ci[pn++] = e; /* keep e in Ei */ + h += e; /* compute the hash of node i */ + } + else + { + Cp[e] = amd_flip (k); /* aggressive absorb. e->k */ + w[e] = 0; /* e is a dead element */ + } + } + } + elen[i] = pn - p1 + 1; /* elen[i] = |Ei| */ + p3 = pn; + p4 = p1 + len[i]; + for(p = p2 + 1; p < p4; p++) /* prune edges in Ai */ + { + j = Ci[p]; + if((nvj = nv[j]) <= 0) continue; /* node j dead or in Lk */ + d += nvj; /* degree(i) += |j| */ + Ci[pn++] = j; /* place j in node list of i */ + h += j; /* compute hash for node i */ + } + if(d == 0) /* check for mass elimination */ + { + Cp[i] = amd_flip (k); /* absorb i into k */ + nvi = -nv[i]; + dk -= nvi; /* |Lk| -= |i| */ + nvk += nvi; /* |k| += nv[i] */ + nel += nvi; + nv[i] = 0; + elen[i] = -1; /* node i is dead */ + } + else + { + degree[i] = std::min (degree[i], d); /* update degree(i) */ + Ci[pn] = Ci[p3]; /* move first node to end */ + Ci[p3] = Ci[p1]; /* move 1st el. to end of Ei */ + Ci[p1] = k; /* add k as 1st element in of Ei */ + len[i] = pn - p1 + 1; /* new len of adj. list of node i */ + h %= n; /* finalize hash of i */ + next[i] = hhead[h]; /* place i in hash bucket */ + hhead[h] = i; + last[i] = h; /* save hash of i in last[i] */ + } + } /* scan2 is done */ + degree[k] = dk; /* finalize |Lk| */ + lemax = std::max(lemax, dk); + mark = internal::cs_wclear(mark+lemax, lemax, w, n); /* clear w */ + + /* --- Supernode detection ------------------------------------------ */ + for(pk = pk1; pk < pk2; pk++) + { + i = Ci[pk]; + if(nv[i] >= 0) continue; /* skip if i is dead */ + h = last[i]; /* scan hash bucket of node i */ + i = hhead[h]; + hhead[h] = -1; /* hash bucket will be empty */ + for(; i != -1 && next[i] != -1; i = next[i], mark++) + { + ln = len[i]; + eln = elen[i]; + for(p = Cp[i]+1; p <= Cp[i] + ln-1; p++) w[Ci[p]] = mark; + jlast = i; + for(j = next[i]; j != -1; ) /* compare i with all j */ + { + ok = (len[j] == ln) && (elen[j] == eln); + for(p = Cp[j] + 1; ok && p <= Cp[j] + ln - 1; p++) + { + if(w[Ci[p]] != mark) ok = 0; /* compare i and j*/ + } + if(ok) /* i and j are identical */ + { + Cp[j] = amd_flip (i); /* absorb j into i */ + nv[i] += nv[j]; + nv[j] = 0; + elen[j] = -1; /* node j is dead */ + j = next[j]; /* delete j from hash bucket */ + next[jlast] = j; + } + else + { + jlast = j; /* j and i are different */ + j = next[j]; + } + } + } + } + + /* --- Finalize new element------------------------------------------ */ + for(p = pk1, pk = pk1; pk < pk2; pk++) /* finalize Lk */ + { + i = Ci[pk]; + if((nvi = -nv[i]) <= 0) continue;/* skip if i is dead */ + nv[i] = nvi; /* restore nv[i] */ + d = degree[i] + dk - nvi; /* compute external degree(i) */ + d = std::min (d, n - nel - nvi); + if(head[d] != -1) last[head[d]] = i; + next[i] = head[d]; /* put i back in degree list */ + last[i] = -1; + head[d] = i; + mindeg = std::min (mindeg, d); /* find new minimum degree */ + degree[i] = d; + Ci[p++] = i; /* place i in Lk */ + } + nv[k] = nvk; /* # nodes absorbed into k */ + if((len[k] = p-pk1) == 0) /* length of adj list of element k*/ + { + Cp[k] = -1; /* k is a root of the tree */ + w[k] = 0; /* k is now a dead element */ + } + if(elenk != 0) cnz = p; /* free unused space in Lk */ + } + + /* --- Postordering ----------------------------------------------------- */ + for(i = 0; i < n; i++) Cp[i] = amd_flip (Cp[i]);/* fix assembly tree */ + for(j = 0; j <= n; j++) head[j] = -1; + for(j = n; j >= 0; j--) /* place unordered nodes in lists */ + { + if(nv[j] > 0) continue; /* skip if j is an element */ + next[j] = head[Cp[j]]; /* place j in list of its parent */ + head[Cp[j]] = j; + } + for(e = n; e >= 0; e--) /* place elements in lists */ + { + if(nv[e] <= 0) continue; /* skip unless e is an element */ + if(Cp[e] != -1) + { + next[e] = head[Cp[e]]; /* place e in list of its parent */ + head[Cp[e]] = e; + } + } + for(k = 0, i = 0; i <= n; i++) /* postorder the assembly tree */ + { + if(Cp[i] == -1) k = internal::cs_tdfs(i, k, head, next, perm.indices().data(), w); + } + + perm.indices().conservativeResize(n); +} + +} // namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSE_AMD_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Eigen_Colamd.h b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Eigen_Colamd.h new file mode 100644 index 0000000000000000000000000000000000000000..8e339a704a1812c368e19f445aaec7deda219eb2 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Eigen_Colamd.h @@ -0,0 +1,1863 @@ +// // This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Desire Nuentsa Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// This file is modified from the colamd/symamd library. The copyright is below + +// The authors of the code itself are Stefan I. Larimore and Timothy A. +// Davis (davis@cise.ufl.edu), University of Florida. The algorithm was +// developed in collaboration with John Gilbert, Xerox PARC, and Esmond +// Ng, Oak Ridge National Laboratory. +// +// Date: +// +// September 8, 2003. Version 2.3. +// +// Acknowledgements: +// +// This work was supported by the National Science Foundation, under +// grants DMS-9504974 and DMS-9803599. +// +// Notice: +// +// Copyright (c) 1998-2003 by the University of Florida. +// All Rights Reserved. +// +// THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY +// EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. +// +// Permission is hereby granted to use, copy, modify, and/or distribute +// this program, provided that the Copyright, this License, and the +// Availability of the original version is retained on all copies and made +// accessible to the end-user of any code or package that includes COLAMD +// or any modified version of COLAMD. +// +// Availability: +// +// The colamd/symamd library is available at +// +// http://www.suitesparse.com + + +#ifndef EIGEN_COLAMD_H +#define EIGEN_COLAMD_H + +namespace internal { + +namespace Colamd { + +/* Ensure that debugging is turned off: */ +#ifndef COLAMD_NDEBUG +#define COLAMD_NDEBUG +#endif /* NDEBUG */ + + +/* ========================================================================== */ +/* === Knob and statistics definitions ====================================== */ +/* ========================================================================== */ + +/* size of the knobs [ ] array. Only knobs [0..1] are currently used. */ +const int NKnobs = 20; + +/* number of output statistics. Only stats [0..6] are currently used. */ +const int NStats = 20; + +/* Indices into knobs and stats array. */ +enum KnobsStatsIndex { + /* knobs [0] and stats [0]: dense row knob and output statistic. */ + DenseRow = 0, + + /* knobs [1] and stats [1]: dense column knob and output statistic. */ + DenseCol = 1, + + /* stats [2]: memory defragmentation count output statistic */ + DefragCount = 2, + + /* stats [3]: colamd status: zero OK, > 0 warning or notice, < 0 error */ + Status = 3, + + /* stats [4..6]: error info, or info on jumbled columns */ + Info1 = 4, + Info2 = 5, + Info3 = 6 +}; + +/* error codes returned in stats [3]: */ +enum Status { + Ok = 0, + OkButJumbled = 1, + ErrorANotPresent = -1, + ErrorPNotPresent = -2, + ErrorNrowNegative = -3, + ErrorNcolNegative = -4, + ErrorNnzNegative = -5, + ErrorP0Nonzero = -6, + ErrorATooSmall = -7, + ErrorColLengthNegative = -8, + ErrorRowIndexOutOfBounds = -9, + ErrorOutOfMemory = -10, + ErrorInternalError = -999 +}; +/* ========================================================================== */ +/* === Definitions ========================================================== */ +/* ========================================================================== */ + +template +IndexType ones_complement(const IndexType r) { + return (-(r)-1); +} + +/* -------------------------------------------------------------------------- */ +const int Empty = -1; + +/* Row and column status */ +enum RowColumnStatus { + Alive = 0, + Dead = -1 +}; + +/* Column status */ +enum ColumnStatus { + DeadPrincipal = -1, + DeadNonPrincipal = -2 +}; + +/* ========================================================================== */ +/* === Colamd reporting mechanism =========================================== */ +/* ========================================================================== */ + +// == Row and Column structures == +template +struct ColStructure +{ + IndexType start ; /* index for A of first row in this column, or Dead */ + /* if column is dead */ + IndexType length ; /* number of rows in this column */ + union + { + IndexType thickness ; /* number of original columns represented by this */ + /* col, if the column is alive */ + IndexType parent ; /* parent in parent tree super-column structure, if */ + /* the column is dead */ + } shared1 ; + union + { + IndexType score ; /* the score used to maintain heap, if col is alive */ + IndexType order ; /* pivot ordering of this column, if col is dead */ + } shared2 ; + union + { + IndexType headhash ; /* head of a hash bucket, if col is at the head of */ + /* a degree list */ + IndexType hash ; /* hash value, if col is not in a degree list */ + IndexType prev ; /* previous column in degree list, if col is in a */ + /* degree list (but not at the head of a degree list) */ + } shared3 ; + union + { + IndexType degree_next ; /* next column, if col is in a degree list */ + IndexType hash_next ; /* next column, if col is in a hash list */ + } shared4 ; + + inline bool is_dead() const { return start < Alive; } + + inline bool is_alive() const { return start >= Alive; } + + inline bool is_dead_principal() const { return start == DeadPrincipal; } + + inline void kill_principal() { start = DeadPrincipal; } + + inline void kill_non_principal() { start = DeadNonPrincipal; } + +}; + +template +struct RowStructure +{ + IndexType start ; /* index for A of first col in this row */ + IndexType length ; /* number of principal columns in this row */ + union + { + IndexType degree ; /* number of principal & non-principal columns in row */ + IndexType p ; /* used as a row pointer in init_rows_cols () */ + } shared1 ; + union + { + IndexType mark ; /* for computing set differences and marking dead rows*/ + IndexType first_column ;/* first column in row (used in garbage collection) */ + } shared2 ; + + inline bool is_dead() const { return shared2.mark < Alive; } + + inline bool is_alive() const { return shared2.mark >= Alive; } + + inline void kill() { shared2.mark = Dead; } + +}; + +/* ========================================================================== */ +/* === Colamd recommended memory size ======================================= */ +/* ========================================================================== */ + +/* + The recommended length Alen of the array A passed to colamd is given by + the COLAMD_RECOMMENDED (nnz, n_row, n_col) macro. It returns -1 if any + argument is negative. 2*nnz space is required for the row and column + indices of the matrix. colamd_c (n_col) + colamd_r (n_row) space is + required for the Col and Row arrays, respectively, which are internal to + colamd. An additional n_col space is the minimal amount of "elbow room", + and nnz/5 more space is recommended for run time efficiency. + + This macro is not needed when using symamd. + + Explicit typecast to IndexType added Sept. 23, 2002, COLAMD version 2.2, to avoid + gcc -pedantic warning messages. +*/ +template +inline IndexType colamd_c(IndexType n_col) +{ return IndexType( ((n_col) + 1) * sizeof (ColStructure) / sizeof (IndexType) ) ; } + +template +inline IndexType colamd_r(IndexType n_row) +{ return IndexType(((n_row) + 1) * sizeof (RowStructure) / sizeof (IndexType)); } + +// Prototypes of non-user callable routines +template +static IndexType init_rows_cols (IndexType n_row, IndexType n_col, RowStructure Row [], ColStructure col [], IndexType A [], IndexType p [], IndexType stats[NStats] ); + +template +static void init_scoring (IndexType n_row, IndexType n_col, RowStructure Row [], ColStructure Col [], IndexType A [], IndexType head [], double knobs[NKnobs], IndexType *p_n_row2, IndexType *p_n_col2, IndexType *p_max_deg); + +template +static IndexType find_ordering (IndexType n_row, IndexType n_col, IndexType Alen, RowStructure Row [], ColStructure Col [], IndexType A [], IndexType head [], IndexType n_col2, IndexType max_deg, IndexType pfree); + +template +static void order_children (IndexType n_col, ColStructure Col [], IndexType p []); + +template +static void detect_super_cols (ColStructure Col [], IndexType A [], IndexType head [], IndexType row_start, IndexType row_length ) ; + +template +static IndexType garbage_collection (IndexType n_row, IndexType n_col, RowStructure Row [], ColStructure Col [], IndexType A [], IndexType *pfree) ; + +template +static inline IndexType clear_mark (IndexType n_row, RowStructure Row [] ) ; + +/* === No debugging ========================================================= */ + +#define COLAMD_DEBUG0(params) ; +#define COLAMD_DEBUG1(params) ; +#define COLAMD_DEBUG2(params) ; +#define COLAMD_DEBUG3(params) ; +#define COLAMD_DEBUG4(params) ; + +#define COLAMD_ASSERT(expression) ((void) 0) + + +/** + * \brief Returns the recommended value of Alen + * + * Returns recommended value of Alen for use by colamd. + * Returns -1 if any input argument is negative. + * The use of this routine or macro is optional. + * Note that the macro uses its arguments more than once, + * so be careful for side effects, if you pass expressions as arguments to COLAMD_RECOMMENDED. + * + * \param nnz nonzeros in A + * \param n_row number of rows in A + * \param n_col number of columns in A + * \return recommended value of Alen for use by colamd + */ +template +inline IndexType recommended ( IndexType nnz, IndexType n_row, IndexType n_col) +{ + if ((nnz) < 0 || (n_row) < 0 || (n_col) < 0) + return (-1); + else + return (2 * (nnz) + colamd_c (n_col) + colamd_r (n_row) + (n_col) + ((nnz) / 5)); +} + +/** + * \brief set default parameters The use of this routine is optional. + * + * Colamd: rows with more than (knobs [DenseRow] * n_col) + * entries are removed prior to ordering. Columns with more than + * (knobs [DenseCol] * n_row) entries are removed prior to + * ordering, and placed last in the output column ordering. + * + * DenseRow and DenseCol are defined as 0 and 1, + * respectively, in colamd.h. Default values of these two knobs + * are both 0.5. Currently, only knobs [0] and knobs [1] are + * used, but future versions may use more knobs. If so, they will + * be properly set to their defaults by the future version of + * colamd_set_defaults, so that the code that calls colamd will + * not need to change, assuming that you either use + * colamd_set_defaults, or pass a (double *) NULL pointer as the + * knobs array to colamd or symamd. + * + * \param knobs parameter settings for colamd + */ + +static inline void set_defaults(double knobs[NKnobs]) +{ + /* === Local variables ================================================== */ + + int i ; + + if (!knobs) + { + return ; /* no knobs to initialize */ + } + for (i = 0 ; i < NKnobs ; i++) + { + knobs [i] = 0 ; + } + knobs [Colamd::DenseRow] = 0.5 ; /* ignore rows over 50% dense */ + knobs [Colamd::DenseCol] = 0.5 ; /* ignore columns over 50% dense */ +} + +/** + * \brief Computes a column ordering using the column approximate minimum degree ordering + * + * Computes a column ordering (Q) of A such that P(AQ)=LU or + * (AQ)'AQ=LL' have less fill-in and require fewer floating point + * operations than factorizing the unpermuted matrix A or A'A, + * respectively. + * + * + * \param n_row number of rows in A + * \param n_col number of columns in A + * \param Alen, size of the array A + * \param A row indices of the matrix, of size ALen + * \param p column pointers of A, of size n_col+1 + * \param knobs parameter settings for colamd + * \param stats colamd output statistics and error codes + */ +template +static bool compute_ordering(IndexType n_row, IndexType n_col, IndexType Alen, IndexType *A, IndexType *p, double knobs[NKnobs], IndexType stats[NStats]) +{ + /* === Local variables ================================================== */ + + IndexType i ; /* loop index */ + IndexType nnz ; /* nonzeros in A */ + IndexType Row_size ; /* size of Row [], in integers */ + IndexType Col_size ; /* size of Col [], in integers */ + IndexType need ; /* minimum required length of A */ + Colamd::RowStructure *Row ; /* pointer into A of Row [0..n_row] array */ + Colamd::ColStructure *Col ; /* pointer into A of Col [0..n_col] array */ + IndexType n_col2 ; /* number of non-dense, non-empty columns */ + IndexType n_row2 ; /* number of non-dense, non-empty rows */ + IndexType ngarbage ; /* number of garbage collections performed */ + IndexType max_deg ; /* maximum row degree */ + double default_knobs [NKnobs] ; /* default knobs array */ + + + /* === Check the input arguments ======================================== */ + + if (!stats) + { + COLAMD_DEBUG0 (("colamd: stats not present\n")) ; + return (false) ; + } + for (i = 0 ; i < NStats ; i++) + { + stats [i] = 0 ; + } + stats [Colamd::Status] = Colamd::Ok ; + stats [Colamd::Info1] = -1 ; + stats [Colamd::Info2] = -1 ; + + if (!A) /* A is not present */ + { + stats [Colamd::Status] = Colamd::ErrorANotPresent ; + COLAMD_DEBUG0 (("colamd: A not present\n")) ; + return (false) ; + } + + if (!p) /* p is not present */ + { + stats [Colamd::Status] = Colamd::ErrorPNotPresent ; + COLAMD_DEBUG0 (("colamd: p not present\n")) ; + return (false) ; + } + + if (n_row < 0) /* n_row must be >= 0 */ + { + stats [Colamd::Status] = Colamd::ErrorNrowNegative ; + stats [Colamd::Info1] = n_row ; + COLAMD_DEBUG0 (("colamd: nrow negative %d\n", n_row)) ; + return (false) ; + } + + if (n_col < 0) /* n_col must be >= 0 */ + { + stats [Colamd::Status] = Colamd::ErrorNcolNegative ; + stats [Colamd::Info1] = n_col ; + COLAMD_DEBUG0 (("colamd: ncol negative %d\n", n_col)) ; + return (false) ; + } + + nnz = p [n_col] ; + if (nnz < 0) /* nnz must be >= 0 */ + { + stats [Colamd::Status] = Colamd::ErrorNnzNegative ; + stats [Colamd::Info1] = nnz ; + COLAMD_DEBUG0 (("colamd: number of entries negative %d\n", nnz)) ; + return (false) ; + } + + if (p [0] != 0) + { + stats [Colamd::Status] = Colamd::ErrorP0Nonzero ; + stats [Colamd::Info1] = p [0] ; + COLAMD_DEBUG0 (("colamd: p[0] not zero %d\n", p [0])) ; + return (false) ; + } + + /* === If no knobs, set default knobs =================================== */ + + if (!knobs) + { + set_defaults (default_knobs) ; + knobs = default_knobs ; + } + + /* === Allocate the Row and Col arrays from array A ===================== */ + + Col_size = colamd_c (n_col) ; + Row_size = colamd_r (n_row) ; + need = 2*nnz + n_col + Col_size + Row_size ; + + if (need > Alen) + { + /* not enough space in array A to perform the ordering */ + stats [Colamd::Status] = Colamd::ErrorATooSmall ; + stats [Colamd::Info1] = need ; + stats [Colamd::Info2] = Alen ; + COLAMD_DEBUG0 (("colamd: Need Alen >= %d, given only Alen = %d\n", need,Alen)); + return (false) ; + } + + Alen -= Col_size + Row_size ; + Col = (ColStructure *) &A [Alen] ; + Row = (RowStructure *) &A [Alen + Col_size] ; + + /* === Construct the row and column data structures ===================== */ + + if (!Colamd::init_rows_cols (n_row, n_col, Row, Col, A, p, stats)) + { + /* input matrix is invalid */ + COLAMD_DEBUG0 (("colamd: Matrix invalid\n")) ; + return (false) ; + } + + /* === Initialize scores, kill dense rows/columns ======================= */ + + Colamd::init_scoring (n_row, n_col, Row, Col, A, p, knobs, + &n_row2, &n_col2, &max_deg) ; + + /* === Order the supercolumns =========================================== */ + + ngarbage = Colamd::find_ordering (n_row, n_col, Alen, Row, Col, A, p, + n_col2, max_deg, 2*nnz) ; + + /* === Order the non-principal columns ================================== */ + + Colamd::order_children (n_col, Col, p) ; + + /* === Return statistics in stats ======================================= */ + + stats [Colamd::DenseRow] = n_row - n_row2 ; + stats [Colamd::DenseCol] = n_col - n_col2 ; + stats [Colamd::DefragCount] = ngarbage ; + COLAMD_DEBUG0 (("colamd: done.\n")) ; + return (true) ; +} + +/* ========================================================================== */ +/* === NON-USER-CALLABLE ROUTINES: ========================================== */ +/* ========================================================================== */ + +/* There are no user-callable routines beyond this point in the file */ + +/* ========================================================================== */ +/* === init_rows_cols ======================================================= */ +/* ========================================================================== */ + +/* + Takes the column form of the matrix in A and creates the row form of the + matrix. Also, row and column attributes are stored in the Col and Row + structs. If the columns are un-sorted or contain duplicate row indices, + this routine will also sort and remove duplicate row indices from the + column form of the matrix. Returns false if the matrix is invalid, + true otherwise. Not user-callable. +*/ +template +static IndexType init_rows_cols /* returns true if OK, or false otherwise */ + ( + /* === Parameters ======================================================= */ + + IndexType n_row, /* number of rows of A */ + IndexType n_col, /* number of columns of A */ + RowStructure Row [], /* of size n_row+1 */ + ColStructure Col [], /* of size n_col+1 */ + IndexType A [], /* row indices of A, of size Alen */ + IndexType p [], /* pointers to columns in A, of size n_col+1 */ + IndexType stats [NStats] /* colamd statistics */ + ) +{ + /* === Local variables ================================================== */ + + IndexType col ; /* a column index */ + IndexType row ; /* a row index */ + IndexType *cp ; /* a column pointer */ + IndexType *cp_end ; /* a pointer to the end of a column */ + IndexType *rp ; /* a row pointer */ + IndexType *rp_end ; /* a pointer to the end of a row */ + IndexType last_row ; /* previous row */ + + /* === Initialize columns, and check column pointers ==================== */ + + for (col = 0 ; col < n_col ; col++) + { + Col [col].start = p [col] ; + Col [col].length = p [col+1] - p [col] ; + + if ((Col [col].length) < 0) // extra parentheses to work-around gcc bug 10200 + { + /* column pointers must be non-decreasing */ + stats [Colamd::Status] = Colamd::ErrorColLengthNegative ; + stats [Colamd::Info1] = col ; + stats [Colamd::Info2] = Col [col].length ; + COLAMD_DEBUG0 (("colamd: col %d length %d < 0\n", col, Col [col].length)) ; + return (false) ; + } + + Col [col].shared1.thickness = 1 ; + Col [col].shared2.score = 0 ; + Col [col].shared3.prev = Empty ; + Col [col].shared4.degree_next = Empty ; + } + + /* p [0..n_col] no longer needed, used as "head" in subsequent routines */ + + /* === Scan columns, compute row degrees, and check row indices ========= */ + + stats [Info3] = 0 ; /* number of duplicate or unsorted row indices*/ + + for (row = 0 ; row < n_row ; row++) + { + Row [row].length = 0 ; + Row [row].shared2.mark = -1 ; + } + + for (col = 0 ; col < n_col ; col++) + { + last_row = -1 ; + + cp = &A [p [col]] ; + cp_end = &A [p [col+1]] ; + + while (cp < cp_end) + { + row = *cp++ ; + + /* make sure row indices within range */ + if (row < 0 || row >= n_row) + { + stats [Colamd::Status] = Colamd::ErrorRowIndexOutOfBounds ; + stats [Colamd::Info1] = col ; + stats [Colamd::Info2] = row ; + stats [Colamd::Info3] = n_row ; + COLAMD_DEBUG0 (("colamd: row %d col %d out of bounds\n", row, col)) ; + return (false) ; + } + + if (row <= last_row || Row [row].shared2.mark == col) + { + /* row index are unsorted or repeated (or both), thus col */ + /* is jumbled. This is a notice, not an error condition. */ + stats [Colamd::Status] = Colamd::OkButJumbled ; + stats [Colamd::Info1] = col ; + stats [Colamd::Info2] = row ; + (stats [Colamd::Info3]) ++ ; + COLAMD_DEBUG1 (("colamd: row %d col %d unsorted/duplicate\n",row,col)); + } + + if (Row [row].shared2.mark != col) + { + Row [row].length++ ; + } + else + { + /* this is a repeated entry in the column, */ + /* it will be removed */ + Col [col].length-- ; + } + + /* mark the row as having been seen in this column */ + Row [row].shared2.mark = col ; + + last_row = row ; + } + } + + /* === Compute row pointers ============================================= */ + + /* row form of the matrix starts directly after the column */ + /* form of matrix in A */ + Row [0].start = p [n_col] ; + Row [0].shared1.p = Row [0].start ; + Row [0].shared2.mark = -1 ; + for (row = 1 ; row < n_row ; row++) + { + Row [row].start = Row [row-1].start + Row [row-1].length ; + Row [row].shared1.p = Row [row].start ; + Row [row].shared2.mark = -1 ; + } + + /* === Create row form ================================================== */ + + if (stats [Status] == OkButJumbled) + { + /* if cols jumbled, watch for repeated row indices */ + for (col = 0 ; col < n_col ; col++) + { + cp = &A [p [col]] ; + cp_end = &A [p [col+1]] ; + while (cp < cp_end) + { + row = *cp++ ; + if (Row [row].shared2.mark != col) + { + A [(Row [row].shared1.p)++] = col ; + Row [row].shared2.mark = col ; + } + } + } + } + else + { + /* if cols not jumbled, we don't need the mark (this is faster) */ + for (col = 0 ; col < n_col ; col++) + { + cp = &A [p [col]] ; + cp_end = &A [p [col+1]] ; + while (cp < cp_end) + { + A [(Row [*cp++].shared1.p)++] = col ; + } + } + } + + /* === Clear the row marks and set row degrees ========================== */ + + for (row = 0 ; row < n_row ; row++) + { + Row [row].shared2.mark = 0 ; + Row [row].shared1.degree = Row [row].length ; + } + + /* === See if we need to re-create columns ============================== */ + + if (stats [Status] == OkButJumbled) + { + COLAMD_DEBUG0 (("colamd: reconstructing column form, matrix jumbled\n")) ; + + + /* === Compute col pointers ========================================= */ + + /* col form of the matrix starts at A [0]. */ + /* Note, we may have a gap between the col form and the row */ + /* form if there were duplicate entries, if so, it will be */ + /* removed upon the first garbage collection */ + Col [0].start = 0 ; + p [0] = Col [0].start ; + for (col = 1 ; col < n_col ; col++) + { + /* note that the lengths here are for pruned columns, i.e. */ + /* no duplicate row indices will exist for these columns */ + Col [col].start = Col [col-1].start + Col [col-1].length ; + p [col] = Col [col].start ; + } + + /* === Re-create col form =========================================== */ + + for (row = 0 ; row < n_row ; row++) + { + rp = &A [Row [row].start] ; + rp_end = rp + Row [row].length ; + while (rp < rp_end) + { + A [(p [*rp++])++] = row ; + } + } + } + + /* === Done. Matrix is not (or no longer) jumbled ====================== */ + + return (true) ; +} + + +/* ========================================================================== */ +/* === init_scoring ========================================================= */ +/* ========================================================================== */ + +/* + Kills dense or empty columns and rows, calculates an initial score for + each column, and places all columns in the degree lists. Not user-callable. +*/ +template +static void init_scoring + ( + /* === Parameters ======================================================= */ + + IndexType n_row, /* number of rows of A */ + IndexType n_col, /* number of columns of A */ + RowStructure Row [], /* of size n_row+1 */ + ColStructure Col [], /* of size n_col+1 */ + IndexType A [], /* column form and row form of A */ + IndexType head [], /* of size n_col+1 */ + double knobs [NKnobs],/* parameters */ + IndexType *p_n_row2, /* number of non-dense, non-empty rows */ + IndexType *p_n_col2, /* number of non-dense, non-empty columns */ + IndexType *p_max_deg /* maximum row degree */ + ) +{ + /* === Local variables ================================================== */ + + IndexType c ; /* a column index */ + IndexType r, row ; /* a row index */ + IndexType *cp ; /* a column pointer */ + IndexType deg ; /* degree of a row or column */ + IndexType *cp_end ; /* a pointer to the end of a column */ + IndexType *new_cp ; /* new column pointer */ + IndexType col_length ; /* length of pruned column */ + IndexType score ; /* current column score */ + IndexType n_col2 ; /* number of non-dense, non-empty columns */ + IndexType n_row2 ; /* number of non-dense, non-empty rows */ + IndexType dense_row_count ; /* remove rows with more entries than this */ + IndexType dense_col_count ; /* remove cols with more entries than this */ + IndexType min_score ; /* smallest column score */ + IndexType max_deg ; /* maximum row degree */ + IndexType next_col ; /* Used to add to degree list.*/ + + + /* === Extract knobs ==================================================== */ + + dense_row_count = numext::maxi(IndexType(0), numext::mini(IndexType(knobs [Colamd::DenseRow] * n_col), n_col)) ; + dense_col_count = numext::maxi(IndexType(0), numext::mini(IndexType(knobs [Colamd::DenseCol] * n_row), n_row)) ; + COLAMD_DEBUG1 (("colamd: densecount: %d %d\n", dense_row_count, dense_col_count)) ; + max_deg = 0 ; + n_col2 = n_col ; + n_row2 = n_row ; + + /* === Kill empty columns =============================================== */ + + /* Put the empty columns at the end in their natural order, so that LU */ + /* factorization can proceed as far as possible. */ + for (c = n_col-1 ; c >= 0 ; c--) + { + deg = Col [c].length ; + if (deg == 0) + { + /* this is a empty column, kill and order it last */ + Col [c].shared2.order = --n_col2 ; + Col[c].kill_principal() ; + } + } + COLAMD_DEBUG1 (("colamd: null columns killed: %d\n", n_col - n_col2)) ; + + /* === Kill dense columns =============================================== */ + + /* Put the dense columns at the end, in their natural order */ + for (c = n_col-1 ; c >= 0 ; c--) + { + /* skip any dead columns */ + if (Col[c].is_dead()) + { + continue ; + } + deg = Col [c].length ; + if (deg > dense_col_count) + { + /* this is a dense column, kill and order it last */ + Col [c].shared2.order = --n_col2 ; + /* decrement the row degrees */ + cp = &A [Col [c].start] ; + cp_end = cp + Col [c].length ; + while (cp < cp_end) + { + Row [*cp++].shared1.degree-- ; + } + Col[c].kill_principal() ; + } + } + COLAMD_DEBUG1 (("colamd: Dense and null columns killed: %d\n", n_col - n_col2)) ; + + /* === Kill dense and empty rows ======================================== */ + + for (r = 0 ; r < n_row ; r++) + { + deg = Row [r].shared1.degree ; + COLAMD_ASSERT (deg >= 0 && deg <= n_col) ; + if (deg > dense_row_count || deg == 0) + { + /* kill a dense or empty row */ + Row[r].kill() ; + --n_row2 ; + } + else + { + /* keep track of max degree of remaining rows */ + max_deg = numext::maxi(max_deg, deg) ; + } + } + COLAMD_DEBUG1 (("colamd: Dense and null rows killed: %d\n", n_row - n_row2)) ; + + /* === Compute initial column scores ==================================== */ + + /* At this point the row degrees are accurate. They reflect the number */ + /* of "live" (non-dense) columns in each row. No empty rows exist. */ + /* Some "live" columns may contain only dead rows, however. These are */ + /* pruned in the code below. */ + + /* now find the initial matlab score for each column */ + for (c = n_col-1 ; c >= 0 ; c--) + { + /* skip dead column */ + if (Col[c].is_dead()) + { + continue ; + } + score = 0 ; + cp = &A [Col [c].start] ; + new_cp = cp ; + cp_end = cp + Col [c].length ; + while (cp < cp_end) + { + /* get a row */ + row = *cp++ ; + /* skip if dead */ + if (Row[row].is_dead()) + { + continue ; + } + /* compact the column */ + *new_cp++ = row ; + /* add row's external degree */ + score += Row [row].shared1.degree - 1 ; + /* guard against integer overflow */ + score = numext::mini(score, n_col) ; + } + /* determine pruned column length */ + col_length = (IndexType) (new_cp - &A [Col [c].start]) ; + if (col_length == 0) + { + /* a newly-made null column (all rows in this col are "dense" */ + /* and have already been killed) */ + COLAMD_DEBUG2 (("Newly null killed: %d\n", c)) ; + Col [c].shared2.order = --n_col2 ; + Col[c].kill_principal() ; + } + else + { + /* set column length and set score */ + COLAMD_ASSERT (score >= 0) ; + COLAMD_ASSERT (score <= n_col) ; + Col [c].length = col_length ; + Col [c].shared2.score = score ; + } + } + COLAMD_DEBUG1 (("colamd: Dense, null, and newly-null columns killed: %d\n", + n_col-n_col2)) ; + + /* At this point, all empty rows and columns are dead. All live columns */ + /* are "clean" (containing no dead rows) and simplicial (no supercolumns */ + /* yet). Rows may contain dead columns, but all live rows contain at */ + /* least one live column. */ + + /* === Initialize degree lists ========================================== */ + + + /* clear the hash buckets */ + for (c = 0 ; c <= n_col ; c++) + { + head [c] = Empty ; + } + min_score = n_col ; + /* place in reverse order, so low column indices are at the front */ + /* of the lists. This is to encourage natural tie-breaking */ + for (c = n_col-1 ; c >= 0 ; c--) + { + /* only add principal columns to degree lists */ + if (Col[c].is_alive()) + { + COLAMD_DEBUG4 (("place %d score %d minscore %d ncol %d\n", + c, Col [c].shared2.score, min_score, n_col)) ; + + /* === Add columns score to DList =============================== */ + + score = Col [c].shared2.score ; + + COLAMD_ASSERT (min_score >= 0) ; + COLAMD_ASSERT (min_score <= n_col) ; + COLAMD_ASSERT (score >= 0) ; + COLAMD_ASSERT (score <= n_col) ; + COLAMD_ASSERT (head [score] >= Empty) ; + + /* now add this column to dList at proper score location */ + next_col = head [score] ; + Col [c].shared3.prev = Empty ; + Col [c].shared4.degree_next = next_col ; + + /* if there already was a column with the same score, set its */ + /* previous pointer to this new column */ + if (next_col != Empty) + { + Col [next_col].shared3.prev = c ; + } + head [score] = c ; + + /* see if this score is less than current min */ + min_score = numext::mini(min_score, score) ; + + + } + } + + + /* === Return number of remaining columns, and max row degree =========== */ + + *p_n_col2 = n_col2 ; + *p_n_row2 = n_row2 ; + *p_max_deg = max_deg ; +} + + +/* ========================================================================== */ +/* === find_ordering ======================================================== */ +/* ========================================================================== */ + +/* + Order the principal columns of the supercolumn form of the matrix + (no supercolumns on input). Uses a minimum approximate column minimum + degree ordering method. Not user-callable. +*/ +template +static IndexType find_ordering /* return the number of garbage collections */ + ( + /* === Parameters ======================================================= */ + + IndexType n_row, /* number of rows of A */ + IndexType n_col, /* number of columns of A */ + IndexType Alen, /* size of A, 2*nnz + n_col or larger */ + RowStructure Row [], /* of size n_row+1 */ + ColStructure Col [], /* of size n_col+1 */ + IndexType A [], /* column form and row form of A */ + IndexType head [], /* of size n_col+1 */ + IndexType n_col2, /* Remaining columns to order */ + IndexType max_deg, /* Maximum row degree */ + IndexType pfree /* index of first free slot (2*nnz on entry) */ + ) +{ + /* === Local variables ================================================== */ + + IndexType k ; /* current pivot ordering step */ + IndexType pivot_col ; /* current pivot column */ + IndexType *cp ; /* a column pointer */ + IndexType *rp ; /* a row pointer */ + IndexType pivot_row ; /* current pivot row */ + IndexType *new_cp ; /* modified column pointer */ + IndexType *new_rp ; /* modified row pointer */ + IndexType pivot_row_start ; /* pointer to start of pivot row */ + IndexType pivot_row_degree ; /* number of columns in pivot row */ + IndexType pivot_row_length ; /* number of supercolumns in pivot row */ + IndexType pivot_col_score ; /* score of pivot column */ + IndexType needed_memory ; /* free space needed for pivot row */ + IndexType *cp_end ; /* pointer to the end of a column */ + IndexType *rp_end ; /* pointer to the end of a row */ + IndexType row ; /* a row index */ + IndexType col ; /* a column index */ + IndexType max_score ; /* maximum possible score */ + IndexType cur_score ; /* score of current column */ + unsigned int hash ; /* hash value for supernode detection */ + IndexType head_column ; /* head of hash bucket */ + IndexType first_col ; /* first column in hash bucket */ + IndexType tag_mark ; /* marker value for mark array */ + IndexType row_mark ; /* Row [row].shared2.mark */ + IndexType set_difference ; /* set difference size of row with pivot row */ + IndexType min_score ; /* smallest column score */ + IndexType col_thickness ; /* "thickness" (no. of columns in a supercol) */ + IndexType max_mark ; /* maximum value of tag_mark */ + IndexType pivot_col_thickness ; /* number of columns represented by pivot col */ + IndexType prev_col ; /* Used by Dlist operations. */ + IndexType next_col ; /* Used by Dlist operations. */ + IndexType ngarbage ; /* number of garbage collections performed */ + + + /* === Initialization and clear mark ==================================== */ + + max_mark = INT_MAX - n_col ; /* INT_MAX defined in */ + tag_mark = Colamd::clear_mark (n_row, Row) ; + min_score = 0 ; + ngarbage = 0 ; + COLAMD_DEBUG1 (("colamd: Ordering, n_col2=%d\n", n_col2)) ; + + /* === Order the columns ================================================ */ + + for (k = 0 ; k < n_col2 ; /* 'k' is incremented below */) + { + + /* === Select pivot column, and order it ============================ */ + + /* make sure degree list isn't empty */ + COLAMD_ASSERT (min_score >= 0) ; + COLAMD_ASSERT (min_score <= n_col) ; + COLAMD_ASSERT (head [min_score] >= Empty) ; + + /* get pivot column from head of minimum degree list */ + while (min_score < n_col && head [min_score] == Empty) + { + min_score++ ; + } + pivot_col = head [min_score] ; + COLAMD_ASSERT (pivot_col >= 0 && pivot_col <= n_col) ; + next_col = Col [pivot_col].shared4.degree_next ; + head [min_score] = next_col ; + if (next_col != Empty) + { + Col [next_col].shared3.prev = Empty ; + } + + COLAMD_ASSERT (Col[pivot_col].is_alive()) ; + COLAMD_DEBUG3 (("Pivot col: %d\n", pivot_col)) ; + + /* remember score for defrag check */ + pivot_col_score = Col [pivot_col].shared2.score ; + + /* the pivot column is the kth column in the pivot order */ + Col [pivot_col].shared2.order = k ; + + /* increment order count by column thickness */ + pivot_col_thickness = Col [pivot_col].shared1.thickness ; + k += pivot_col_thickness ; + COLAMD_ASSERT (pivot_col_thickness > 0) ; + + /* === Garbage_collection, if necessary ============================= */ + + needed_memory = numext::mini(pivot_col_score, n_col - k) ; + if (pfree + needed_memory >= Alen) + { + pfree = Colamd::garbage_collection (n_row, n_col, Row, Col, A, &A [pfree]) ; + ngarbage++ ; + /* after garbage collection we will have enough */ + COLAMD_ASSERT (pfree + needed_memory < Alen) ; + /* garbage collection has wiped out the Row[].shared2.mark array */ + tag_mark = Colamd::clear_mark (n_row, Row) ; + + } + + /* === Compute pivot row pattern ==================================== */ + + /* get starting location for this new merged row */ + pivot_row_start = pfree ; + + /* initialize new row counts to zero */ + pivot_row_degree = 0 ; + + /* tag pivot column as having been visited so it isn't included */ + /* in merged pivot row */ + Col [pivot_col].shared1.thickness = -pivot_col_thickness ; + + /* pivot row is the union of all rows in the pivot column pattern */ + cp = &A [Col [pivot_col].start] ; + cp_end = cp + Col [pivot_col].length ; + while (cp < cp_end) + { + /* get a row */ + row = *cp++ ; + COLAMD_DEBUG4 (("Pivot col pattern %d %d\n", Row[row].is_alive(), row)) ; + /* skip if row is dead */ + if (Row[row].is_dead()) + { + continue ; + } + rp = &A [Row [row].start] ; + rp_end = rp + Row [row].length ; + while (rp < rp_end) + { + /* get a column */ + col = *rp++ ; + /* add the column, if alive and untagged */ + col_thickness = Col [col].shared1.thickness ; + if (col_thickness > 0 && Col[col].is_alive()) + { + /* tag column in pivot row */ + Col [col].shared1.thickness = -col_thickness ; + COLAMD_ASSERT (pfree < Alen) ; + /* place column in pivot row */ + A [pfree++] = col ; + pivot_row_degree += col_thickness ; + } + } + } + + /* clear tag on pivot column */ + Col [pivot_col].shared1.thickness = pivot_col_thickness ; + max_deg = numext::maxi(max_deg, pivot_row_degree) ; + + + /* === Kill all rows used to construct pivot row ==================== */ + + /* also kill pivot row, temporarily */ + cp = &A [Col [pivot_col].start] ; + cp_end = cp + Col [pivot_col].length ; + while (cp < cp_end) + { + /* may be killing an already dead row */ + row = *cp++ ; + COLAMD_DEBUG3 (("Kill row in pivot col: %d\n", row)) ; + Row[row].kill() ; + } + + /* === Select a row index to use as the new pivot row =============== */ + + pivot_row_length = pfree - pivot_row_start ; + if (pivot_row_length > 0) + { + /* pick the "pivot" row arbitrarily (first row in col) */ + pivot_row = A [Col [pivot_col].start] ; + COLAMD_DEBUG3 (("Pivotal row is %d\n", pivot_row)) ; + } + else + { + /* there is no pivot row, since it is of zero length */ + pivot_row = Empty ; + COLAMD_ASSERT (pivot_row_length == 0) ; + } + COLAMD_ASSERT (Col [pivot_col].length > 0 || pivot_row_length == 0) ; + + /* === Approximate degree computation =============================== */ + + /* Here begins the computation of the approximate degree. The column */ + /* score is the sum of the pivot row "length", plus the size of the */ + /* set differences of each row in the column minus the pattern of the */ + /* pivot row itself. The column ("thickness") itself is also */ + /* excluded from the column score (we thus use an approximate */ + /* external degree). */ + + /* The time taken by the following code (compute set differences, and */ + /* add them up) is proportional to the size of the data structure */ + /* being scanned - that is, the sum of the sizes of each column in */ + /* the pivot row. Thus, the amortized time to compute a column score */ + /* is proportional to the size of that column (where size, in this */ + /* context, is the column "length", or the number of row indices */ + /* in that column). The number of row indices in a column is */ + /* monotonically non-decreasing, from the length of the original */ + /* column on input to colamd. */ + + /* === Compute set differences ====================================== */ + + COLAMD_DEBUG3 (("** Computing set differences phase. **\n")) ; + + /* pivot row is currently dead - it will be revived later. */ + + COLAMD_DEBUG3 (("Pivot row: ")) ; + /* for each column in pivot row */ + rp = &A [pivot_row_start] ; + rp_end = rp + pivot_row_length ; + while (rp < rp_end) + { + col = *rp++ ; + COLAMD_ASSERT (Col[col].is_alive() && col != pivot_col) ; + COLAMD_DEBUG3 (("Col: %d\n", col)) ; + + /* clear tags used to construct pivot row pattern */ + col_thickness = -Col [col].shared1.thickness ; + COLAMD_ASSERT (col_thickness > 0) ; + Col [col].shared1.thickness = col_thickness ; + + /* === Remove column from degree list =========================== */ + + cur_score = Col [col].shared2.score ; + prev_col = Col [col].shared3.prev ; + next_col = Col [col].shared4.degree_next ; + COLAMD_ASSERT (cur_score >= 0) ; + COLAMD_ASSERT (cur_score <= n_col) ; + COLAMD_ASSERT (cur_score >= Empty) ; + if (prev_col == Empty) + { + head [cur_score] = next_col ; + } + else + { + Col [prev_col].shared4.degree_next = next_col ; + } + if (next_col != Empty) + { + Col [next_col].shared3.prev = prev_col ; + } + + /* === Scan the column ========================================== */ + + cp = &A [Col [col].start] ; + cp_end = cp + Col [col].length ; + while (cp < cp_end) + { + /* get a row */ + row = *cp++ ; + /* skip if dead */ + if (Row[row].is_dead()) + { + continue ; + } + row_mark = Row [row].shared2.mark ; + COLAMD_ASSERT (row != pivot_row) ; + set_difference = row_mark - tag_mark ; + /* check if the row has been seen yet */ + if (set_difference < 0) + { + COLAMD_ASSERT (Row [row].shared1.degree <= max_deg) ; + set_difference = Row [row].shared1.degree ; + } + /* subtract column thickness from this row's set difference */ + set_difference -= col_thickness ; + COLAMD_ASSERT (set_difference >= 0) ; + /* absorb this row if the set difference becomes zero */ + if (set_difference == 0) + { + COLAMD_DEBUG3 (("aggressive absorption. Row: %d\n", row)) ; + Row[row].kill() ; + } + else + { + /* save the new mark */ + Row [row].shared2.mark = set_difference + tag_mark ; + } + } + } + + + /* === Add up set differences for each column ======================= */ + + COLAMD_DEBUG3 (("** Adding set differences phase. **\n")) ; + + /* for each column in pivot row */ + rp = &A [pivot_row_start] ; + rp_end = rp + pivot_row_length ; + while (rp < rp_end) + { + /* get a column */ + col = *rp++ ; + COLAMD_ASSERT (Col[col].is_alive() && col != pivot_col) ; + hash = 0 ; + cur_score = 0 ; + cp = &A [Col [col].start] ; + /* compact the column */ + new_cp = cp ; + cp_end = cp + Col [col].length ; + + COLAMD_DEBUG4 (("Adding set diffs for Col: %d.\n", col)) ; + + while (cp < cp_end) + { + /* get a row */ + row = *cp++ ; + COLAMD_ASSERT(row >= 0 && row < n_row) ; + /* skip if dead */ + if (Row [row].is_dead()) + { + continue ; + } + row_mark = Row [row].shared2.mark ; + COLAMD_ASSERT (row_mark > tag_mark) ; + /* compact the column */ + *new_cp++ = row ; + /* compute hash function */ + hash += row ; + /* add set difference */ + cur_score += row_mark - tag_mark ; + /* integer overflow... */ + cur_score = numext::mini(cur_score, n_col) ; + } + + /* recompute the column's length */ + Col [col].length = (IndexType) (new_cp - &A [Col [col].start]) ; + + /* === Further mass elimination ================================= */ + + if (Col [col].length == 0) + { + COLAMD_DEBUG4 (("further mass elimination. Col: %d\n", col)) ; + /* nothing left but the pivot row in this column */ + Col[col].kill_principal() ; + pivot_row_degree -= Col [col].shared1.thickness ; + COLAMD_ASSERT (pivot_row_degree >= 0) ; + /* order it */ + Col [col].shared2.order = k ; + /* increment order count by column thickness */ + k += Col [col].shared1.thickness ; + } + else + { + /* === Prepare for supercolumn detection ==================== */ + + COLAMD_DEBUG4 (("Preparing supercol detection for Col: %d.\n", col)) ; + + /* save score so far */ + Col [col].shared2.score = cur_score ; + + /* add column to hash table, for supercolumn detection */ + hash %= n_col + 1 ; + + COLAMD_DEBUG4 ((" Hash = %d, n_col = %d.\n", hash, n_col)) ; + COLAMD_ASSERT (hash <= n_col) ; + + head_column = head [hash] ; + if (head_column > Empty) + { + /* degree list "hash" is non-empty, use prev (shared3) of */ + /* first column in degree list as head of hash bucket */ + first_col = Col [head_column].shared3.headhash ; + Col [head_column].shared3.headhash = col ; + } + else + { + /* degree list "hash" is empty, use head as hash bucket */ + first_col = - (head_column + 2) ; + head [hash] = - (col + 2) ; + } + Col [col].shared4.hash_next = first_col ; + + /* save hash function in Col [col].shared3.hash */ + Col [col].shared3.hash = (IndexType) hash ; + COLAMD_ASSERT (Col[col].is_alive()) ; + } + } + + /* The approximate external column degree is now computed. */ + + /* === Supercolumn detection ======================================== */ + + COLAMD_DEBUG3 (("** Supercolumn detection phase. **\n")) ; + + Colamd::detect_super_cols (Col, A, head, pivot_row_start, pivot_row_length) ; + + /* === Kill the pivotal column ====================================== */ + + Col[pivot_col].kill_principal() ; + + /* === Clear mark =================================================== */ + + tag_mark += (max_deg + 1) ; + if (tag_mark >= max_mark) + { + COLAMD_DEBUG2 (("clearing tag_mark\n")) ; + tag_mark = Colamd::clear_mark (n_row, Row) ; + } + + /* === Finalize the new pivot row, and column scores ================ */ + + COLAMD_DEBUG3 (("** Finalize scores phase. **\n")) ; + + /* for each column in pivot row */ + rp = &A [pivot_row_start] ; + /* compact the pivot row */ + new_rp = rp ; + rp_end = rp + pivot_row_length ; + while (rp < rp_end) + { + col = *rp++ ; + /* skip dead columns */ + if (Col[col].is_dead()) + { + continue ; + } + *new_rp++ = col ; + /* add new pivot row to column */ + A [Col [col].start + (Col [col].length++)] = pivot_row ; + + /* retrieve score so far and add on pivot row's degree. */ + /* (we wait until here for this in case the pivot */ + /* row's degree was reduced due to mass elimination). */ + cur_score = Col [col].shared2.score + pivot_row_degree ; + + /* calculate the max possible score as the number of */ + /* external columns minus the 'k' value minus the */ + /* columns thickness */ + max_score = n_col - k - Col [col].shared1.thickness ; + + /* make the score the external degree of the union-of-rows */ + cur_score -= Col [col].shared1.thickness ; + + /* make sure score is less or equal than the max score */ + cur_score = numext::mini(cur_score, max_score) ; + COLAMD_ASSERT (cur_score >= 0) ; + + /* store updated score */ + Col [col].shared2.score = cur_score ; + + /* === Place column back in degree list ========================= */ + + COLAMD_ASSERT (min_score >= 0) ; + COLAMD_ASSERT (min_score <= n_col) ; + COLAMD_ASSERT (cur_score >= 0) ; + COLAMD_ASSERT (cur_score <= n_col) ; + COLAMD_ASSERT (head [cur_score] >= Empty) ; + next_col = head [cur_score] ; + Col [col].shared4.degree_next = next_col ; + Col [col].shared3.prev = Empty ; + if (next_col != Empty) + { + Col [next_col].shared3.prev = col ; + } + head [cur_score] = col ; + + /* see if this score is less than current min */ + min_score = numext::mini(min_score, cur_score) ; + + } + + /* === Resurrect the new pivot row ================================== */ + + if (pivot_row_degree > 0) + { + /* update pivot row length to reflect any cols that were killed */ + /* during super-col detection and mass elimination */ + Row [pivot_row].start = pivot_row_start ; + Row [pivot_row].length = (IndexType) (new_rp - &A[pivot_row_start]) ; + Row [pivot_row].shared1.degree = pivot_row_degree ; + Row [pivot_row].shared2.mark = 0 ; + /* pivot row is no longer dead */ + } + } + + /* === All principal columns have now been ordered ====================== */ + + return (ngarbage) ; +} + + +/* ========================================================================== */ +/* === order_children ======================================================= */ +/* ========================================================================== */ + +/* + The find_ordering routine has ordered all of the principal columns (the + representatives of the supercolumns). The non-principal columns have not + yet been ordered. This routine orders those columns by walking up the + parent tree (a column is a child of the column which absorbed it). The + final permutation vector is then placed in p [0 ... n_col-1], with p [0] + being the first column, and p [n_col-1] being the last. It doesn't look + like it at first glance, but be assured that this routine takes time linear + in the number of columns. Although not immediately obvious, the time + taken by this routine is O (n_col), that is, linear in the number of + columns. Not user-callable. +*/ +template +static inline void order_children +( + /* === Parameters ======================================================= */ + + IndexType n_col, /* number of columns of A */ + ColStructure Col [], /* of size n_col+1 */ + IndexType p [] /* p [0 ... n_col-1] is the column permutation*/ + ) +{ + /* === Local variables ================================================== */ + + IndexType i ; /* loop counter for all columns */ + IndexType c ; /* column index */ + IndexType parent ; /* index of column's parent */ + IndexType order ; /* column's order */ + + /* === Order each non-principal column ================================== */ + + for (i = 0 ; i < n_col ; i++) + { + /* find an un-ordered non-principal column */ + COLAMD_ASSERT (col_is_dead(Col, i)) ; + if (!Col[i].is_dead_principal() && Col [i].shared2.order == Empty) + { + parent = i ; + /* once found, find its principal parent */ + do + { + parent = Col [parent].shared1.parent ; + } while (!Col[parent].is_dead_principal()) ; + + /* now, order all un-ordered non-principal columns along path */ + /* to this parent. collapse tree at the same time */ + c = i ; + /* get order of parent */ + order = Col [parent].shared2.order ; + + do + { + COLAMD_ASSERT (Col [c].shared2.order == Empty) ; + + /* order this column */ + Col [c].shared2.order = order++ ; + /* collaps tree */ + Col [c].shared1.parent = parent ; + + /* get immediate parent of this column */ + c = Col [c].shared1.parent ; + + /* continue until we hit an ordered column. There are */ + /* guaranteed not to be anymore unordered columns */ + /* above an ordered column */ + } while (Col [c].shared2.order == Empty) ; + + /* re-order the super_col parent to largest order for this group */ + Col [parent].shared2.order = order ; + } + } + + /* === Generate the permutation ========================================= */ + + for (c = 0 ; c < n_col ; c++) + { + p [Col [c].shared2.order] = c ; + } +} + + +/* ========================================================================== */ +/* === detect_super_cols ==================================================== */ +/* ========================================================================== */ + +/* + Detects supercolumns by finding matches between columns in the hash buckets. + Check amongst columns in the set A [row_start ... row_start + row_length-1]. + The columns under consideration are currently *not* in the degree lists, + and have already been placed in the hash buckets. + + The hash bucket for columns whose hash function is equal to h is stored + as follows: + + if head [h] is >= 0, then head [h] contains a degree list, so: + + head [h] is the first column in degree bucket h. + Col [head [h]].headhash gives the first column in hash bucket h. + + otherwise, the degree list is empty, and: + + -(head [h] + 2) is the first column in hash bucket h. + + For a column c in a hash bucket, Col [c].shared3.prev is NOT a "previous + column" pointer. Col [c].shared3.hash is used instead as the hash number + for that column. The value of Col [c].shared4.hash_next is the next column + in the same hash bucket. + + Assuming no, or "few" hash collisions, the time taken by this routine is + linear in the sum of the sizes (lengths) of each column whose score has + just been computed in the approximate degree computation. + Not user-callable. +*/ +template +static void detect_super_cols +( + /* === Parameters ======================================================= */ + + ColStructure Col [], /* of size n_col+1 */ + IndexType A [], /* row indices of A */ + IndexType head [], /* head of degree lists and hash buckets */ + IndexType row_start, /* pointer to set of columns to check */ + IndexType row_length /* number of columns to check */ +) +{ + /* === Local variables ================================================== */ + + IndexType hash ; /* hash value for a column */ + IndexType *rp ; /* pointer to a row */ + IndexType c ; /* a column index */ + IndexType super_c ; /* column index of the column to absorb into */ + IndexType *cp1 ; /* column pointer for column super_c */ + IndexType *cp2 ; /* column pointer for column c */ + IndexType length ; /* length of column super_c */ + IndexType prev_c ; /* column preceding c in hash bucket */ + IndexType i ; /* loop counter */ + IndexType *rp_end ; /* pointer to the end of the row */ + IndexType col ; /* a column index in the row to check */ + IndexType head_column ; /* first column in hash bucket or degree list */ + IndexType first_col ; /* first column in hash bucket */ + + /* === Consider each column in the row ================================== */ + + rp = &A [row_start] ; + rp_end = rp + row_length ; + while (rp < rp_end) + { + col = *rp++ ; + if (Col[col].is_dead()) + { + continue ; + } + + /* get hash number for this column */ + hash = Col [col].shared3.hash ; + COLAMD_ASSERT (hash <= n_col) ; + + /* === Get the first column in this hash bucket ===================== */ + + head_column = head [hash] ; + if (head_column > Empty) + { + first_col = Col [head_column].shared3.headhash ; + } + else + { + first_col = - (head_column + 2) ; + } + + /* === Consider each column in the hash bucket ====================== */ + + for (super_c = first_col ; super_c != Empty ; + super_c = Col [super_c].shared4.hash_next) + { + COLAMD_ASSERT (Col [super_c].is_alive()) ; + COLAMD_ASSERT (Col [super_c].shared3.hash == hash) ; + length = Col [super_c].length ; + + /* prev_c is the column preceding column c in the hash bucket */ + prev_c = super_c ; + + /* === Compare super_c with all columns after it ================ */ + + for (c = Col [super_c].shared4.hash_next ; + c != Empty ; c = Col [c].shared4.hash_next) + { + COLAMD_ASSERT (c != super_c) ; + COLAMD_ASSERT (Col[c].is_alive()) ; + COLAMD_ASSERT (Col [c].shared3.hash == hash) ; + + /* not identical if lengths or scores are different */ + if (Col [c].length != length || + Col [c].shared2.score != Col [super_c].shared2.score) + { + prev_c = c ; + continue ; + } + + /* compare the two columns */ + cp1 = &A [Col [super_c].start] ; + cp2 = &A [Col [c].start] ; + + for (i = 0 ; i < length ; i++) + { + /* the columns are "clean" (no dead rows) */ + COLAMD_ASSERT ( cp1->is_alive() ); + COLAMD_ASSERT ( cp2->is_alive() ); + /* row indices will same order for both supercols, */ + /* no gather scatter necessary */ + if (*cp1++ != *cp2++) + { + break ; + } + } + + /* the two columns are different if the for-loop "broke" */ + if (i != length) + { + prev_c = c ; + continue ; + } + + /* === Got it! two columns are identical =================== */ + + COLAMD_ASSERT (Col [c].shared2.score == Col [super_c].shared2.score) ; + + Col [super_c].shared1.thickness += Col [c].shared1.thickness ; + Col [c].shared1.parent = super_c ; + Col[c].kill_non_principal() ; + /* order c later, in order_children() */ + Col [c].shared2.order = Empty ; + /* remove c from hash bucket */ + Col [prev_c].shared4.hash_next = Col [c].shared4.hash_next ; + } + } + + /* === Empty this hash bucket ======================================= */ + + if (head_column > Empty) + { + /* corresponding degree list "hash" is not empty */ + Col [head_column].shared3.headhash = Empty ; + } + else + { + /* corresponding degree list "hash" is empty */ + head [hash] = Empty ; + } + } +} + + +/* ========================================================================== */ +/* === garbage_collection =================================================== */ +/* ========================================================================== */ + +/* + Defragments and compacts columns and rows in the workspace A. Used when + all available memory has been used while performing row merging. Returns + the index of the first free position in A, after garbage collection. The + time taken by this routine is linear is the size of the array A, which is + itself linear in the number of nonzeros in the input matrix. + Not user-callable. +*/ +template +static IndexType garbage_collection /* returns the new value of pfree */ + ( + /* === Parameters ======================================================= */ + + IndexType n_row, /* number of rows */ + IndexType n_col, /* number of columns */ + RowStructure Row [], /* row info */ + ColStructure Col [], /* column info */ + IndexType A [], /* A [0 ... Alen-1] holds the matrix */ + IndexType *pfree /* &A [0] ... pfree is in use */ + ) +{ + /* === Local variables ================================================== */ + + IndexType *psrc ; /* source pointer */ + IndexType *pdest ; /* destination pointer */ + IndexType j ; /* counter */ + IndexType r ; /* a row index */ + IndexType c ; /* a column index */ + IndexType length ; /* length of a row or column */ + + /* === Defragment the columns =========================================== */ + + pdest = &A[0] ; + for (c = 0 ; c < n_col ; c++) + { + if (Col[c].is_alive()) + { + psrc = &A [Col [c].start] ; + + /* move and compact the column */ + COLAMD_ASSERT (pdest <= psrc) ; + Col [c].start = (IndexType) (pdest - &A [0]) ; + length = Col [c].length ; + for (j = 0 ; j < length ; j++) + { + r = *psrc++ ; + if (Row[r].is_alive()) + { + *pdest++ = r ; + } + } + Col [c].length = (IndexType) (pdest - &A [Col [c].start]) ; + } + } + + /* === Prepare to defragment the rows =================================== */ + + for (r = 0 ; r < n_row ; r++) + { + if (Row[r].is_alive()) + { + if (Row [r].length == 0) + { + /* this row is of zero length. cannot compact it, so kill it */ + COLAMD_DEBUG3 (("Defrag row kill\n")) ; + Row[r].kill() ; + } + else + { + /* save first column index in Row [r].shared2.first_column */ + psrc = &A [Row [r].start] ; + Row [r].shared2.first_column = *psrc ; + COLAMD_ASSERT (Row[r].is_alive()) ; + /* flag the start of the row with the one's complement of row */ + *psrc = ones_complement(r) ; + + } + } + } + + /* === Defragment the rows ============================================== */ + + psrc = pdest ; + while (psrc < pfree) + { + /* find a negative number ... the start of a row */ + if (*psrc++ < 0) + { + psrc-- ; + /* get the row index */ + r = ones_complement(*psrc) ; + COLAMD_ASSERT (r >= 0 && r < n_row) ; + /* restore first column index */ + *psrc = Row [r].shared2.first_column ; + COLAMD_ASSERT (Row[r].is_alive()) ; + + /* move and compact the row */ + COLAMD_ASSERT (pdest <= psrc) ; + Row [r].start = (IndexType) (pdest - &A [0]) ; + length = Row [r].length ; + for (j = 0 ; j < length ; j++) + { + c = *psrc++ ; + if (Col[c].is_alive()) + { + *pdest++ = c ; + } + } + Row [r].length = (IndexType) (pdest - &A [Row [r].start]) ; + + } + } + /* ensure we found all the rows */ + COLAMD_ASSERT (debug_rows == 0) ; + + /* === Return the new value of pfree ==================================== */ + + return ((IndexType) (pdest - &A [0])) ; +} + + +/* ========================================================================== */ +/* === clear_mark =========================================================== */ +/* ========================================================================== */ + +/* + Clears the Row [].shared2.mark array, and returns the new tag_mark. + Return value is the new tag_mark. Not user-callable. +*/ +template +static inline IndexType clear_mark /* return the new value for tag_mark */ + ( + /* === Parameters ======================================================= */ + + IndexType n_row, /* number of rows in A */ + RowStructure Row [] /* Row [0 ... n_row-1].shared2.mark is set to zero */ + ) +{ + /* === Local variables ================================================== */ + + IndexType r ; + + for (r = 0 ; r < n_row ; r++) + { + if (Row[r].is_alive()) + { + Row [r].shared2.mark = 0 ; + } + } + return (1) ; +} + +} // namespace Colamd + +} // namespace internal +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Ordering.h b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Ordering.h new file mode 100644 index 0000000000000000000000000000000000000000..c578970142114353ea402af96e575496ea97c8a6 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/OrderingMethods/Ordering.h @@ -0,0 +1,153 @@ + +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ORDERING_H +#define EIGEN_ORDERING_H + +namespace Eigen { + +#include "Eigen_Colamd.h" + +namespace internal { + +/** \internal + * \ingroup OrderingMethods_Module + * \param[in] A the input non-symmetric matrix + * \param[out] symmat the symmetric pattern A^T+A from the input matrix \a A. + * FIXME: The values should not be considered here + */ +template +void ordering_helper_at_plus_a(const MatrixType& A, MatrixType& symmat) +{ + MatrixType C; + C = A.transpose(); // NOTE: Could be costly + for (int i = 0; i < C.rows(); i++) + { + for (typename MatrixType::InnerIterator it(C, i); it; ++it) + it.valueRef() = typename MatrixType::Scalar(0); + } + symmat = C + A; +} + +} + +/** \ingroup OrderingMethods_Module + * \class AMDOrdering + * + * Functor computing the \em approximate \em minimum \em degree ordering + * If the matrix is not structurally symmetric, an ordering of A^T+A is computed + * \tparam StorageIndex The type of indices of the matrix + * \sa COLAMDOrdering + */ +template +class AMDOrdering +{ + public: + typedef PermutationMatrix PermutationType; + + /** Compute the permutation vector from a sparse matrix + * This routine is much faster if the input matrix is column-major + */ + template + void operator()(const MatrixType& mat, PermutationType& perm) + { + // Compute the symmetric pattern + SparseMatrix symm; + internal::ordering_helper_at_plus_a(mat,symm); + + // Call the AMD routine + //m_mat.prune(keep_diag()); + internal::minimum_degree_ordering(symm, perm); + } + + /** Compute the permutation with a selfadjoint matrix */ + template + void operator()(const SparseSelfAdjointView& mat, PermutationType& perm) + { + SparseMatrix C; C = mat; + + // Call the AMD routine + // m_mat.prune(keep_diag()); //Remove the diagonal elements + internal::minimum_degree_ordering(C, perm); + } +}; + +/** \ingroup OrderingMethods_Module + * \class NaturalOrdering + * + * Functor computing the natural ordering (identity) + * + * \note Returns an empty permutation matrix + * \tparam StorageIndex The type of indices of the matrix + */ +template +class NaturalOrdering +{ + public: + typedef PermutationMatrix PermutationType; + + /** Compute the permutation vector from a column-major sparse matrix */ + template + void operator()(const MatrixType& /*mat*/, PermutationType& perm) + { + perm.resize(0); + } + +}; + +/** \ingroup OrderingMethods_Module + * \class COLAMDOrdering + * + * \tparam StorageIndex The type of indices of the matrix + * + * Functor computing the \em column \em approximate \em minimum \em degree ordering + * The matrix should be in column-major and \b compressed format (see SparseMatrix::makeCompressed()). + */ +template +class COLAMDOrdering +{ + public: + typedef PermutationMatrix PermutationType; + typedef Matrix IndexVector; + + /** Compute the permutation vector \a perm form the sparse matrix \a mat + * \warning The input sparse matrix \a mat must be in compressed mode (see SparseMatrix::makeCompressed()). + */ + template + void operator() (const MatrixType& mat, PermutationType& perm) + { + eigen_assert(mat.isCompressed() && "COLAMDOrdering requires a sparse matrix in compressed mode. Call .makeCompressed() before passing it to COLAMDOrdering"); + + StorageIndex m = StorageIndex(mat.rows()); + StorageIndex n = StorageIndex(mat.cols()); + StorageIndex nnz = StorageIndex(mat.nonZeros()); + // Get the recommended value of Alen to be used by colamd + StorageIndex Alen = internal::Colamd::recommended(nnz, m, n); + // Set the default parameters + double knobs [internal::Colamd::NKnobs]; + StorageIndex stats [internal::Colamd::NStats]; + internal::Colamd::set_defaults(knobs); + + IndexVector p(n+1), A(Alen); + for(StorageIndex i=0; i <= n; i++) p(i) = mat.outerIndexPtr()[i]; + for(StorageIndex i=0; i < nnz; i++) A(i) = mat.innerIndexPtr()[i]; + // Call Colamd routine to compute the ordering + StorageIndex info = internal::Colamd::compute_ordering(m, n, Alen, A.data(), p.data(), knobs, stats); + EIGEN_UNUSED_VARIABLE(info); + eigen_assert( info && "COLAMD failed " ); + + perm.resize(n); + for (StorageIndex i = 0; i < n; i++) perm.indices()(p(i)) = i; + } +}; + +} // end namespace Eigen + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/PardisoSupport/PardisoSupport.h b/vendor/eigen/include/eigen3/Eigen/src/PardisoSupport/PardisoSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..f89b79bd55bcd039f9cb3293da6cc9ebec56bcd1 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/PardisoSupport/PardisoSupport.h @@ -0,0 +1,545 @@ +/* + Copyright (c) 2011, Intel Corporation. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ******************************************************************************** + * Content : Eigen bindings to Intel(R) MKL PARDISO + ******************************************************************************** +*/ + +#ifndef EIGEN_PARDISOSUPPORT_H +#define EIGEN_PARDISOSUPPORT_H + +namespace Eigen { + +template class PardisoLU; +template class PardisoLLT; +template class PardisoLDLT; + +namespace internal +{ + template + struct pardiso_run_selector + { + static IndexType run( _MKL_DSS_HANDLE_t pt, IndexType maxfct, IndexType mnum, IndexType type, IndexType phase, IndexType n, void *a, + IndexType *ia, IndexType *ja, IndexType *perm, IndexType nrhs, IndexType *iparm, IndexType msglvl, void *b, void *x) + { + IndexType error = 0; + ::pardiso(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error); + return error; + } + }; + template<> + struct pardiso_run_selector + { + typedef long long int IndexType; + static IndexType run( _MKL_DSS_HANDLE_t pt, IndexType maxfct, IndexType mnum, IndexType type, IndexType phase, IndexType n, void *a, + IndexType *ia, IndexType *ja, IndexType *perm, IndexType nrhs, IndexType *iparm, IndexType msglvl, void *b, void *x) + { + IndexType error = 0; + ::pardiso_64(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error); + return error; + } + }; + + template struct pardiso_traits; + + template + struct pardiso_traits< PardisoLU<_MatrixType> > + { + typedef _MatrixType MatrixType; + typedef typename _MatrixType::Scalar Scalar; + typedef typename _MatrixType::RealScalar RealScalar; + typedef typename _MatrixType::StorageIndex StorageIndex; + }; + + template + struct pardiso_traits< PardisoLLT<_MatrixType, Options> > + { + typedef _MatrixType MatrixType; + typedef typename _MatrixType::Scalar Scalar; + typedef typename _MatrixType::RealScalar RealScalar; + typedef typename _MatrixType::StorageIndex StorageIndex; + }; + + template + struct pardiso_traits< PardisoLDLT<_MatrixType, Options> > + { + typedef _MatrixType MatrixType; + typedef typename _MatrixType::Scalar Scalar; + typedef typename _MatrixType::RealScalar RealScalar; + typedef typename _MatrixType::StorageIndex StorageIndex; + }; + +} // end namespace internal + +template +class PardisoImpl : public SparseSolverBase +{ + protected: + typedef SparseSolverBase Base; + using Base::derived; + using Base::m_isInitialized; + + typedef internal::pardiso_traits Traits; + public: + using Base::_solve_impl; + + typedef typename Traits::MatrixType MatrixType; + typedef typename Traits::Scalar Scalar; + typedef typename Traits::RealScalar RealScalar; + typedef typename Traits::StorageIndex StorageIndex; + typedef SparseMatrix SparseMatrixType; + typedef Matrix VectorType; + typedef Matrix IntRowVectorType; + typedef Matrix IntColVectorType; + typedef Array ParameterType; + enum { + ScalarIsComplex = NumTraits::IsComplex, + ColsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic + }; + + PardisoImpl() + : m_analysisIsOk(false), m_factorizationIsOk(false) + { + eigen_assert((sizeof(StorageIndex) >= sizeof(_INTEGER_t) && sizeof(StorageIndex) <= 8) && "Non-supported index type"); + m_iparm.setZero(); + m_msglvl = 0; // No output + m_isInitialized = false; + } + + ~PardisoImpl() + { + pardisoRelease(); + } + + inline Index cols() const { return m_size; } + inline Index rows() const { return m_size; } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + /** \warning for advanced usage only. + * \returns a reference to the parameter array controlling PARDISO. + * See the PARDISO manual to know how to use it. */ + ParameterType& pardisoParameterArray() + { + return m_iparm; + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + Derived& analyzePattern(const MatrixType& matrix); + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed. + * + * \sa analyzePattern() + */ + Derived& factorize(const MatrixType& matrix); + + Derived& compute(const MatrixType& matrix); + + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const; + + protected: + void pardisoRelease() + { + if(m_isInitialized) // Factorization ran at least once + { + internal::pardiso_run_selector::run(m_pt, 1, 1, m_type, -1, internal::convert_index(m_size),0, 0, 0, m_perm.data(), 0, + m_iparm.data(), m_msglvl, NULL, NULL); + m_isInitialized = false; + } + } + + void pardisoInit(int type) + { + m_type = type; + bool symmetric = std::abs(m_type) < 10; + m_iparm[0] = 1; // No solver default + m_iparm[1] = 2; // use Metis for the ordering + m_iparm[2] = 0; // Reserved. Set to zero. (??Numbers of processors, value of OMP_NUM_THREADS??) + m_iparm[3] = 0; // No iterative-direct algorithm + m_iparm[4] = 0; // No user fill-in reducing permutation + m_iparm[5] = 0; // Write solution into x, b is left unchanged + m_iparm[6] = 0; // Not in use + m_iparm[7] = 2; // Max numbers of iterative refinement steps + m_iparm[8] = 0; // Not in use + m_iparm[9] = 13; // Perturb the pivot elements with 1E-13 + m_iparm[10] = symmetric ? 0 : 1; // Use nonsymmetric permutation and scaling MPS + m_iparm[11] = 0; // Not in use + m_iparm[12] = symmetric ? 0 : 1; // Maximum weighted matching algorithm is switched-off (default for symmetric). + // Try m_iparm[12] = 1 in case of inappropriate accuracy + m_iparm[13] = 0; // Output: Number of perturbed pivots + m_iparm[14] = 0; // Not in use + m_iparm[15] = 0; // Not in use + m_iparm[16] = 0; // Not in use + m_iparm[17] = -1; // Output: Number of nonzeros in the factor LU + m_iparm[18] = -1; // Output: Mflops for LU factorization + m_iparm[19] = 0; // Output: Numbers of CG Iterations + + m_iparm[20] = 0; // 1x1 pivoting + m_iparm[26] = 0; // No matrix checker + m_iparm[27] = (sizeof(RealScalar) == 4) ? 1 : 0; + m_iparm[34] = 1; // C indexing + m_iparm[36] = 0; // CSR + m_iparm[59] = 0; // 0 - In-Core ; 1 - Automatic switch between In-Core and Out-of-Core modes ; 2 - Out-of-Core + + memset(m_pt, 0, sizeof(m_pt)); + } + + protected: + // cached data to reduce reallocation, etc. + + void manageErrorCode(Index error) const + { + switch(error) + { + case 0: + m_info = Success; + break; + case -4: + case -7: + m_info = NumericalIssue; + break; + default: + m_info = InvalidInput; + } + } + + mutable SparseMatrixType m_matrix; + mutable ComputationInfo m_info; + bool m_analysisIsOk, m_factorizationIsOk; + StorageIndex m_type, m_msglvl; + mutable void *m_pt[64]; + mutable ParameterType m_iparm; + mutable IntColVectorType m_perm; + Index m_size; + +}; + +template +Derived& PardisoImpl::compute(const MatrixType& a) +{ + m_size = a.rows(); + eigen_assert(a.rows() == a.cols()); + + pardisoRelease(); + m_perm.setZero(m_size); + derived().getMatrix(a); + + Index error; + error = internal::pardiso_run_selector::run(m_pt, 1, 1, m_type, 12, internal::convert_index(m_size), + m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), + m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); + manageErrorCode(error); + m_analysisIsOk = true; + m_factorizationIsOk = true; + m_isInitialized = true; + return derived(); +} + +template +Derived& PardisoImpl::analyzePattern(const MatrixType& a) +{ + m_size = a.rows(); + eigen_assert(m_size == a.cols()); + + pardisoRelease(); + m_perm.setZero(m_size); + derived().getMatrix(a); + + Index error; + error = internal::pardiso_run_selector::run(m_pt, 1, 1, m_type, 11, internal::convert_index(m_size), + m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), + m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); + + manageErrorCode(error); + m_analysisIsOk = true; + m_factorizationIsOk = false; + m_isInitialized = true; + return derived(); +} + +template +Derived& PardisoImpl::factorize(const MatrixType& a) +{ + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + eigen_assert(m_size == a.rows() && m_size == a.cols()); + + derived().getMatrix(a); + + Index error; + error = internal::pardiso_run_selector::run(m_pt, 1, 1, m_type, 22, internal::convert_index(m_size), + m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), + m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); + + manageErrorCode(error); + m_factorizationIsOk = true; + return derived(); +} + +template +template +void PardisoImpl::_solve_impl(const MatrixBase &b, MatrixBase& x) const +{ + if(m_iparm[0] == 0) // Factorization was not computed + { + m_info = InvalidInput; + return; + } + + //Index n = m_matrix.rows(); + Index nrhs = Index(b.cols()); + eigen_assert(m_size==b.rows()); + eigen_assert(((MatrixBase::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major right hand sides are not supported"); + eigen_assert(((MatrixBase::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major matrices of unknowns are not supported"); + eigen_assert(((nrhs == 1) || b.outerStride() == b.rows())); + + +// switch (transposed) { +// case SvNoTrans : m_iparm[11] = 0 ; break; +// case SvTranspose : m_iparm[11] = 2 ; break; +// case SvAdjoint : m_iparm[11] = 1 ; break; +// default: +// //std::cerr << "Eigen: transposition option \"" << transposed << "\" not supported by the PARDISO backend\n"; +// m_iparm[11] = 0; +// } + + Scalar* rhs_ptr = const_cast(b.derived().data()); + Matrix tmp; + + // Pardiso cannot solve in-place + if(rhs_ptr == x.derived().data()) + { + tmp = b; + rhs_ptr = tmp.data(); + } + + Index error; + error = internal::pardiso_run_selector::run(m_pt, 1, 1, m_type, 33, internal::convert_index(m_size), + m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), + m_perm.data(), internal::convert_index(nrhs), m_iparm.data(), m_msglvl, + rhs_ptr, x.derived().data()); + + manageErrorCode(error); +} + + +/** \ingroup PardisoSupport_Module + * \class PardisoLU + * \brief A sparse direct LU factorization and solver based on the PARDISO library + * + * This class allows to solve for A.X = B sparse linear problems via a direct LU factorization + * using the Intel MKL PARDISO library. The sparse matrix A must be squared and invertible. + * The vectors or matrices X and B can be either dense or sparse. + * + * By default, it runs in in-core mode. To enable PARDISO's out-of-core feature, set: + * \code solver.pardisoParameterArray()[59] = 1; \endcode + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class SparseLU + */ +template +class PardisoLU : public PardisoImpl< PardisoLU > +{ + protected: + typedef PardisoImpl Base; + using Base::pardisoInit; + using Base::m_matrix; + friend class PardisoImpl< PardisoLU >; + + public: + + typedef typename Base::Scalar Scalar; + typedef typename Base::RealScalar RealScalar; + + using Base::compute; + using Base::solve; + + PardisoLU() + : Base() + { + pardisoInit(Base::ScalarIsComplex ? 13 : 11); + } + + explicit PardisoLU(const MatrixType& matrix) + : Base() + { + pardisoInit(Base::ScalarIsComplex ? 13 : 11); + compute(matrix); + } + protected: + void getMatrix(const MatrixType& matrix) + { + m_matrix = matrix; + m_matrix.makeCompressed(); + } +}; + +/** \ingroup PardisoSupport_Module + * \class PardisoLLT + * \brief A sparse direct Cholesky (LLT) factorization and solver based on the PARDISO library + * + * This class allows to solve for A.X = B sparse linear problems via a LL^T Cholesky factorization + * using the Intel MKL PARDISO library. The sparse matrix A must be selfajoint and positive definite. + * The vectors or matrices X and B can be either dense or sparse. + * + * By default, it runs in in-core mode. To enable PARDISO's out-of-core feature, set: + * \code solver.pardisoParameterArray()[59] = 1; \endcode + * + * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam UpLo can be any bitwise combination of Upper, Lower. The default is Upper, meaning only the upper triangular part has to be used. + * Upper|Lower can be used to tell both triangular parts can be used as input. + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class SimplicialLLT + */ +template +class PardisoLLT : public PardisoImpl< PardisoLLT > +{ + protected: + typedef PardisoImpl< PardisoLLT > Base; + using Base::pardisoInit; + using Base::m_matrix; + friend class PardisoImpl< PardisoLLT >; + + public: + + typedef typename Base::Scalar Scalar; + typedef typename Base::RealScalar RealScalar; + typedef typename Base::StorageIndex StorageIndex; + enum { UpLo = _UpLo }; + using Base::compute; + + PardisoLLT() + : Base() + { + pardisoInit(Base::ScalarIsComplex ? 4 : 2); + } + + explicit PardisoLLT(const MatrixType& matrix) + : Base() + { + pardisoInit(Base::ScalarIsComplex ? 4 : 2); + compute(matrix); + } + + protected: + + void getMatrix(const MatrixType& matrix) + { + // PARDISO supports only upper, row-major matrices + PermutationMatrix p_null; + m_matrix.resize(matrix.rows(), matrix.cols()); + m_matrix.template selfadjointView() = matrix.template selfadjointView().twistedBy(p_null); + m_matrix.makeCompressed(); + } +}; + +/** \ingroup PardisoSupport_Module + * \class PardisoLDLT + * \brief A sparse direct Cholesky (LDLT) factorization and solver based on the PARDISO library + * + * This class allows to solve for A.X = B sparse linear problems via a LDL^T Cholesky factorization + * using the Intel MKL PARDISO library. The sparse matrix A is assumed to be selfajoint and positive definite. + * For complex matrices, A can also be symmetric only, see the \a Options template parameter. + * The vectors or matrices X and B can be either dense or sparse. + * + * By default, it runs in in-core mode. To enable PARDISO's out-of-core feature, set: + * \code solver.pardisoParameterArray()[59] = 1; \endcode + * + * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam Options can be any bitwise combination of Upper, Lower, and Symmetric. The default is Upper, meaning only the upper triangular part has to be used. + * Symmetric can be used for symmetric, non-selfadjoint complex matrices, the default being to assume a selfadjoint matrix. + * Upper|Lower can be used to tell both triangular parts can be used as input. + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class SimplicialLDLT + */ +template +class PardisoLDLT : public PardisoImpl< PardisoLDLT > +{ + protected: + typedef PardisoImpl< PardisoLDLT > Base; + using Base::pardisoInit; + using Base::m_matrix; + friend class PardisoImpl< PardisoLDLT >; + + public: + + typedef typename Base::Scalar Scalar; + typedef typename Base::RealScalar RealScalar; + typedef typename Base::StorageIndex StorageIndex; + using Base::compute; + enum { UpLo = Options&(Upper|Lower) }; + + PardisoLDLT() + : Base() + { + pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2); + } + + explicit PardisoLDLT(const MatrixType& matrix) + : Base() + { + pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2); + compute(matrix); + } + + void getMatrix(const MatrixType& matrix) + { + // PARDISO supports only upper, row-major matrices + PermutationMatrix p_null; + m_matrix.resize(matrix.rows(), matrix.cols()); + m_matrix.template selfadjointView() = matrix.template selfadjointView().twistedBy(p_null); + m_matrix.makeCompressed(); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_PARDISOSUPPORT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SPQRSupport/SuiteSparseQRSupport.h b/vendor/eigen/include/eigen3/Eigen/src/SPQRSupport/SuiteSparseQRSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..013c7ae7a9cc0149ab07654f5c1f59f7f1c3d42a --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SPQRSupport/SuiteSparseQRSupport.h @@ -0,0 +1,335 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Desire Nuentsa +// Copyright (C) 2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SUITESPARSEQRSUPPORT_H +#define EIGEN_SUITESPARSEQRSUPPORT_H + +namespace Eigen { + + template class SPQR; + template struct SPQRMatrixQReturnType; + template struct SPQRMatrixQTransposeReturnType; + template struct SPQR_QProduct; + namespace internal { + template struct traits > + { + typedef typename SPQRType::MatrixType ReturnType; + }; + template struct traits > + { + typedef typename SPQRType::MatrixType ReturnType; + }; + template struct traits > + { + typedef typename Derived::PlainObject ReturnType; + }; + } // End namespace internal + +/** + * \ingroup SPQRSupport_Module + * \class SPQR + * \brief Sparse QR factorization based on SuiteSparseQR library + * + * This class is used to perform a multithreaded and multifrontal rank-revealing QR decomposition + * of sparse matrices. The result is then used to solve linear leasts_square systems. + * Clearly, a QR factorization is returned such that A*P = Q*R where : + * + * P is the column permutation. Use colsPermutation() to get it. + * + * Q is the orthogonal matrix represented as Householder reflectors. + * Use matrixQ() to get an expression and matrixQ().transpose() to get the transpose. + * You can then apply it to a vector. + * + * R is the sparse triangular factor. Use matrixQR() to get it as SparseMatrix. + * NOTE : The Index type of R is always SuiteSparse_long. You can get it with SPQR::Index + * + * \tparam _MatrixType The type of the sparse matrix A, must be a column-major SparseMatrix<> + * + * \implsparsesolverconcept + * + * + */ +template +class SPQR : public SparseSolverBase > +{ + protected: + typedef SparseSolverBase > Base; + using Base::m_isInitialized; + public: + typedef typename _MatrixType::Scalar Scalar; + typedef typename _MatrixType::RealScalar RealScalar; + typedef SuiteSparse_long StorageIndex ; + typedef SparseMatrix MatrixType; + typedef Map > PermutationType; + enum { + ColsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic + }; + public: + SPQR() + : m_analysisIsOk(false), + m_factorizationIsOk(false), + m_isRUpToDate(false), + m_ordering(SPQR_ORDERING_DEFAULT), + m_allow_tol(SPQR_DEFAULT_TOL), + m_tolerance (NumTraits::epsilon()), + m_cR(0), + m_E(0), + m_H(0), + m_HPinv(0), + m_HTau(0), + m_useDefaultThreshold(true) + { + cholmod_l_start(&m_cc); + } + + explicit SPQR(const _MatrixType& matrix) + : m_analysisIsOk(false), + m_factorizationIsOk(false), + m_isRUpToDate(false), + m_ordering(SPQR_ORDERING_DEFAULT), + m_allow_tol(SPQR_DEFAULT_TOL), + m_tolerance (NumTraits::epsilon()), + m_cR(0), + m_E(0), + m_H(0), + m_HPinv(0), + m_HTau(0), + m_useDefaultThreshold(true) + { + cholmod_l_start(&m_cc); + compute(matrix); + } + + ~SPQR() + { + SPQR_free(); + cholmod_l_finish(&m_cc); + } + void SPQR_free() + { + cholmod_l_free_sparse(&m_H, &m_cc); + cholmod_l_free_sparse(&m_cR, &m_cc); + cholmod_l_free_dense(&m_HTau, &m_cc); + std::free(m_E); + std::free(m_HPinv); + } + + void compute(const _MatrixType& matrix) + { + if(m_isInitialized) SPQR_free(); + + MatrixType mat(matrix); + + /* Compute the default threshold as in MatLab, see: + * Tim Davis, "Algorithm 915, SuiteSparseQR: Multifrontal Multithreaded Rank-Revealing + * Sparse QR Factorization, ACM Trans. on Math. Soft. 38(1), 2011, Page 8:3 + */ + RealScalar pivotThreshold = m_tolerance; + if(m_useDefaultThreshold) + { + RealScalar max2Norm = 0.0; + for (int j = 0; j < mat.cols(); j++) max2Norm = numext::maxi(max2Norm, mat.col(j).norm()); + if(max2Norm==RealScalar(0)) + max2Norm = RealScalar(1); + pivotThreshold = 20 * (mat.rows() + mat.cols()) * max2Norm * NumTraits::epsilon(); + } + cholmod_sparse A; + A = viewAsCholmod(mat); + m_rows = matrix.rows(); + Index col = matrix.cols(); + m_rank = SuiteSparseQR(m_ordering, pivotThreshold, col, &A, + &m_cR, &m_E, &m_H, &m_HPinv, &m_HTau, &m_cc); + + if (!m_cR) + { + m_info = NumericalIssue; + m_isInitialized = false; + return; + } + m_info = Success; + m_isInitialized = true; + m_isRUpToDate = false; + } + /** + * Get the number of rows of the input matrix and the Q matrix + */ + inline Index rows() const {return m_rows; } + + /** + * Get the number of columns of the input matrix. + */ + inline Index cols() const { return m_cR->ncol; } + + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const + { + eigen_assert(m_isInitialized && " The QR factorization should be computed first, call compute()"); + eigen_assert(b.cols()==1 && "This method is for vectors only"); + + //Compute Q^T * b + typename Dest::PlainObject y, y2; + y = matrixQ().transpose() * b; + + // Solves with the triangular matrix R + Index rk = this->rank(); + y2 = y; + y.resize((std::max)(cols(),Index(y.rows())),y.cols()); + y.topRows(rk) = this->matrixR().topLeftCorner(rk, rk).template triangularView().solve(y2.topRows(rk)); + + // Apply the column permutation + // colsPermutation() performs a copy of the permutation, + // so let's apply it manually: + for(Index i = 0; i < rk; ++i) dest.row(m_E[i]) = y.row(i); + for(Index i = rk; i < cols(); ++i) dest.row(m_E[i]).setZero(); + +// y.bottomRows(y.rows()-rk).setZero(); +// dest = colsPermutation() * y.topRows(cols()); + + m_info = Success; + } + + /** \returns the sparse triangular factor R. It is a sparse matrix + */ + const MatrixType matrixR() const + { + eigen_assert(m_isInitialized && " The QR factorization should be computed first, call compute()"); + if(!m_isRUpToDate) { + m_R = viewAsEigen(*m_cR); + m_isRUpToDate = true; + } + return m_R; + } + /// Get an expression of the matrix Q + SPQRMatrixQReturnType matrixQ() const + { + return SPQRMatrixQReturnType(*this); + } + /// Get the permutation that was applied to columns of A + PermutationType colsPermutation() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return PermutationType(m_E, m_cR->ncol); + } + /** + * Gets the rank of the matrix. + * It should be equal to matrixQR().cols if the matrix is full-rank + */ + Index rank() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_cc.SPQR_istat[4]; + } + /// Set the fill-reducing ordering method to be used + void setSPQROrdering(int ord) { m_ordering = ord;} + /// Set the tolerance tol to treat columns with 2-norm < =tol as zero + void setPivotThreshold(const RealScalar& tol) + { + m_useDefaultThreshold = false; + m_tolerance = tol; + } + + /** \returns a pointer to the SPQR workspace */ + cholmod_common *cholmodCommon() const { return &m_cc; } + + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the sparse QR can not be computed + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + protected: + bool m_analysisIsOk; + bool m_factorizationIsOk; + mutable bool m_isRUpToDate; + mutable ComputationInfo m_info; + int m_ordering; // Ordering method to use, see SPQR's manual + int m_allow_tol; // Allow to use some tolerance during numerical factorization. + RealScalar m_tolerance; // treat columns with 2-norm below this tolerance as zero + mutable cholmod_sparse *m_cR; // The sparse R factor in cholmod format + mutable MatrixType m_R; // The sparse matrix R in Eigen format + mutable StorageIndex *m_E; // The permutation applied to columns + mutable cholmod_sparse *m_H; //The householder vectors + mutable StorageIndex *m_HPinv; // The row permutation of H + mutable cholmod_dense *m_HTau; // The Householder coefficients + mutable Index m_rank; // The rank of the matrix + mutable cholmod_common m_cc; // Workspace and parameters + bool m_useDefaultThreshold; // Use default threshold + Index m_rows; + template friend struct SPQR_QProduct; +}; + +template +struct SPQR_QProduct : ReturnByValue > +{ + typedef typename SPQRType::Scalar Scalar; + typedef typename SPQRType::StorageIndex StorageIndex; + //Define the constructor to get reference to argument types + SPQR_QProduct(const SPQRType& spqr, const Derived& other, bool transpose) : m_spqr(spqr),m_other(other),m_transpose(transpose) {} + + inline Index rows() const { return m_transpose ? m_spqr.rows() : m_spqr.cols(); } + inline Index cols() const { return m_other.cols(); } + // Assign to a vector + template + void evalTo(ResType& res) const + { + cholmod_dense y_cd; + cholmod_dense *x_cd; + int method = m_transpose ? SPQR_QTX : SPQR_QX; + cholmod_common *cc = m_spqr.cholmodCommon(); + y_cd = viewAsCholmod(m_other.const_cast_derived()); + x_cd = SuiteSparseQR_qmult(method, m_spqr.m_H, m_spqr.m_HTau, m_spqr.m_HPinv, &y_cd, cc); + res = Matrix::Map(reinterpret_cast(x_cd->x), x_cd->nrow, x_cd->ncol); + cholmod_l_free_dense(&x_cd, cc); + } + const SPQRType& m_spqr; + const Derived& m_other; + bool m_transpose; + +}; +template +struct SPQRMatrixQReturnType{ + + SPQRMatrixQReturnType(const SPQRType& spqr) : m_spqr(spqr) {} + template + SPQR_QProduct operator*(const MatrixBase& other) + { + return SPQR_QProduct(m_spqr,other.derived(),false); + } + SPQRMatrixQTransposeReturnType adjoint() const + { + return SPQRMatrixQTransposeReturnType(m_spqr); + } + // To use for operations with the transpose of Q + SPQRMatrixQTransposeReturnType transpose() const + { + return SPQRMatrixQTransposeReturnType(m_spqr); + } + const SPQRType& m_spqr; +}; + +template +struct SPQRMatrixQTransposeReturnType{ + SPQRMatrixQTransposeReturnType(const SPQRType& spqr) : m_spqr(spqr) {} + template + SPQR_QProduct operator*(const MatrixBase& other) + { + return SPQR_QProduct(m_spqr,other.derived(), true); + } + const SPQRType& m_spqr; +}; + +}// End namespace Eigen +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..948650253b5d773252c0118c765868ad0d2fd2df --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h @@ -0,0 +1,352 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H +#define EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H + +namespace Eigen { + +namespace internal { + +template +static void conservative_sparse_sparse_product_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res, bool sortedInsertion = false) +{ + typedef typename remove_all::type::Scalar LhsScalar; + typedef typename remove_all::type::Scalar RhsScalar; + typedef typename remove_all::type::Scalar ResScalar; + + // make sure to call innerSize/outerSize since we fake the storage order. + Index rows = lhs.innerSize(); + Index cols = rhs.outerSize(); + eigen_assert(lhs.outerSize() == rhs.innerSize()); + + ei_declare_aligned_stack_constructed_variable(bool, mask, rows, 0); + ei_declare_aligned_stack_constructed_variable(ResScalar, values, rows, 0); + ei_declare_aligned_stack_constructed_variable(Index, indices, rows, 0); + + std::memset(mask,0,sizeof(bool)*rows); + + evaluator lhsEval(lhs); + evaluator rhsEval(rhs); + + // estimate the number of non zero entries + // given a rhs column containing Y non zeros, we assume that the respective Y columns + // of the lhs differs in average of one non zeros, thus the number of non zeros for + // the product of a rhs column with the lhs is X+Y where X is the average number of non zero + // per column of the lhs. + // Therefore, we have nnz(lhs*rhs) = nnz(lhs) + nnz(rhs) + Index estimated_nnz_prod = lhsEval.nonZerosEstimate() + rhsEval.nonZerosEstimate(); + + res.setZero(); + res.reserve(Index(estimated_nnz_prod)); + // we compute each column of the result, one after the other + for (Index j=0; j::InnerIterator rhsIt(rhsEval, j); rhsIt; ++rhsIt) + { + RhsScalar y = rhsIt.value(); + Index k = rhsIt.index(); + for (typename evaluator::InnerIterator lhsIt(lhsEval, k); lhsIt; ++lhsIt) + { + Index i = lhsIt.index(); + LhsScalar x = lhsIt.value(); + if(!mask[i]) + { + mask[i] = true; + values[i] = x * y; + indices[nnz] = i; + ++nnz; + } + else + values[i] += x * y; + } + } + if(!sortedInsertion) + { + // unordered insertion + for(Index k=0; k use a quick sort + // otherwise => loop through the entire vector + // In order to avoid to perform an expensive log2 when the + // result is clearly very sparse we use a linear bound up to 200. + if((nnz<200 && nnz1) std::sort(indices,indices+nnz); + for(Index k=0; k::Flags&RowMajorBit) ? RowMajor : ColMajor, + int RhsStorageOrder = (traits::Flags&RowMajorBit) ? RowMajor : ColMajor, + int ResStorageOrder = (traits::Flags&RowMajorBit) ? RowMajor : ColMajor> +struct conservative_sparse_sparse_product_selector; + +template +struct conservative_sparse_sparse_product_selector +{ + typedef typename remove_all::type LhsCleaned; + typedef typename LhsCleaned::Scalar Scalar; + + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix RowMajorMatrix; + typedef SparseMatrix ColMajorMatrixAux; + typedef typename sparse_eval::type ColMajorMatrix; + + // If the result is tall and thin (in the extreme case a column vector) + // then it is faster to sort the coefficients inplace instead of transposing twice. + // FIXME, the following heuristic is probably not very good. + if(lhs.rows()>rhs.cols()) + { + ColMajorMatrix resCol(lhs.rows(),rhs.cols()); + // perform sorted insertion + internal::conservative_sparse_sparse_product_impl(lhs, rhs, resCol, true); + res = resCol.markAsRValue(); + } + else + { + ColMajorMatrixAux resCol(lhs.rows(),rhs.cols()); + // resort to transpose to sort the entries + internal::conservative_sparse_sparse_product_impl(lhs, rhs, resCol, false); + RowMajorMatrix resRow(resCol); + res = resRow.markAsRValue(); + } + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix RowMajorRhs; + typedef SparseMatrix RowMajorRes; + RowMajorRhs rhsRow = rhs; + RowMajorRes resRow(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(rhsRow, lhs, resRow); + res = resRow; + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix RowMajorLhs; + typedef SparseMatrix RowMajorRes; + RowMajorLhs lhsRow = lhs; + RowMajorRes resRow(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(rhs, lhsRow, resRow); + res = resRow; + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix RowMajorMatrix; + RowMajorMatrix resRow(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(rhs, lhs, resRow); + res = resRow; + } +}; + + +template +struct conservative_sparse_sparse_product_selector +{ + typedef typename traits::type>::Scalar Scalar; + + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix ColMajorMatrix; + ColMajorMatrix resCol(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(lhs, rhs, resCol); + res = resCol; + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix ColMajorLhs; + typedef SparseMatrix ColMajorRes; + ColMajorLhs lhsCol = lhs; + ColMajorRes resCol(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(lhsCol, rhs, resCol); + res = resCol; + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix ColMajorRhs; + typedef SparseMatrix ColMajorRes; + ColMajorRhs rhsCol = rhs; + ColMajorRes resCol(lhs.rows(), rhs.cols()); + internal::conservative_sparse_sparse_product_impl(lhs, rhsCol, resCol); + res = resCol; + } +}; + +template +struct conservative_sparse_sparse_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix RowMajorMatrix; + typedef SparseMatrix ColMajorMatrix; + RowMajorMatrix resRow(lhs.rows(),rhs.cols()); + internal::conservative_sparse_sparse_product_impl(rhs, lhs, resRow); + // sort the non zeros: + ColMajorMatrix resCol(resRow); + res = resCol; + } +}; + +} // end namespace internal + + +namespace internal { + +template +static void sparse_sparse_to_dense_product_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res) +{ + typedef typename remove_all::type::Scalar LhsScalar; + typedef typename remove_all::type::Scalar RhsScalar; + Index cols = rhs.outerSize(); + eigen_assert(lhs.outerSize() == rhs.innerSize()); + + evaluator lhsEval(lhs); + evaluator rhsEval(rhs); + + for (Index j=0; j::InnerIterator rhsIt(rhsEval, j); rhsIt; ++rhsIt) + { + RhsScalar y = rhsIt.value(); + Index k = rhsIt.index(); + for (typename evaluator::InnerIterator lhsIt(lhsEval, k); lhsIt; ++lhsIt) + { + Index i = lhsIt.index(); + LhsScalar x = lhsIt.value(); + res.coeffRef(i,j) += x * y; + } + } + } +} + + +} // end namespace internal + +namespace internal { + +template::Flags&RowMajorBit) ? RowMajor : ColMajor, + int RhsStorageOrder = (traits::Flags&RowMajorBit) ? RowMajor : ColMajor> +struct sparse_sparse_to_dense_product_selector; + +template +struct sparse_sparse_to_dense_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + internal::sparse_sparse_to_dense_product_impl(lhs, rhs, res); + } +}; + +template +struct sparse_sparse_to_dense_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix ColMajorLhs; + ColMajorLhs lhsCol(lhs); + internal::sparse_sparse_to_dense_product_impl(lhsCol, rhs, res); + } +}; + +template +struct sparse_sparse_to_dense_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + typedef SparseMatrix ColMajorRhs; + ColMajorRhs rhsCol(rhs); + internal::sparse_sparse_to_dense_product_impl(lhs, rhsCol, res); + } +}; + +template +struct sparse_sparse_to_dense_product_selector +{ + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res) + { + Transpose trRes(res); + internal::sparse_sparse_to_dense_product_impl >(rhs, lhs, trRes); + } +}; + + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CONSERVATIVESPARSESPARSEPRODUCT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..67718c85be99e933ab23606d1c87c639552fc206 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h @@ -0,0 +1,67 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MAPPED_SPARSEMATRIX_H +#define EIGEN_MAPPED_SPARSEMATRIX_H + +namespace Eigen { + +/** \deprecated Use Map > + * \class MappedSparseMatrix + * + * \brief Sparse matrix + * + * \param _Scalar the scalar type, i.e. the type of the coefficients + * + * See http://www.netlib.org/linalg/html_templates/node91.html for details on the storage scheme. + * + */ +namespace internal { +template +struct traits > : traits > +{}; +} // end namespace internal + +template +class MappedSparseMatrix + : public Map > +{ + typedef Map > Base; + + public: + + typedef typename Base::StorageIndex StorageIndex; + typedef typename Base::Scalar Scalar; + + inline MappedSparseMatrix(Index rows, Index cols, Index nnz, StorageIndex* outerIndexPtr, StorageIndex* innerIndexPtr, Scalar* valuePtr, StorageIndex* innerNonZeroPtr = 0) + : Base(rows, cols, nnz, outerIndexPtr, innerIndexPtr, valuePtr, innerNonZeroPtr) + {} + + /** Empty destructor */ + inline ~MappedSparseMatrix() {} +}; + +namespace internal { + +template +struct evaluator > + : evaluator > > +{ + typedef MappedSparseMatrix<_Scalar,_Options,_StorageIndex> XprType; + typedef evaluator > Base; + + evaluator() : Base() {} + explicit evaluator(const XprType &mat) : Base(mat) {} +}; + +} + +} // end namespace Eigen + +#endif // EIGEN_MAPPED_SPARSEMATRIX_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseAssign.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseAssign.h new file mode 100644 index 0000000000000000000000000000000000000000..905485c88ed11bc8c5a6c731459b84aa20d1e5c3 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseAssign.h @@ -0,0 +1,270 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEASSIGN_H +#define EIGEN_SPARSEASSIGN_H + +namespace Eigen { + +template +template +Derived& SparseMatrixBase::operator=(const EigenBase &other) +{ + internal::call_assignment_no_alias(derived(), other.derived()); + return derived(); +} + +template +template +Derived& SparseMatrixBase::operator=(const ReturnByValue& other) +{ + // TODO use the evaluator mechanism + other.evalTo(derived()); + return derived(); +} + +template +template +inline Derived& SparseMatrixBase::operator=(const SparseMatrixBase& other) +{ + // by default sparse evaluation do not alias, so we can safely bypass the generic call_assignment routine + internal::Assignment > + ::run(derived(), other.derived(), internal::assign_op()); + return derived(); +} + +template +inline Derived& SparseMatrixBase::operator=(const Derived& other) +{ + internal::call_assignment_no_alias(derived(), other.derived()); + return derived(); +} + +namespace internal { + +template<> +struct storage_kind_to_evaluator_kind { + typedef IteratorBased Kind; +}; + +template<> +struct storage_kind_to_shape { + typedef SparseShape Shape; +}; + +struct Sparse2Sparse {}; +struct Sparse2Dense {}; + +template<> struct AssignmentKind { typedef Sparse2Sparse Kind; }; +template<> struct AssignmentKind { typedef Sparse2Sparse Kind; }; +template<> struct AssignmentKind { typedef Sparse2Dense Kind; }; +template<> struct AssignmentKind { typedef Sparse2Dense Kind; }; + + +template +void assign_sparse_to_sparse(DstXprType &dst, const SrcXprType &src) +{ + typedef typename DstXprType::Scalar Scalar; + typedef internal::evaluator DstEvaluatorType; + typedef internal::evaluator SrcEvaluatorType; + + SrcEvaluatorType srcEvaluator(src); + + const bool transpose = (DstEvaluatorType::Flags & RowMajorBit) != (SrcEvaluatorType::Flags & RowMajorBit); + const Index outerEvaluationSize = (SrcEvaluatorType::Flags&RowMajorBit) ? src.rows() : src.cols(); + if ((!transpose) && src.isRValue()) + { + // eval without temporary + dst.resize(src.rows(), src.cols()); + dst.setZero(); + dst.reserve((std::min)(src.rows()*src.cols(), (std::max)(src.rows(),src.cols())*2)); + for (Index j=0; j::SupportedAccessPatterns & OuterRandomAccessPattern)==OuterRandomAccessPattern) || + (!((DstEvaluatorType::Flags & RowMajorBit) != (SrcEvaluatorType::Flags & RowMajorBit)))) && + "the transpose operation is supposed to be handled in SparseMatrix::operator="); + + enum { Flip = (DstEvaluatorType::Flags & RowMajorBit) != (SrcEvaluatorType::Flags & RowMajorBit) }; + + + DstXprType temp(src.rows(), src.cols()); + + temp.reserve((std::min)(src.rows()*src.cols(), (std::max)(src.rows(),src.cols())*2)); + for (Index j=0; j +struct Assignment +{ + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &/*func*/) + { + assign_sparse_to_sparse(dst.derived(), src.derived()); + } +}; + +// Generic Sparse to Dense assignment +template< typename DstXprType, typename SrcXprType, typename Functor, typename Weak> +struct Assignment +{ + static void run(DstXprType &dst, const SrcXprType &src, const Functor &func) + { + if(internal::is_same >::value) + dst.setZero(); + + internal::evaluator srcEval(src); + resize_if_allowed(dst, src, func); + internal::evaluator dstEval(dst); + + const Index outerEvaluationSize = (internal::evaluator::Flags&RowMajorBit) ? src.rows() : src.cols(); + for (Index j=0; j::InnerIterator i(srcEval,j); i; ++i) + func.assignCoeff(dstEval.coeffRef(i.row(),i.col()), i.value()); + } +}; + +// Specialization for dense ?= dense +/- sparse and dense ?= sparse +/- dense +template +struct assignment_from_dense_op_sparse +{ + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const InitialFunc& /*func*/) + { + #ifdef EIGEN_SPARSE_ASSIGNMENT_FROM_DENSE_OP_SPARSE_PLUGIN + EIGEN_SPARSE_ASSIGNMENT_FROM_DENSE_OP_SPARSE_PLUGIN + #endif + + call_assignment_no_alias(dst, src.lhs(), Func1()); + call_assignment_no_alias(dst, src.rhs(), Func2()); + } + + // Specialization for dense1 = sparse + dense2; -> dense1 = dense2; dense1 += sparse; + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename internal::enable_if::Shape,DenseShape>::value>::type + run(DstXprType &dst, const CwiseBinaryOp, const Lhs, const Rhs> &src, + const internal::assign_op& /*func*/) + { + #ifdef EIGEN_SPARSE_ASSIGNMENT_FROM_SPARSE_ADD_DENSE_PLUGIN + EIGEN_SPARSE_ASSIGNMENT_FROM_SPARSE_ADD_DENSE_PLUGIN + #endif + + // Apply the dense matrix first, then the sparse one. + call_assignment_no_alias(dst, src.rhs(), Func1()); + call_assignment_no_alias(dst, src.lhs(), Func2()); + } + + // Specialization for dense1 = sparse - dense2; -> dense1 = -dense2; dense1 += sparse; + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename internal::enable_if::Shape,DenseShape>::value>::type + run(DstXprType &dst, const CwiseBinaryOp, const Lhs, const Rhs> &src, + const internal::assign_op& /*func*/) + { + #ifdef EIGEN_SPARSE_ASSIGNMENT_FROM_SPARSE_SUB_DENSE_PLUGIN + EIGEN_SPARSE_ASSIGNMENT_FROM_SPARSE_SUB_DENSE_PLUGIN + #endif + + // Apply the dense matrix first, then the sparse one. + call_assignment_no_alias(dst, -src.rhs(), Func1()); + call_assignment_no_alias(dst, src.lhs(), add_assign_op()); + } +}; + +#define EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(ASSIGN_OP,BINOP,ASSIGN_OP2) \ + template< typename DstXprType, typename Lhs, typename Rhs, typename Scalar> \ + struct Assignment, const Lhs, const Rhs>, internal::ASSIGN_OP, \ + Sparse2Dense, \ + typename internal::enable_if< internal::is_same::Shape,DenseShape>::value \ + || internal::is_same::Shape,DenseShape>::value>::type> \ + : assignment_from_dense_op_sparse, internal::ASSIGN_OP2 > \ + {} + +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(assign_op, scalar_sum_op,add_assign_op); +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(add_assign_op,scalar_sum_op,add_assign_op); +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(sub_assign_op,scalar_sum_op,sub_assign_op); + +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(assign_op, scalar_difference_op,sub_assign_op); +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(add_assign_op,scalar_difference_op,sub_assign_op); +EIGEN_CATCH_ASSIGN_DENSE_OP_SPARSE(sub_assign_op,scalar_difference_op,add_assign_op); + + +// Specialization for "dst = dec.solve(rhs)" +// NOTE we need to specialize it for Sparse2Sparse to avoid ambiguous specialization error +template +struct Assignment, internal::assign_op, Sparse2Sparse> +{ + typedef Solve SrcXprType; + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + src.dec()._solve_impl(src.rhs(), dst); + } +}; + +struct Diagonal2Sparse {}; + +template<> struct AssignmentKind { typedef Diagonal2Sparse Kind; }; + +template< typename DstXprType, typename SrcXprType, typename Functor> +struct Assignment +{ + typedef typename DstXprType::StorageIndex StorageIndex; + typedef typename DstXprType::Scalar Scalar; + + template + static void run(SparseMatrix &dst, const SrcXprType &src, const AssignFunc &func) + { dst.assignDiagonal(src.diagonal(), func); } + + template + static void run(SparseMatrixBase &dst, const SrcXprType &src, const internal::assign_op &/*func*/) + { dst.derived().diagonal() = src.diagonal(); } + + template + static void run(SparseMatrixBase &dst, const SrcXprType &src, const internal::add_assign_op &/*func*/) + { dst.derived().diagonal() += src.diagonal(); } + + template + static void run(SparseMatrixBase &dst, const SrcXprType &src, const internal::sub_assign_op &/*func*/) + { dst.derived().diagonal() -= src.diagonal(); } +}; +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSEASSIGN_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDenseProduct.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDenseProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..f005a18a18e2b35e57fb56349f191edf8825f3da --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDenseProduct.h @@ -0,0 +1,342 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEDENSEPRODUCT_H +#define EIGEN_SPARSEDENSEPRODUCT_H + +namespace Eigen { + +namespace internal { + +template <> struct product_promote_storage_type { typedef Sparse ret; }; +template <> struct product_promote_storage_type { typedef Sparse ret; }; + +template +struct sparse_time_dense_product_impl; + +template +struct sparse_time_dense_product_impl +{ + typedef typename internal::remove_all::type Lhs; + typedef typename internal::remove_all::type Rhs; + typedef typename internal::remove_all::type Res; + typedef typename evaluator::InnerIterator LhsInnerIterator; + typedef evaluator LhsEval; + static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const typename Res::Scalar& alpha) + { + LhsEval lhsEval(lhs); + + Index n = lhs.outerSize(); +#ifdef EIGEN_HAS_OPENMP + Eigen::initParallel(); + Index threads = Eigen::nbThreads(); +#endif + + for(Index c=0; c1 && lhsEval.nonZerosEstimate() > 20000) + { + #pragma omp parallel for schedule(dynamic,(n+threads*4-1)/(threads*4)) num_threads(threads) + for(Index i=0; i let's disable it for now as it is conflicting with generic scalar*matrix and matrix*scalar operators +// template +// struct ScalarBinaryOpTraits > +// { +// enum { +// Defined = 1 +// }; +// typedef typename CwiseUnaryOp, T2>::PlainObject ReturnType; +// }; + +template +struct sparse_time_dense_product_impl +{ + typedef typename internal::remove_all::type Lhs; + typedef typename internal::remove_all::type Rhs; + typedef typename internal::remove_all::type Res; + typedef evaluator LhsEval; + typedef typename LhsEval::InnerIterator LhsInnerIterator; + static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha) + { + LhsEval lhsEval(lhs); + for(Index c=0; c::ReturnType rhs_j(alpha * rhs.coeff(j,c)); + for(LhsInnerIterator it(lhsEval,j); it ;++it) + res.coeffRef(it.index(),c) += it.value() * rhs_j; + } + } + } +}; + +template +struct sparse_time_dense_product_impl +{ + typedef typename internal::remove_all::type Lhs; + typedef typename internal::remove_all::type Rhs; + typedef typename internal::remove_all::type Res; + typedef evaluator LhsEval; + typedef typename LhsEval::InnerIterator LhsInnerIterator; + static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const typename Res::Scalar& alpha) + { + Index n = lhs.rows(); + LhsEval lhsEval(lhs); + +#ifdef EIGEN_HAS_OPENMP + Eigen::initParallel(); + Index threads = Eigen::nbThreads(); + // This 20000 threshold has been found experimentally on 2D and 3D Poisson problems. + // It basically represents the minimal amount of work to be done to be worth it. + if(threads>1 && lhsEval.nonZerosEstimate()*rhs.cols() > 20000) + { + #pragma omp parallel for schedule(dynamic,(n+threads*4-1)/(threads*4)) num_threads(threads) + for(Index i=0; i +struct sparse_time_dense_product_impl +{ + typedef typename internal::remove_all::type Lhs; + typedef typename internal::remove_all::type Rhs; + typedef typename internal::remove_all::type Res; + typedef typename evaluator::InnerIterator LhsInnerIterator; + static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const typename Res::Scalar& alpha) + { + evaluator lhsEval(lhs); + for(Index j=0; j +inline void sparse_time_dense_product(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha) +{ + sparse_time_dense_product_impl::run(lhs, rhs, res, alpha); +} + +} // end namespace internal + +namespace internal { + +template +struct generic_product_impl + : generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + typedef typename nested_eval::type LhsNested; + typedef typename nested_eval::type RhsNested; + LhsNested lhsNested(lhs); + RhsNested rhsNested(rhs); + internal::sparse_time_dense_product(lhsNested, rhsNested, dst, alpha); + } +}; + +template +struct generic_product_impl + : generic_product_impl +{}; + +template +struct generic_product_impl + : generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + typedef typename nested_eval::type LhsNested; + typedef typename nested_eval::type RhsNested; + LhsNested lhsNested(lhs); + RhsNested rhsNested(rhs); + + // transpose everything + Transpose dstT(dst); + internal::sparse_time_dense_product(rhsNested.transpose(), lhsNested.transpose(), dstT, alpha); + } +}; + +template +struct generic_product_impl + : generic_product_impl +{}; + +template +struct sparse_dense_outer_product_evaluator +{ +protected: + typedef typename conditional::type Lhs1; + typedef typename conditional::type ActualRhs; + typedef Product ProdXprType; + + // if the actual left-hand side is a dense vector, + // then build a sparse-view so that we can seamlessly iterate over it. + typedef typename conditional::StorageKind,Sparse>::value, + Lhs1, SparseView >::type ActualLhs; + typedef typename conditional::StorageKind,Sparse>::value, + Lhs1 const&, SparseView >::type LhsArg; + + typedef evaluator LhsEval; + typedef evaluator RhsEval; + typedef typename evaluator::InnerIterator LhsIterator; + typedef typename ProdXprType::Scalar Scalar; + +public: + enum { + Flags = NeedToTranspose ? RowMajorBit : 0, + CoeffReadCost = HugeCost + }; + + class InnerIterator : public LhsIterator + { + public: + InnerIterator(const sparse_dense_outer_product_evaluator &xprEval, Index outer) + : LhsIterator(xprEval.m_lhsXprImpl, 0), + m_outer(outer), + m_empty(false), + m_factor(get(xprEval.m_rhsXprImpl, outer, typename internal::traits::StorageKind() )) + {} + + EIGEN_STRONG_INLINE Index outer() const { return m_outer; } + EIGEN_STRONG_INLINE Index row() const { return NeedToTranspose ? m_outer : LhsIterator::index(); } + EIGEN_STRONG_INLINE Index col() const { return NeedToTranspose ? LhsIterator::index() : m_outer; } + + EIGEN_STRONG_INLINE Scalar value() const { return LhsIterator::value() * m_factor; } + EIGEN_STRONG_INLINE operator bool() const { return LhsIterator::operator bool() && (!m_empty); } + + protected: + Scalar get(const RhsEval &rhs, Index outer, Dense = Dense()) const + { + return rhs.coeff(outer); + } + + Scalar get(const RhsEval &rhs, Index outer, Sparse = Sparse()) + { + typename RhsEval::InnerIterator it(rhs, outer); + if (it && it.index()==0 && it.value()!=Scalar(0)) + return it.value(); + m_empty = true; + return Scalar(0); + } + + Index m_outer; + bool m_empty; + Scalar m_factor; + }; + + sparse_dense_outer_product_evaluator(const Lhs1 &lhs, const ActualRhs &rhs) + : m_lhs(lhs), m_lhsXprImpl(m_lhs), m_rhsXprImpl(rhs) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + // transpose case + sparse_dense_outer_product_evaluator(const ActualRhs &rhs, const Lhs1 &lhs) + : m_lhs(lhs), m_lhsXprImpl(m_lhs), m_rhsXprImpl(rhs) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + +protected: + const LhsArg m_lhs; + evaluator m_lhsXprImpl; + evaluator m_rhsXprImpl; +}; + +// sparse * dense outer product +template +struct product_evaluator, OuterProduct, SparseShape, DenseShape> + : sparse_dense_outer_product_evaluator +{ + typedef sparse_dense_outer_product_evaluator Base; + + typedef Product XprType; + typedef typename XprType::PlainObject PlainObject; + + explicit product_evaluator(const XprType& xpr) + : Base(xpr.lhs(), xpr.rhs()) + {} + +}; + +template +struct product_evaluator, OuterProduct, DenseShape, SparseShape> + : sparse_dense_outer_product_evaluator +{ + typedef sparse_dense_outer_product_evaluator Base; + + typedef Product XprType; + typedef typename XprType::PlainObject PlainObject; + + explicit product_evaluator(const XprType& xpr) + : Base(xpr.lhs(), xpr.rhs()) + {} + +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSEDENSEPRODUCT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..941c03be3dea31dc05fb79a3ed8006791db46bed --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h @@ -0,0 +1,138 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_DIAGONAL_PRODUCT_H +#define EIGEN_SPARSE_DIAGONAL_PRODUCT_H + +namespace Eigen { + +// The product of a diagonal matrix with a sparse matrix can be easily +// implemented using expression template. +// We have two consider very different cases: +// 1 - diag * row-major sparse +// => each inner vector <=> scalar * sparse vector product +// => so we can reuse CwiseUnaryOp::InnerIterator +// 2 - diag * col-major sparse +// => each inner vector <=> densevector * sparse vector cwise product +// => again, we can reuse specialization of CwiseBinaryOp::InnerIterator +// for that particular case +// The two other cases are symmetric. + +namespace internal { + +enum { + SDP_AsScalarProduct, + SDP_AsCwiseProduct +}; + +template +struct sparse_diagonal_product_evaluator; + +template +struct product_evaluator, ProductTag, DiagonalShape, SparseShape> + : public sparse_diagonal_product_evaluator +{ + typedef Product XprType; + enum { CoeffReadCost = HugeCost, Flags = Rhs::Flags&RowMajorBit, Alignment = 0 }; // FIXME CoeffReadCost & Flags + + typedef sparse_diagonal_product_evaluator Base; + explicit product_evaluator(const XprType& xpr) : Base(xpr.rhs(), xpr.lhs().diagonal()) {} +}; + +template +struct product_evaluator, ProductTag, SparseShape, DiagonalShape> + : public sparse_diagonal_product_evaluator, Lhs::Flags&RowMajorBit?SDP_AsCwiseProduct:SDP_AsScalarProduct> +{ + typedef Product XprType; + enum { CoeffReadCost = HugeCost, Flags = Lhs::Flags&RowMajorBit, Alignment = 0 }; // FIXME CoeffReadCost & Flags + + typedef sparse_diagonal_product_evaluator, Lhs::Flags&RowMajorBit?SDP_AsCwiseProduct:SDP_AsScalarProduct> Base; + explicit product_evaluator(const XprType& xpr) : Base(xpr.lhs(), xpr.rhs().diagonal().transpose()) {} +}; + +template +struct sparse_diagonal_product_evaluator +{ +protected: + typedef typename evaluator::InnerIterator SparseXprInnerIterator; + typedef typename SparseXprType::Scalar Scalar; + +public: + class InnerIterator : public SparseXprInnerIterator + { + public: + InnerIterator(const sparse_diagonal_product_evaluator &xprEval, Index outer) + : SparseXprInnerIterator(xprEval.m_sparseXprImpl, outer), + m_coeff(xprEval.m_diagCoeffImpl.coeff(outer)) + {} + + EIGEN_STRONG_INLINE Scalar value() const { return m_coeff * SparseXprInnerIterator::value(); } + protected: + typename DiagonalCoeffType::Scalar m_coeff; + }; + + sparse_diagonal_product_evaluator(const SparseXprType &sparseXpr, const DiagonalCoeffType &diagCoeff) + : m_sparseXprImpl(sparseXpr), m_diagCoeffImpl(diagCoeff) + {} + + Index nonZerosEstimate() const { return m_sparseXprImpl.nonZerosEstimate(); } + +protected: + evaluator m_sparseXprImpl; + evaluator m_diagCoeffImpl; +}; + + +template +struct sparse_diagonal_product_evaluator +{ + typedef typename SparseXprType::Scalar Scalar; + typedef typename SparseXprType::StorageIndex StorageIndex; + + typedef typename nested_eval::type DiagCoeffNested; + + class InnerIterator + { + typedef typename evaluator::InnerIterator SparseXprIter; + public: + InnerIterator(const sparse_diagonal_product_evaluator &xprEval, Index outer) + : m_sparseIter(xprEval.m_sparseXprEval, outer), m_diagCoeffNested(xprEval.m_diagCoeffNested) + {} + + inline Scalar value() const { return m_sparseIter.value() * m_diagCoeffNested.coeff(index()); } + inline StorageIndex index() const { return m_sparseIter.index(); } + inline Index outer() const { return m_sparseIter.outer(); } + inline Index col() const { return SparseXprType::IsRowMajor ? m_sparseIter.index() : m_sparseIter.outer(); } + inline Index row() const { return SparseXprType::IsRowMajor ? m_sparseIter.outer() : m_sparseIter.index(); } + + EIGEN_STRONG_INLINE InnerIterator& operator++() { ++m_sparseIter; return *this; } + inline operator bool() const { return m_sparseIter; } + + protected: + SparseXprIter m_sparseIter; + DiagCoeffNested m_diagCoeffNested; + }; + + sparse_diagonal_product_evaluator(const SparseXprType &sparseXpr, const DiagCoeffType &diagCoeff) + : m_sparseXprEval(sparseXpr), m_diagCoeffNested(diagCoeff) + {} + + Index nonZerosEstimate() const { return m_sparseXprEval.nonZerosEstimate(); } + +protected: + evaluator m_sparseXprEval; + DiagCoeffNested m_diagCoeffNested; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSE_DIAGONAL_PRODUCT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseRef.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseRef.h new file mode 100644 index 0000000000000000000000000000000000000000..748f87d62639028b2306af14d26a7503d60524a6 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseRef.h @@ -0,0 +1,397 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_REF_H +#define EIGEN_SPARSE_REF_H + +namespace Eigen { + +enum { + StandardCompressedFormat = 2 /**< used by Ref to specify whether the input storage must be in standard compressed form */ +}; + +namespace internal { + +template class SparseRefBase; + +template +struct traits, _Options, _StrideType> > + : public traits > +{ + typedef SparseMatrix PlainObjectType; + enum { + Options = _Options, + Flags = traits::Flags | CompressedAccessBit | NestByRefBit + }; + + template struct match { + enum { + StorageOrderMatch = PlainObjectType::IsVectorAtCompileTime || Derived::IsVectorAtCompileTime || ((PlainObjectType::Flags&RowMajorBit)==(Derived::Flags&RowMajorBit)), + MatchAtCompileTime = (Derived::Flags&CompressedAccessBit) && StorageOrderMatch + }; + typedef typename internal::conditional::type type; + }; + +}; + +template +struct traits, _Options, _StrideType> > + : public traits, _Options, _StrideType> > +{ + enum { + Flags = (traits >::Flags | CompressedAccessBit | NestByRefBit) & ~LvalueBit + }; +}; + +template +struct traits, _Options, _StrideType> > + : public traits > +{ + typedef SparseVector PlainObjectType; + enum { + Options = _Options, + Flags = traits::Flags | CompressedAccessBit | NestByRefBit + }; + + template struct match { + enum { + MatchAtCompileTime = (Derived::Flags&CompressedAccessBit) && Derived::IsVectorAtCompileTime + }; + typedef typename internal::conditional::type type; + }; + +}; + +template +struct traits, _Options, _StrideType> > + : public traits, _Options, _StrideType> > +{ + enum { + Flags = (traits >::Flags | CompressedAccessBit | NestByRefBit) & ~LvalueBit + }; +}; + +template +struct traits > : public traits {}; + +template class SparseRefBase + : public SparseMapBase +{ +public: + + typedef SparseMapBase Base; + EIGEN_SPARSE_PUBLIC_INTERFACE(SparseRefBase) + + SparseRefBase() + : Base(RowsAtCompileTime==Dynamic?0:RowsAtCompileTime,ColsAtCompileTime==Dynamic?0:ColsAtCompileTime, 0, 0, 0, 0, 0) + {} + +protected: + + template + void construct(Expression& expr) + { + if(expr.outerIndexPtr()==0) + ::new (static_cast(this)) Base(expr.size(), expr.nonZeros(), expr.innerIndexPtr(), expr.valuePtr()); + else + ::new (static_cast(this)) Base(expr.rows(), expr.cols(), expr.nonZeros(), expr.outerIndexPtr(), expr.innerIndexPtr(), expr.valuePtr(), expr.innerNonZeroPtr()); + } +}; + +} // namespace internal + + +/** + * \ingroup SparseCore_Module + * + * \brief A sparse matrix expression referencing an existing sparse expression + * + * \tparam SparseMatrixType the equivalent sparse matrix type of the referenced data, it must be a template instance of class SparseMatrix. + * \tparam Options specifies whether the a standard compressed format is required \c Options is \c #StandardCompressedFormat, or \c 0. + * The default is \c 0. + * + * \sa class Ref + */ +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +class Ref, Options, StrideType > + : public internal::SparseRefBase, Options, StrideType > > +#else +template +class Ref + : public SparseMapBase // yes, that's weird to use Derived here, but that works! +#endif +{ + typedef SparseMatrix PlainObjectType; + typedef internal::traits Traits; + template + inline Ref(const SparseMatrix& expr); + template + inline Ref(const MappedSparseMatrix& expr); + public: + + typedef internal::SparseRefBase Base; + EIGEN_SPARSE_PUBLIC_INTERFACE(Ref) + + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + inline Ref(SparseMatrix& expr) + { + EIGEN_STATIC_ASSERT(bool(Traits::template match >::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + eigen_assert( ((Options & int(StandardCompressedFormat))==0) || (expr.isCompressed()) ); + Base::construct(expr.derived()); + } + + template + inline Ref(MappedSparseMatrix& expr) + { + EIGEN_STATIC_ASSERT(bool(Traits::template match >::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + eigen_assert( ((Options & int(StandardCompressedFormat))==0) || (expr.isCompressed()) ); + Base::construct(expr.derived()); + } + + template + inline Ref(const SparseCompressedBase& expr) + #else + /** Implicit constructor from any sparse expression (2D matrix or 1D vector) */ + template + inline Ref(SparseCompressedBase& expr) + #endif + { + EIGEN_STATIC_ASSERT(bool(internal::is_lvalue::value), THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + eigen_assert( ((Options & int(StandardCompressedFormat))==0) || (expr.isCompressed()) ); + Base::construct(expr.const_cast_derived()); + } +}; + +// this is the const ref version +template +class Ref, Options, StrideType> + : public internal::SparseRefBase, Options, StrideType> > +{ + typedef SparseMatrix TPlainObjectType; + typedef internal::traits Traits; + public: + + typedef internal::SparseRefBase Base; + EIGEN_SPARSE_PUBLIC_INTERFACE(Ref) + + template + inline Ref(const SparseMatrixBase& expr) : m_hasCopy(false) + { + construct(expr.derived(), typename Traits::template match::type()); + } + + inline Ref(const Ref& other) : Base(other), m_hasCopy(false) { + // copy constructor shall not copy the m_object, to avoid unnecessary malloc and copy + } + + template + inline Ref(const RefBase& other) : m_hasCopy(false) { + construct(other.derived(), typename Traits::template match::type()); + } + + ~Ref() { + if(m_hasCopy) { + TPlainObjectType* obj = reinterpret_cast(&m_storage); + obj->~TPlainObjectType(); + } + } + + protected: + + template + void construct(const Expression& expr,internal::true_type) + { + if((Options & int(StandardCompressedFormat)) && (!expr.isCompressed())) + { + TPlainObjectType* obj = reinterpret_cast(&m_storage); + ::new (obj) TPlainObjectType(expr); + m_hasCopy = true; + Base::construct(*obj); + } + else + { + Base::construct(expr); + } + } + + template + void construct(const Expression& expr, internal::false_type) + { + TPlainObjectType* obj = reinterpret_cast(&m_storage); + ::new (obj) TPlainObjectType(expr); + m_hasCopy = true; + Base::construct(*obj); + } + + protected: + typename internal::aligned_storage::type m_storage; + bool m_hasCopy; +}; + + + +/** + * \ingroup SparseCore_Module + * + * \brief A sparse vector expression referencing an existing sparse vector expression + * + * \tparam SparseVectorType the equivalent sparse vector type of the referenced data, it must be a template instance of class SparseVector. + * + * \sa class Ref + */ +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +class Ref, Options, StrideType > + : public internal::SparseRefBase, Options, StrideType > > +#else +template +class Ref + : public SparseMapBase +#endif +{ + typedef SparseVector PlainObjectType; + typedef internal::traits Traits; + template + inline Ref(const SparseVector& expr); + public: + + typedef internal::SparseRefBase Base; + EIGEN_SPARSE_PUBLIC_INTERFACE(Ref) + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + inline Ref(SparseVector& expr) + { + EIGEN_STATIC_ASSERT(bool(Traits::template match >::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + Base::construct(expr.derived()); + } + + template + inline Ref(const SparseCompressedBase& expr) + #else + /** Implicit constructor from any 1D sparse vector expression */ + template + inline Ref(SparseCompressedBase& expr) + #endif + { + EIGEN_STATIC_ASSERT(bool(internal::is_lvalue::value), THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + Base::construct(expr.const_cast_derived()); + } +}; + +// this is the const ref version +template +class Ref, Options, StrideType> + : public internal::SparseRefBase, Options, StrideType> > +{ + typedef SparseVector TPlainObjectType; + typedef internal::traits Traits; + public: + + typedef internal::SparseRefBase Base; + EIGEN_SPARSE_PUBLIC_INTERFACE(Ref) + + template + inline Ref(const SparseMatrixBase& expr) : m_hasCopy(false) + { + construct(expr.derived(), typename Traits::template match::type()); + } + + inline Ref(const Ref& other) : Base(other), m_hasCopy(false) { + // copy constructor shall not copy the m_object, to avoid unnecessary malloc and copy + } + + template + inline Ref(const RefBase& other) : m_hasCopy(false) { + construct(other.derived(), typename Traits::template match::type()); + } + + ~Ref() { + if(m_hasCopy) { + TPlainObjectType* obj = reinterpret_cast(&m_storage); + obj->~TPlainObjectType(); + } + } + + protected: + + template + void construct(const Expression& expr,internal::true_type) + { + Base::construct(expr); + } + + template + void construct(const Expression& expr, internal::false_type) + { + TPlainObjectType* obj = reinterpret_cast(&m_storage); + ::new (obj) TPlainObjectType(expr); + m_hasCopy = true; + Base::construct(*obj); + } + + protected: + typename internal::aligned_storage::type m_storage; + bool m_hasCopy; +}; + +namespace internal { + +// FIXME shall we introduce a general evaluatior_ref that we can specialize for any sparse object once, and thus remove this copy-pasta thing... + +template +struct evaluator, Options, StrideType> > + : evaluator, Options, StrideType> > > +{ + typedef evaluator, Options, StrideType> > > Base; + typedef Ref, Options, StrideType> XprType; + evaluator() : Base() {} + explicit evaluator(const XprType &mat) : Base(mat) {} +}; + +template +struct evaluator, Options, StrideType> > + : evaluator, Options, StrideType> > > +{ + typedef evaluator, Options, StrideType> > > Base; + typedef Ref, Options, StrideType> XprType; + evaluator() : Base() {} + explicit evaluator(const XprType &mat) : Base(mat) {} +}; + +template +struct evaluator, Options, StrideType> > + : evaluator, Options, StrideType> > > +{ + typedef evaluator, Options, StrideType> > > Base; + typedef Ref, Options, StrideType> XprType; + evaluator() : Base() {} + explicit evaluator(const XprType &mat) : Base(mat) {} +}; + +template +struct evaluator, Options, StrideType> > + : evaluator, Options, StrideType> > > +{ + typedef evaluator, Options, StrideType> > > Base; + typedef Ref, Options, StrideType> XprType; + evaluator() : Base() {} + explicit evaluator(const XprType &mat) : Base(mat) {} +}; + +} + +} // end namespace Eigen + +#endif // EIGEN_SPARSE_REF_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSolverBase.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSolverBase.h new file mode 100644 index 0000000000000000000000000000000000000000..b4c9a422f057a66913a33827d6f91eb22d954a5b --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSolverBase.h @@ -0,0 +1,124 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSESOLVERBASE_H +#define EIGEN_SPARSESOLVERBASE_H + +namespace Eigen { + +namespace internal { + + /** \internal + * Helper functions to solve with a sparse right-hand-side and result. + * The rhs is decomposed into small vertical panels which are solved through dense temporaries. + */ +template +typename enable_if::type +solve_sparse_through_dense_panels(const Decomposition &dec, const Rhs& rhs, Dest &dest) +{ + EIGEN_STATIC_ASSERT((Dest::Flags&RowMajorBit)==0,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + typedef typename Dest::Scalar DestScalar; + // we process the sparse rhs per block of NbColsAtOnce columns temporarily stored into a dense matrix. + static const Index NbColsAtOnce = 4; + Index rhsCols = rhs.cols(); + Index size = rhs.rows(); + // the temporary matrices do not need more columns than NbColsAtOnce: + Index tmpCols = (std::min)(rhsCols, NbColsAtOnce); + Eigen::Matrix tmp(size,tmpCols); + Eigen::Matrix tmpX(size,tmpCols); + for(Index k=0; k(rhsCols-k, NbColsAtOnce); + tmp.leftCols(actualCols) = rhs.middleCols(k,actualCols); + tmpX.leftCols(actualCols) = dec.solve(tmp.leftCols(actualCols)); + dest.middleCols(k,actualCols) = tmpX.leftCols(actualCols).sparseView(); + } +} + +// Overload for vector as rhs +template +typename enable_if::type +solve_sparse_through_dense_panels(const Decomposition &dec, const Rhs& rhs, Dest &dest) +{ + typedef typename Dest::Scalar DestScalar; + Index size = rhs.rows(); + Eigen::Matrix rhs_dense(rhs); + Eigen::Matrix dest_dense(size); + dest_dense = dec.solve(rhs_dense); + dest = dest_dense.sparseView(); +} + +} // end namespace internal + +/** \class SparseSolverBase + * \ingroup SparseCore_Module + * \brief A base class for sparse solvers + * + * \tparam Derived the actual type of the solver. + * + */ +template +class SparseSolverBase : internal::noncopyable +{ + public: + + /** Default constructor */ + SparseSolverBase() + : m_isInitialized(false) + {} + + ~SparseSolverBase() + {} + + Derived& derived() { return *static_cast(this); } + const Derived& derived() const { return *static_cast(this); } + + /** \returns an expression of the solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * \sa compute() + */ + template + inline const Solve + solve(const MatrixBase& b) const + { + eigen_assert(m_isInitialized && "Solver is not initialized."); + eigen_assert(derived().rows()==b.rows() && "solve(): invalid number of rows of the right hand side matrix b"); + return Solve(derived(), b.derived()); + } + + /** \returns an expression of the solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * \sa compute() + */ + template + inline const Solve + solve(const SparseMatrixBase& b) const + { + eigen_assert(m_isInitialized && "Solver is not initialized."); + eigen_assert(derived().rows()==b.rows() && "solve(): invalid number of rows of the right hand side matrix b"); + return Solve(derived(), b.derived()); + } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal default implementation of solving with a sparse rhs */ + template + void _solve_impl(const SparseMatrixBase &b, SparseMatrixBase &dest) const + { + internal::solve_sparse_through_dense_panels(derived(), b.derived(), dest.derived()); + } + #endif // EIGEN_PARSED_BY_DOXYGEN + + protected: + + mutable bool m_isInitialized; +}; + +} // end namespace Eigen + +#endif // EIGEN_SPARSESOLVERBASE_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h new file mode 100644 index 0000000000000000000000000000000000000000..88820a48f364a8a7663ad37d0a9505550cdcba44 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h @@ -0,0 +1,198 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H +#define EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H + +namespace Eigen { + +namespace internal { + + +// perform a pseudo in-place sparse * sparse product assuming all matrices are col major +template +static void sparse_sparse_product_with_pruning_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res, const typename ResultType::RealScalar& tolerance) +{ + // return sparse_sparse_product_with_pruning_impl2(lhs,rhs,res); + + typedef typename remove_all::type::Scalar RhsScalar; + typedef typename remove_all::type::Scalar ResScalar; + typedef typename remove_all::type::StorageIndex StorageIndex; + + // make sure to call innerSize/outerSize since we fake the storage order. + Index rows = lhs.innerSize(); + Index cols = rhs.outerSize(); + //Index size = lhs.outerSize(); + eigen_assert(lhs.outerSize() == rhs.innerSize()); + + // allocate a temporary buffer + AmbiVector tempVector(rows); + + // mimics a resizeByInnerOuter: + if(ResultType::IsRowMajor) + res.resize(cols, rows); + else + res.resize(rows, cols); + + evaluator lhsEval(lhs); + evaluator rhsEval(rhs); + + // estimate the number of non zero entries + // given a rhs column containing Y non zeros, we assume that the respective Y columns + // of the lhs differs in average of one non zeros, thus the number of non zeros for + // the product of a rhs column with the lhs is X+Y where X is the average number of non zero + // per column of the lhs. + // Therefore, we have nnz(lhs*rhs) = nnz(lhs) + nnz(rhs) + Index estimated_nnz_prod = lhsEval.nonZerosEstimate() + rhsEval.nonZerosEstimate(); + + res.reserve(estimated_nnz_prod); + double ratioColRes = double(estimated_nnz_prod)/(double(lhs.rows())*double(rhs.cols())); + for (Index j=0; j::InnerIterator rhsIt(rhsEval, j); rhsIt; ++rhsIt) + { + // FIXME should be written like this: tmp += rhsIt.value() * lhs.col(rhsIt.index()) + tempVector.restart(); + RhsScalar x = rhsIt.value(); + for (typename evaluator::InnerIterator lhsIt(lhsEval, rhsIt.index()); lhsIt; ++lhsIt) + { + tempVector.coeffRef(lhsIt.index()) += lhsIt.value() * x; + } + } + res.startVec(j); + for (typename AmbiVector::Iterator it(tempVector,tolerance); it; ++it) + res.insertBackByOuterInner(j,it.index()) = it.value(); + } + res.finalize(); +} + +template::Flags&RowMajorBit, + int RhsStorageOrder = traits::Flags&RowMajorBit, + int ResStorageOrder = traits::Flags&RowMajorBit> +struct sparse_sparse_product_with_pruning_selector; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typename remove_all::type _res(res.rows(), res.cols()); + internal::sparse_sparse_product_with_pruning_impl(lhs, rhs, _res, tolerance); + res.swap(_res); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + // we need a col-major matrix to hold the result + typedef SparseMatrix SparseTemporaryType; + SparseTemporaryType _res(res.rows(), res.cols()); + internal::sparse_sparse_product_with_pruning_impl(lhs, rhs, _res, tolerance); + res = _res; + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + // let's transpose the product to get a column x column product + typename remove_all::type _res(res.rows(), res.cols()); + internal::sparse_sparse_product_with_pruning_impl(rhs, lhs, _res, tolerance); + res.swap(_res); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typedef SparseMatrix ColMajorMatrixLhs; + typedef SparseMatrix ColMajorMatrixRhs; + ColMajorMatrixLhs colLhs(lhs); + ColMajorMatrixRhs colRhs(rhs); + internal::sparse_sparse_product_with_pruning_impl(colLhs, colRhs, res, tolerance); + + // let's transpose the product to get a column x column product +// typedef SparseMatrix SparseTemporaryType; +// SparseTemporaryType _res(res.cols(), res.rows()); +// sparse_sparse_product_with_pruning_impl(rhs, lhs, _res); +// res = _res.transpose(); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typedef SparseMatrix RowMajorMatrixLhs; + RowMajorMatrixLhs rowLhs(lhs); + sparse_sparse_product_with_pruning_selector(rowLhs,rhs,res,tolerance); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typedef SparseMatrix RowMajorMatrixRhs; + RowMajorMatrixRhs rowRhs(rhs); + sparse_sparse_product_with_pruning_selector(lhs,rowRhs,res,tolerance); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typedef SparseMatrix ColMajorMatrixRhs; + ColMajorMatrixRhs colRhs(rhs); + internal::sparse_sparse_product_with_pruning_impl(lhs, colRhs, res, tolerance); + } +}; + +template +struct sparse_sparse_product_with_pruning_selector +{ + typedef typename ResultType::RealScalar RealScalar; + static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance) + { + typedef SparseMatrix ColMajorMatrixLhs; + ColMajorMatrixLhs colLhs(lhs); + internal::sparse_sparse_product_with_pruning_impl(colLhs, rhs, res, tolerance); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseTriangularView.h b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseTriangularView.h new file mode 100644 index 0000000000000000000000000000000000000000..9ac120266a802556a47d2b59a0adcd4f803730ae --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseCore/SparseTriangularView.h @@ -0,0 +1,189 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2015 Gael Guennebaud +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_TRIANGULARVIEW_H +#define EIGEN_SPARSE_TRIANGULARVIEW_H + +namespace Eigen { + +/** \ingroup SparseCore_Module + * + * \brief Base class for a triangular part in a \b sparse matrix + * + * This class is an abstract base class of class TriangularView, and objects of type TriangularViewImpl cannot be instantiated. + * It extends class TriangularView with additional methods which are available for sparse expressions only. + * + * \sa class TriangularView, SparseMatrixBase::triangularView() + */ +template class TriangularViewImpl + : public SparseMatrixBase > +{ + enum { SkipFirst = ((Mode&Lower) && !(MatrixType::Flags&RowMajorBit)) + || ((Mode&Upper) && (MatrixType::Flags&RowMajorBit)), + SkipLast = !SkipFirst, + SkipDiag = (Mode&ZeroDiag) ? 1 : 0, + HasUnitDiag = (Mode&UnitDiag) ? 1 : 0 + }; + + typedef TriangularView TriangularViewType; + + protected: + // dummy solve function to make TriangularView happy. + void solve() const; + + typedef SparseMatrixBase Base; + public: + + EIGEN_SPARSE_PUBLIC_INTERFACE(TriangularViewType) + + typedef typename MatrixType::Nested MatrixTypeNested; + typedef typename internal::remove_reference::type MatrixTypeNestedNonRef; + typedef typename internal::remove_all::type MatrixTypeNestedCleaned; + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _solve_impl(const RhsType &rhs, DstType &dst) const { + if(!(internal::is_same::value && internal::extract_data(dst) == internal::extract_data(rhs))) + dst = rhs; + this->solveInPlace(dst); + } + + /** Applies the inverse of \c *this to the dense vector or matrix \a other, "in-place" */ + template void solveInPlace(MatrixBase& other) const; + + /** Applies the inverse of \c *this to the sparse vector or matrix \a other, "in-place" */ + template void solveInPlace(SparseMatrixBase& other) const; + +}; + +namespace internal { + +template +struct unary_evaluator, IteratorBased> + : evaluator_base > +{ + typedef TriangularView XprType; + +protected: + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::StorageIndex StorageIndex; + typedef typename evaluator::InnerIterator EvalIterator; + + enum { SkipFirst = ((Mode&Lower) && !(ArgType::Flags&RowMajorBit)) + || ((Mode&Upper) && (ArgType::Flags&RowMajorBit)), + SkipLast = !SkipFirst, + SkipDiag = (Mode&ZeroDiag) ? 1 : 0, + HasUnitDiag = (Mode&UnitDiag) ? 1 : 0 + }; + +public: + + enum { + CoeffReadCost = evaluator::CoeffReadCost, + Flags = XprType::Flags + }; + + explicit unary_evaluator(const XprType &xpr) : m_argImpl(xpr.nestedExpression()), m_arg(xpr.nestedExpression()) {} + + inline Index nonZerosEstimate() const { + return m_argImpl.nonZerosEstimate(); + } + + class InnerIterator : public EvalIterator + { + typedef EvalIterator Base; + public: + + EIGEN_STRONG_INLINE InnerIterator(const unary_evaluator& xprEval, Index outer) + : Base(xprEval.m_argImpl,outer), m_returnOne(false), m_containsDiag(Base::outer()index()<=outer : this->index()=Base::outer())) + { + if((!SkipFirst) && Base::operator bool()) + Base::operator++(); + m_returnOne = m_containsDiag; + } + } + + EIGEN_STRONG_INLINE InnerIterator& operator++() + { + if(HasUnitDiag && m_returnOne) + m_returnOne = false; + else + { + Base::operator++(); + if(HasUnitDiag && (!SkipFirst) && ((!Base::operator bool()) || Base::index()>=Base::outer())) + { + if((!SkipFirst) && Base::operator bool()) + Base::operator++(); + m_returnOne = m_containsDiag; + } + } + return *this; + } + + EIGEN_STRONG_INLINE operator bool() const + { + if(HasUnitDiag && m_returnOne) + return true; + if(SkipFirst) return Base::operator bool(); + else + { + if (SkipDiag) return (Base::operator bool() && this->index() < this->outer()); + else return (Base::operator bool() && this->index() <= this->outer()); + } + } + +// inline Index row() const { return (ArgType::Flags&RowMajorBit ? Base::outer() : this->index()); } +// inline Index col() const { return (ArgType::Flags&RowMajorBit ? this->index() : Base::outer()); } + inline StorageIndex index() const + { + if(HasUnitDiag && m_returnOne) return internal::convert_index(Base::outer()); + else return Base::index(); + } + inline Scalar value() const + { + if(HasUnitDiag && m_returnOne) return Scalar(1); + else return Base::value(); + } + + protected: + bool m_returnOne; + bool m_containsDiag; + private: + Scalar& valueRef(); + }; + +protected: + evaluator m_argImpl; + const ArgType& m_arg; +}; + +} // end namespace internal + +template +template +inline const TriangularView +SparseMatrixBase::triangularView() const +{ + return TriangularView(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_SPARSE_TRIANGULARVIEW_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU.h new file mode 100644 index 0000000000000000000000000000000000000000..0c8d8939be2e21089f6883341b4339d5f4868536 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU.h @@ -0,0 +1,923 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_SPARSE_LU_H +#define EIGEN_SPARSE_LU_H + +namespace Eigen { + +template > class SparseLU; +template struct SparseLUMatrixLReturnType; +template struct SparseLUMatrixUReturnType; + +template +class SparseLUTransposeView : public SparseSolverBase > +{ +protected: + typedef SparseSolverBase > APIBase; + using APIBase::m_isInitialized; +public: + typedef typename SparseLUType::Scalar Scalar; + typedef typename SparseLUType::StorageIndex StorageIndex; + typedef typename SparseLUType::MatrixType MatrixType; + typedef typename SparseLUType::OrderingType OrderingType; + + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + SparseLUTransposeView() : m_sparseLU(NULL) {} + SparseLUTransposeView(const SparseLUTransposeView& view) { + this->m_sparseLU = view.m_sparseLU; + } + void setIsInitialized(const bool isInitialized) {this->m_isInitialized = isInitialized;} + void setSparseLU(SparseLUType* sparseLU) {m_sparseLU = sparseLU;} + using APIBase::_solve_impl; + template + bool _solve_impl(const MatrixBase &B, MatrixBase &X_base) const + { + Dest& X(X_base.derived()); + eigen_assert(m_sparseLU->info() == Success && "The matrix should be factorized first"); + EIGEN_STATIC_ASSERT((Dest::Flags&RowMajorBit)==0, + THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + + + // this ugly const_cast_derived() helps to detect aliasing when applying the permutations + for(Index j = 0; j < B.cols(); ++j){ + X.col(j) = m_sparseLU->colsPermutation() * B.const_cast_derived().col(j); + } + //Forward substitution with transposed or adjoint of U + m_sparseLU->matrixU().template solveTransposedInPlace(X); + + //Backward substitution with transposed or adjoint of L + m_sparseLU->matrixL().template solveTransposedInPlace(X); + + // Permute back the solution + for (Index j = 0; j < B.cols(); ++j) + X.col(j) = m_sparseLU->rowsPermutation().transpose() * X.col(j); + return true; + } + inline Index rows() const { return m_sparseLU->rows(); } + inline Index cols() const { return m_sparseLU->cols(); } + +private: + SparseLUType *m_sparseLU; + SparseLUTransposeView& operator=(const SparseLUTransposeView&); +}; + + +/** \ingroup SparseLU_Module + * \class SparseLU + * + * \brief Sparse supernodal LU factorization for general matrices + * + * This class implements the supernodal LU factorization for general matrices. + * It uses the main techniques from the sequential SuperLU package + * (http://crd-legacy.lbl.gov/~xiaoye/SuperLU/). It handles transparently real + * and complex arithmetic with single and double precision, depending on the + * scalar type of your input matrix. + * The code has been optimized to provide BLAS-3 operations during supernode-panel updates. + * It benefits directly from the built-in high-performant Eigen BLAS routines. + * Moreover, when the size of a supernode is very small, the BLAS calls are avoided to + * enable a better optimization from the compiler. For best performance, + * you should compile it with NDEBUG flag to avoid the numerous bounds checking on vectors. + * + * An important parameter of this class is the ordering method. It is used to reorder the columns + * (and eventually the rows) of the matrix to reduce the number of new elements that are created during + * numerical factorization. The cheapest method available is COLAMD. + * See \link OrderingMethods_Module the OrderingMethods module \endlink for the list of + * built-in and external ordering methods. + * + * Simple example with key steps + * \code + * VectorXd x(n), b(n); + * SparseMatrix A; + * SparseLU, COLAMDOrdering > solver; + * // fill A and b; + * // Compute the ordering permutation vector from the structural pattern of A + * solver.analyzePattern(A); + * // Compute the numerical factorization + * solver.factorize(A); + * //Use the factors to solve the linear system + * x = solver.solve(b); + * \endcode + * + * \warning The input matrix A should be in a \b compressed and \b column-major form. + * Otherwise an expensive copy will be made. You can call the inexpensive makeCompressed() to get a compressed matrix. + * + * \note Unlike the initial SuperLU implementation, there is no step to equilibrate the matrix. + * For badly scaled matrices, this step can be useful to reduce the pivoting during factorization. + * If this is the case for your matrices, you can try the basic scaling method at + * "unsupported/Eigen/src/IterativeSolvers/Scaling.h" + * + * \tparam _MatrixType The type of the sparse matrix. It must be a column-major SparseMatrix<> + * \tparam _OrderingType The ordering method to use, either AMD, COLAMD or METIS. Default is COLMAD + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept + * \sa \ref OrderingMethods_Module + */ +template +class SparseLU : public SparseSolverBase >, public internal::SparseLUImpl +{ + protected: + typedef SparseSolverBase > APIBase; + using APIBase::m_isInitialized; + public: + using APIBase::_solve_impl; + + typedef _MatrixType MatrixType; + typedef _OrderingType OrderingType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef SparseMatrix NCMatrix; + typedef internal::MappedSuperNodalMatrix SCMatrix; + typedef Matrix ScalarVector; + typedef Matrix IndexVector; + typedef PermutationMatrix PermutationType; + typedef internal::SparseLUImpl Base; + + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + SparseLU():m_lastError(""),m_Ustore(0,0,0,0,0,0),m_symmetricmode(false),m_diagpivotthresh(1.0),m_detPermR(1) + { + initperfvalues(); + } + explicit SparseLU(const MatrixType& matrix) + : m_lastError(""),m_Ustore(0,0,0,0,0,0),m_symmetricmode(false),m_diagpivotthresh(1.0),m_detPermR(1) + { + initperfvalues(); + compute(matrix); + } + + ~SparseLU() + { + // Free all explicit dynamic pointers + } + + void analyzePattern (const MatrixType& matrix); + void factorize (const MatrixType& matrix); + void simplicialfactorize(const MatrixType& matrix); + + /** + * Compute the symbolic and numeric factorization of the input sparse matrix. + * The input matrix should be in column-major storage. + */ + void compute (const MatrixType& matrix) + { + // Analyze + analyzePattern(matrix); + //Factorize + factorize(matrix); + } + + /** \returns an expression of the transposed of the factored matrix. + * + * A typical usage is to solve for the transposed problem A^T x = b: + * \code + * solver.compute(A); + * x = solver.transpose().solve(b); + * \endcode + * + * \sa adjoint(), solve() + */ + const SparseLUTransposeView > transpose() + { + SparseLUTransposeView > transposeView; + transposeView.setSparseLU(this); + transposeView.setIsInitialized(this->m_isInitialized); + return transposeView; + } + + + /** \returns an expression of the adjoint of the factored matrix + * + * A typical usage is to solve for the adjoint problem A' x = b: + * \code + * solver.compute(A); + * x = solver.adjoint().solve(b); + * \endcode + * + * For real scalar types, this function is equivalent to transpose(). + * + * \sa transpose(), solve() + */ + const SparseLUTransposeView > adjoint() + { + SparseLUTransposeView > adjointView; + adjointView.setSparseLU(this); + adjointView.setIsInitialized(this->m_isInitialized); + return adjointView; + } + + inline Index rows() const { return m_mat.rows(); } + inline Index cols() const { return m_mat.cols(); } + /** Indicate that the pattern of the input matrix is symmetric */ + void isSymmetric(bool sym) + { + m_symmetricmode = sym; + } + + /** \returns an expression of the matrix L, internally stored as supernodes + * The only operation available with this expression is the triangular solve + * \code + * y = b; matrixL().solveInPlace(y); + * \endcode + */ + SparseLUMatrixLReturnType matrixL() const + { + return SparseLUMatrixLReturnType(m_Lstore); + } + /** \returns an expression of the matrix U, + * The only operation available with this expression is the triangular solve + * \code + * y = b; matrixU().solveInPlace(y); + * \endcode + */ + SparseLUMatrixUReturnType > matrixU() const + { + return SparseLUMatrixUReturnType >(m_Lstore, m_Ustore); + } + + /** + * \returns a reference to the row matrix permutation \f$ P_r \f$ such that \f$P_r A P_c^T = L U\f$ + * \sa colsPermutation() + */ + inline const PermutationType& rowsPermutation() const + { + return m_perm_r; + } + /** + * \returns a reference to the column matrix permutation\f$ P_c^T \f$ such that \f$P_r A P_c^T = L U\f$ + * \sa rowsPermutation() + */ + inline const PermutationType& colsPermutation() const + { + return m_perm_c; + } + /** Set the threshold used for a diagonal entry to be an acceptable pivot. */ + void setPivotThreshold(const RealScalar& thresh) + { + m_diagpivotthresh = thresh; + } + +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** \returns the solution X of \f$ A X = B \f$ using the current decomposition of A. + * + * \warning the destination matrix X in X = this->solve(B) must be colmun-major. + * + * \sa compute() + */ + template + inline const Solve solve(const MatrixBase& B) const; +#endif // EIGEN_PARSED_BY_DOXYGEN + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the LU factorization reports a problem, zero diagonal for instance + * \c InvalidInput if the input matrix is invalid + * + * \sa iparm() + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + /** + * \returns A string describing the type of error + */ + std::string lastErrorMessage() const + { + return m_lastError; + } + + template + bool _solve_impl(const MatrixBase &B, MatrixBase &X_base) const + { + Dest& X(X_base.derived()); + eigen_assert(m_factorizationIsOk && "The matrix should be factorized first"); + EIGEN_STATIC_ASSERT((Dest::Flags&RowMajorBit)==0, + THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + + // Permute the right hand side to form X = Pr*B + // on return, X is overwritten by the computed solution + X.resize(B.rows(),B.cols()); + + // this ugly const_cast_derived() helps to detect aliasing when applying the permutations + for(Index j = 0; j < B.cols(); ++j) + X.col(j) = rowsPermutation() * B.const_cast_derived().col(j); + + //Forward substitution with L + this->matrixL().solveInPlace(X); + this->matrixU().solveInPlace(X); + + // Permute back the solution + for (Index j = 0; j < B.cols(); ++j) + X.col(j) = colsPermutation().inverse() * X.col(j); + + return true; + } + + /** + * \returns the absolute value of the determinant of the matrix of which + * *this is the QR decomposition. + * + * \warning a determinant can be very big or small, so for matrices + * of large enough dimension, there is a risk of overflow/underflow. + * One way to work around that is to use logAbsDeterminant() instead. + * + * \sa logAbsDeterminant(), signDeterminant() + */ + Scalar absDeterminant() + { + using std::abs; + eigen_assert(m_factorizationIsOk && "The matrix should be factorized first."); + // Initialize with the determinant of the row matrix + Scalar det = Scalar(1.); + // Note that the diagonal blocks of U are stored in supernodes, + // which are available in the L part :) + for (Index j = 0; j < this->cols(); ++j) + { + for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) + { + if(it.index() == j) + { + det *= abs(it.value()); + break; + } + } + } + return det; + } + + /** \returns the natural log of the absolute value of the determinant of the matrix + * of which **this is the QR decomposition + * + * \note This method is useful to work around the risk of overflow/underflow that's + * inherent to the determinant computation. + * + * \sa absDeterminant(), signDeterminant() + */ + Scalar logAbsDeterminant() const + { + using std::log; + using std::abs; + + eigen_assert(m_factorizationIsOk && "The matrix should be factorized first."); + Scalar det = Scalar(0.); + for (Index j = 0; j < this->cols(); ++j) + { + for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) + { + if(it.row() < j) continue; + if(it.row() == j) + { + det += log(abs(it.value())); + break; + } + } + } + return det; + } + + /** \returns A number representing the sign of the determinant + * + * \sa absDeterminant(), logAbsDeterminant() + */ + Scalar signDeterminant() + { + eigen_assert(m_factorizationIsOk && "The matrix should be factorized first."); + // Initialize with the determinant of the row matrix + Index det = 1; + // Note that the diagonal blocks of U are stored in supernodes, + // which are available in the L part :) + for (Index j = 0; j < this->cols(); ++j) + { + for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) + { + if(it.index() == j) + { + if(it.value()<0) + det = -det; + else if(it.value()==0) + return 0; + break; + } + } + } + return det * m_detPermR * m_detPermC; + } + + /** \returns The determinant of the matrix. + * + * \sa absDeterminant(), logAbsDeterminant() + */ + Scalar determinant() + { + eigen_assert(m_factorizationIsOk && "The matrix should be factorized first."); + // Initialize with the determinant of the row matrix + Scalar det = Scalar(1.); + // Note that the diagonal blocks of U are stored in supernodes, + // which are available in the L part :) + for (Index j = 0; j < this->cols(); ++j) + { + for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) + { + if(it.index() == j) + { + det *= it.value(); + break; + } + } + } + return (m_detPermR * m_detPermC) > 0 ? det : -det; + } + + Index nnzL() const { return m_nnzL; }; + Index nnzU() const { return m_nnzU; }; + + protected: + // Functions + void initperfvalues() + { + m_perfv.panel_size = 16; + m_perfv.relax = 1; + m_perfv.maxsuper = 128; + m_perfv.rowblk = 16; + m_perfv.colblk = 8; + m_perfv.fillfactor = 20; + } + + // Variables + mutable ComputationInfo m_info; + bool m_factorizationIsOk; + bool m_analysisIsOk; + std::string m_lastError; + NCMatrix m_mat; // The input (permuted ) matrix + SCMatrix m_Lstore; // The lower triangular matrix (supernodal) + MappedSparseMatrix m_Ustore; // The upper triangular matrix + PermutationType m_perm_c; // Column permutation + PermutationType m_perm_r ; // Row permutation + IndexVector m_etree; // Column elimination tree + + typename Base::GlobalLU_t m_glu; + + // SparseLU options + bool m_symmetricmode; + // values for performance + internal::perfvalues m_perfv; + RealScalar m_diagpivotthresh; // Specifies the threshold used for a diagonal entry to be an acceptable pivot + Index m_nnzL, m_nnzU; // Nonzeros in L and U factors + Index m_detPermR, m_detPermC; // Determinants of the permutation matrices + private: + // Disable copy constructor + SparseLU (const SparseLU& ); +}; // End class SparseLU + + + +// Functions needed by the anaysis phase +/** + * Compute the column permutation to minimize the fill-in + * + * - Apply this permutation to the input matrix - + * + * - Compute the column elimination tree on the permuted matrix + * + * - Postorder the elimination tree and the column permutation + * + */ +template +void SparseLU::analyzePattern(const MatrixType& mat) +{ + + //TODO It is possible as in SuperLU to compute row and columns scaling vectors to equilibrate the matrix mat. + + // Firstly, copy the whole input matrix. + m_mat = mat; + + // Compute fill-in ordering + OrderingType ord; + ord(m_mat,m_perm_c); + + // Apply the permutation to the column of the input matrix + if (m_perm_c.size()) + { + m_mat.uncompress(); //NOTE: The effect of this command is only to create the InnerNonzeros pointers. FIXME : This vector is filled but not subsequently used. + // Then, permute only the column pointers + ei_declare_aligned_stack_constructed_variable(StorageIndex,outerIndexPtr,mat.cols()+1,mat.isCompressed()?const_cast(mat.outerIndexPtr()):0); + + // If the input matrix 'mat' is uncompressed, then the outer-indices do not match the ones of m_mat, and a copy is thus needed. + if(!mat.isCompressed()) + IndexVector::Map(outerIndexPtr, mat.cols()+1) = IndexVector::Map(m_mat.outerIndexPtr(),mat.cols()+1); + + // Apply the permutation and compute the nnz per column. + for (Index i = 0; i < mat.cols(); i++) + { + m_mat.outerIndexPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i]; + m_mat.innerNonZeroPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i+1] - outerIndexPtr[i]; + } + } + + // Compute the column elimination tree of the permuted matrix + IndexVector firstRowElt; + internal::coletree(m_mat, m_etree,firstRowElt); + + // In symmetric mode, do not do postorder here + if (!m_symmetricmode) { + IndexVector post, iwork; + // Post order etree + internal::treePostorder(StorageIndex(m_mat.cols()), m_etree, post); + + + // Renumber etree in postorder + Index m = m_mat.cols(); + iwork.resize(m+1); + for (Index i = 0; i < m; ++i) iwork(post(i)) = post(m_etree(i)); + m_etree = iwork; + + // Postmultiply A*Pc by post, i.e reorder the matrix according to the postorder of the etree + PermutationType post_perm(m); + for (Index i = 0; i < m; i++) + post_perm.indices()(i) = post(i); + + // Combine the two permutations : postorder the permutation for future use + if(m_perm_c.size()) { + m_perm_c = post_perm * m_perm_c; + } + + } // end postordering + + m_analysisIsOk = true; +} + +// Functions needed by the numerical factorization phase + + +/** + * - Numerical factorization + * - Interleaved with the symbolic factorization + * On exit, info is + * + * = 0: successful factorization + * + * > 0: if info = i, and i is + * + * <= A->ncol: U(i,i) is exactly zero. The factorization has + * been completed, but the factor U is exactly singular, + * and division by zero will occur if it is used to solve a + * system of equations. + * + * > A->ncol: number of bytes allocated when memory allocation + * failure occurred, plus A->ncol. If lwork = -1, it is + * the estimated amount of space needed, plus A->ncol. + */ +template +void SparseLU::factorize(const MatrixType& matrix) +{ + using internal::emptyIdxLU; + eigen_assert(m_analysisIsOk && "analyzePattern() should be called first"); + eigen_assert((matrix.rows() == matrix.cols()) && "Only for squared matrices"); + + m_isInitialized = true; + + // Apply the column permutation computed in analyzepattern() + // m_mat = matrix * m_perm_c.inverse(); + m_mat = matrix; + if (m_perm_c.size()) + { + m_mat.uncompress(); //NOTE: The effect of this command is only to create the InnerNonzeros pointers. + //Then, permute only the column pointers + const StorageIndex * outerIndexPtr; + if (matrix.isCompressed()) outerIndexPtr = matrix.outerIndexPtr(); + else + { + StorageIndex* outerIndexPtr_t = new StorageIndex[matrix.cols()+1]; + for(Index i = 0; i <= matrix.cols(); i++) outerIndexPtr_t[i] = m_mat.outerIndexPtr()[i]; + outerIndexPtr = outerIndexPtr_t; + } + for (Index i = 0; i < matrix.cols(); i++) + { + m_mat.outerIndexPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i]; + m_mat.innerNonZeroPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i+1] - outerIndexPtr[i]; + } + if(!matrix.isCompressed()) delete[] outerIndexPtr; + } + else + { //FIXME This should not be needed if the empty permutation is handled transparently + m_perm_c.resize(matrix.cols()); + for(StorageIndex i = 0; i < matrix.cols(); ++i) m_perm_c.indices()(i) = i; + } + + Index m = m_mat.rows(); + Index n = m_mat.cols(); + Index nnz = m_mat.nonZeros(); + Index maxpanel = m_perfv.panel_size * m; + // Allocate working storage common to the factor routines + Index lwork = 0; + Index info = Base::memInit(m, n, nnz, lwork, m_perfv.fillfactor, m_perfv.panel_size, m_glu); + if (info) + { + m_lastError = "UNABLE TO ALLOCATE WORKING MEMORY\n\n" ; + m_factorizationIsOk = false; + return ; + } + + // Set up pointers for integer working arrays + IndexVector segrep(m); segrep.setZero(); + IndexVector parent(m); parent.setZero(); + IndexVector xplore(m); xplore.setZero(); + IndexVector repfnz(maxpanel); + IndexVector panel_lsub(maxpanel); + IndexVector xprune(n); xprune.setZero(); + IndexVector marker(m*internal::LUNoMarker); marker.setZero(); + + repfnz.setConstant(-1); + panel_lsub.setConstant(-1); + + // Set up pointers for scalar working arrays + ScalarVector dense; + dense.setZero(maxpanel); + ScalarVector tempv; + tempv.setZero(internal::LUnumTempV(m, m_perfv.panel_size, m_perfv.maxsuper, /*m_perfv.rowblk*/m) ); + + // Compute the inverse of perm_c + PermutationType iperm_c(m_perm_c.inverse()); + + // Identify initial relaxed snodes + IndexVector relax_end(n); + if ( m_symmetricmode == true ) + Base::heap_relax_snode(n, m_etree, m_perfv.relax, marker, relax_end); + else + Base::relax_snode(n, m_etree, m_perfv.relax, marker, relax_end); + + + m_perm_r.resize(m); + m_perm_r.indices().setConstant(-1); + marker.setConstant(-1); + m_detPermR = 1; // Record the determinant of the row permutation + + m_glu.supno(0) = emptyIdxLU; m_glu.xsup.setConstant(0); + m_glu.xsup(0) = m_glu.xlsub(0) = m_glu.xusub(0) = m_glu.xlusup(0) = Index(0); + + // Work on one 'panel' at a time. A panel is one of the following : + // (a) a relaxed supernode at the bottom of the etree, or + // (b) panel_size contiguous columns, defined by the user + Index jcol; + Index pivrow; // Pivotal row number in the original row matrix + Index nseg1; // Number of segments in U-column above panel row jcol + Index nseg; // Number of segments in each U-column + Index irep; + Index i, k, jj; + for (jcol = 0; jcol < n; ) + { + // Adjust panel size so that a panel won't overlap with the next relaxed snode. + Index panel_size = m_perfv.panel_size; // upper bound on panel width + for (k = jcol + 1; k < (std::min)(jcol+panel_size, n); k++) + { + if (relax_end(k) != emptyIdxLU) + { + panel_size = k - jcol; + break; + } + } + if (k == n) + panel_size = n - jcol; + + // Symbolic outer factorization on a panel of columns + Base::panel_dfs(m, panel_size, jcol, m_mat, m_perm_r.indices(), nseg1, dense, panel_lsub, segrep, repfnz, xprune, marker, parent, xplore, m_glu); + + // Numeric sup-panel updates in topological order + Base::panel_bmod(m, panel_size, jcol, nseg1, dense, tempv, segrep, repfnz, m_glu); + + // Sparse LU within the panel, and below the panel diagonal + for ( jj = jcol; jj< jcol + panel_size; jj++) + { + k = (jj - jcol) * m; // Column index for w-wide arrays + + nseg = nseg1; // begin after all the panel segments + //Depth-first-search for the current column + VectorBlock panel_lsubk(panel_lsub, k, m); + VectorBlock repfnz_k(repfnz, k, m); + info = Base::column_dfs(m, jj, m_perm_r.indices(), m_perfv.maxsuper, nseg, panel_lsubk, segrep, repfnz_k, xprune, marker, parent, xplore, m_glu); + if ( info ) + { + m_lastError = "UNABLE TO EXPAND MEMORY IN COLUMN_DFS() "; + m_info = NumericalIssue; + m_factorizationIsOk = false; + return; + } + // Numeric updates to this column + VectorBlock dense_k(dense, k, m); + VectorBlock segrep_k(segrep, nseg1, m-nseg1); + info = Base::column_bmod(jj, (nseg - nseg1), dense_k, tempv, segrep_k, repfnz_k, jcol, m_glu); + if ( info ) + { + m_lastError = "UNABLE TO EXPAND MEMORY IN COLUMN_BMOD() "; + m_info = NumericalIssue; + m_factorizationIsOk = false; + return; + } + + // Copy the U-segments to ucol(*) + info = Base::copy_to_ucol(jj, nseg, segrep, repfnz_k ,m_perm_r.indices(), dense_k, m_glu); + if ( info ) + { + m_lastError = "UNABLE TO EXPAND MEMORY IN COPY_TO_UCOL() "; + m_info = NumericalIssue; + m_factorizationIsOk = false; + return; + } + + // Form the L-segment + info = Base::pivotL(jj, m_diagpivotthresh, m_perm_r.indices(), iperm_c.indices(), pivrow, m_glu); + if ( info ) + { + m_lastError = "THE MATRIX IS STRUCTURALLY SINGULAR ... ZERO COLUMN AT "; + std::ostringstream returnInfo; + returnInfo << info; + m_lastError += returnInfo.str(); + m_info = NumericalIssue; + m_factorizationIsOk = false; + return; + } + + // Update the determinant of the row permutation matrix + // FIXME: the following test is not correct, we should probably take iperm_c into account and pivrow is not directly the row pivot. + if (pivrow != jj) m_detPermR = -m_detPermR; + + // Prune columns (0:jj-1) using column jj + Base::pruneL(jj, m_perm_r.indices(), pivrow, nseg, segrep, repfnz_k, xprune, m_glu); + + // Reset repfnz for this column + for (i = 0; i < nseg; i++) + { + irep = segrep(i); + repfnz_k(irep) = emptyIdxLU; + } + } // end SparseLU within the panel + jcol += panel_size; // Move to the next panel + } // end for -- end elimination + + m_detPermR = m_perm_r.determinant(); + m_detPermC = m_perm_c.determinant(); + + // Count the number of nonzeros in factors + Base::countnz(n, m_nnzL, m_nnzU, m_glu); + // Apply permutation to the L subscripts + Base::fixupL(n, m_perm_r.indices(), m_glu); + + // Create supernode matrix L + m_Lstore.setInfos(m, n, m_glu.lusup, m_glu.xlusup, m_glu.lsub, m_glu.xlsub, m_glu.supno, m_glu.xsup); + // Create the column major upper sparse matrix U; + new (&m_Ustore) MappedSparseMatrix ( m, n, m_nnzU, m_glu.xusub.data(), m_glu.usub.data(), m_glu.ucol.data() ); + + m_info = Success; + m_factorizationIsOk = true; +} + +template +struct SparseLUMatrixLReturnType : internal::no_assignment_operator +{ + typedef typename MappedSupernodalType::Scalar Scalar; + explicit SparseLUMatrixLReturnType(const MappedSupernodalType& mapL) : m_mapL(mapL) + { } + Index rows() const { return m_mapL.rows(); } + Index cols() const { return m_mapL.cols(); } + template + void solveInPlace( MatrixBase &X) const + { + m_mapL.solveInPlace(X); + } + template + void solveTransposedInPlace( MatrixBase &X) const + { + m_mapL.template solveTransposedInPlace(X); + } + + const MappedSupernodalType& m_mapL; +}; + +template +struct SparseLUMatrixUReturnType : internal::no_assignment_operator +{ + typedef typename MatrixLType::Scalar Scalar; + SparseLUMatrixUReturnType(const MatrixLType& mapL, const MatrixUType& mapU) + : m_mapL(mapL),m_mapU(mapU) + { } + Index rows() const { return m_mapL.rows(); } + Index cols() const { return m_mapL.cols(); } + + template void solveInPlace(MatrixBase &X) const + { + Index nrhs = X.cols(); + Index n = X.rows(); + // Backward solve with U + for (Index k = m_mapL.nsuper(); k >= 0; k--) + { + Index fsupc = m_mapL.supToCol()[k]; + Index lda = m_mapL.colIndexPtr()[fsupc+1] - m_mapL.colIndexPtr()[fsupc]; // leading dimension + Index nsupc = m_mapL.supToCol()[k+1] - fsupc; + Index luptr = m_mapL.colIndexPtr()[fsupc]; + + if (nsupc == 1) + { + for (Index j = 0; j < nrhs; j++) + { + X(fsupc, j) /= m_mapL.valuePtr()[luptr]; + } + } + else + { + // FIXME: the following lines should use Block expressions and not Map! + Map, 0, OuterStride<> > A( &(m_mapL.valuePtr()[luptr]), nsupc, nsupc, OuterStride<>(lda) ); + Map< Matrix, 0, OuterStride<> > U (&(X.coeffRef(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); + U = A.template triangularView().solve(U); + } + + for (Index j = 0; j < nrhs; ++j) + { + for (Index jcol = fsupc; jcol < fsupc + nsupc; jcol++) + { + typename MatrixUType::InnerIterator it(m_mapU, jcol); + for ( ; it; ++it) + { + Index irow = it.index(); + X(irow, j) -= X(jcol, j) * it.value(); + } + } + } + } // End For U-solve + } + + template void solveTransposedInPlace(MatrixBase &X) const + { + using numext::conj; + Index nrhs = X.cols(); + Index n = X.rows(); + // Forward solve with U + for (Index k = 0; k <= m_mapL.nsuper(); k++) + { + Index fsupc = m_mapL.supToCol()[k]; + Index lda = m_mapL.colIndexPtr()[fsupc+1] - m_mapL.colIndexPtr()[fsupc]; // leading dimension + Index nsupc = m_mapL.supToCol()[k+1] - fsupc; + Index luptr = m_mapL.colIndexPtr()[fsupc]; + + for (Index j = 0; j < nrhs; ++j) + { + for (Index jcol = fsupc; jcol < fsupc + nsupc; jcol++) + { + typename MatrixUType::InnerIterator it(m_mapU, jcol); + for ( ; it; ++it) + { + Index irow = it.index(); + X(jcol, j) -= X(irow, j) * (Conjugate? conj(it.value()): it.value()); + } + } + } + if (nsupc == 1) + { + for (Index j = 0; j < nrhs; j++) + { + X(fsupc, j) /= (Conjugate? conj(m_mapL.valuePtr()[luptr]) : m_mapL.valuePtr()[luptr]); + } + } + else + { + Map, 0, OuterStride<> > A( &(m_mapL.valuePtr()[luptr]), nsupc, nsupc, OuterStride<>(lda) ); + Map< Matrix, 0, OuterStride<> > U (&(X(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); + if(Conjugate) + U = A.adjoint().template triangularView().solve(U); + else + U = A.transpose().template triangularView().solve(U); + } + }// End For U-solve + } + + + const MatrixLType& m_mapL; + const MatrixUType& m_mapU; +}; + +} // End namespace Eigen + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLUImpl.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLUImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..fc0cfc4de1a5cf469ed53cbc8b4720fce7e43424 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLUImpl.h @@ -0,0 +1,66 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +#ifndef SPARSELU_IMPL_H +#define SPARSELU_IMPL_H + +namespace Eigen { +namespace internal { + +/** \ingroup SparseLU_Module + * \class SparseLUImpl + * Base class for sparseLU + */ +template +class SparseLUImpl +{ + public: + typedef Matrix ScalarVector; + typedef Matrix IndexVector; + typedef Matrix ScalarMatrix; + typedef Map > MappedMatrixBlock; + typedef typename ScalarVector::RealScalar RealScalar; + typedef Ref > BlockScalarVector; + typedef Ref > BlockIndexVector; + typedef LU_GlobalLU_t GlobalLU_t; + typedef SparseMatrix MatrixType; + + protected: + template + Index expand(VectorType& vec, Index& length, Index nbElts, Index keep_prev, Index& num_expansions); + Index memInit(Index m, Index n, Index annz, Index lwork, Index fillratio, Index panel_size, GlobalLU_t& glu); + template + Index memXpand(VectorType& vec, Index& maxlen, Index nbElts, MemType memtype, Index& num_expansions); + void heap_relax_snode (const Index n, IndexVector& et, const Index relax_columns, IndexVector& descendants, IndexVector& relax_end); + void relax_snode (const Index n, IndexVector& et, const Index relax_columns, IndexVector& descendants, IndexVector& relax_end); + Index snode_dfs(const Index jcol, const Index kcol,const MatrixType& mat, IndexVector& xprune, IndexVector& marker, GlobalLU_t& glu); + Index snode_bmod (const Index jcol, const Index fsupc, ScalarVector& dense, GlobalLU_t& glu); + Index pivotL(const Index jcol, const RealScalar& diagpivotthresh, IndexVector& perm_r, IndexVector& iperm_c, Index& pivrow, GlobalLU_t& glu); + template + void dfs_kernel(const StorageIndex jj, IndexVector& perm_r, + Index& nseg, IndexVector& panel_lsub, IndexVector& segrep, + Ref repfnz_col, IndexVector& xprune, Ref marker, IndexVector& parent, + IndexVector& xplore, GlobalLU_t& glu, Index& nextl_col, Index krow, Traits& traits); + void panel_dfs(const Index m, const Index w, const Index jcol, MatrixType& A, IndexVector& perm_r, Index& nseg, ScalarVector& dense, IndexVector& panel_lsub, IndexVector& segrep, IndexVector& repfnz, IndexVector& xprune, IndexVector& marker, IndexVector& parent, IndexVector& xplore, GlobalLU_t& glu); + + void panel_bmod(const Index m, const Index w, const Index jcol, const Index nseg, ScalarVector& dense, ScalarVector& tempv, IndexVector& segrep, IndexVector& repfnz, GlobalLU_t& glu); + Index column_dfs(const Index m, const Index jcol, IndexVector& perm_r, Index maxsuper, Index& nseg, BlockIndexVector lsub_col, IndexVector& segrep, BlockIndexVector repfnz, IndexVector& xprune, IndexVector& marker, IndexVector& parent, IndexVector& xplore, GlobalLU_t& glu); + Index column_bmod(const Index jcol, const Index nseg, BlockScalarVector dense, ScalarVector& tempv, BlockIndexVector segrep, BlockIndexVector repfnz, Index fpanelc, GlobalLU_t& glu); + Index copy_to_ucol(const Index jcol, const Index nseg, IndexVector& segrep, BlockIndexVector repfnz ,IndexVector& perm_r, BlockScalarVector dense, GlobalLU_t& glu); + void pruneL(const Index jcol, const IndexVector& perm_r, const Index pivrow, const Index nseg, const IndexVector& segrep, BlockIndexVector repfnz, IndexVector& xprune, GlobalLU_t& glu); + void countnz(const Index n, Index& nnzL, Index& nnzU, GlobalLU_t& glu); + void fixupL(const Index n, const IndexVector& perm_r, GlobalLU_t& glu); + + template + friend struct column_dfs_traits; +}; + +} // end namespace internal +} // namespace Eigen + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Memory.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Memory.h new file mode 100644 index 0000000000000000000000000000000000000000..349bfd585bdcdbc7f192e78d966dbeae748a744e --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Memory.h @@ -0,0 +1,226 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of [s,d,c,z]memory.c files in SuperLU + + * -- SuperLU routine (version 3.1) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * August 1, 2008 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ + +#ifndef EIGEN_SPARSELU_MEMORY +#define EIGEN_SPARSELU_MEMORY + +namespace Eigen { +namespace internal { + +enum { LUNoMarker = 3 }; +enum {emptyIdxLU = -1}; +inline Index LUnumTempV(Index& m, Index& w, Index& t, Index& b) +{ + return (std::max)(m, (t+b)*w); +} + +template< typename Scalar> +inline Index LUTempSpace(Index&m, Index& w) +{ + return (2*w + 4 + LUNoMarker) * m * sizeof(Index) + (w + 1) * m * sizeof(Scalar); +} + + + + +/** + * Expand the existing storage to accommodate more fill-ins + * \param vec Valid pointer to the vector to allocate or expand + * \param[in,out] length At input, contain the current length of the vector that is to be increased. At output, length of the newly allocated vector + * \param[in] nbElts Current number of elements in the factors + * \param keep_prev 1: use length and do not expand the vector; 0: compute new_len and expand + * \param[in,out] num_expansions Number of times the memory has been expanded + */ +template +template +Index SparseLUImpl::expand(VectorType& vec, Index& length, Index nbElts, Index keep_prev, Index& num_expansions) +{ + + float alpha = 1.5; // Ratio of the memory increase + Index new_len; // New size of the allocated memory + + if(num_expansions == 0 || keep_prev) + new_len = length ; // First time allocate requested + else + new_len = (std::max)(length+1,Index(alpha * length)); + + VectorType old_vec; // Temporary vector to hold the previous values + if (nbElts > 0 ) + old_vec = vec.segment(0,nbElts); + + //Allocate or expand the current vector +#ifdef EIGEN_EXCEPTIONS + try +#endif + { + vec.resize(new_len); + } +#ifdef EIGEN_EXCEPTIONS + catch(std::bad_alloc& ) +#else + if(!vec.size()) +#endif + { + if (!num_expansions) + { + // First time to allocate from LUMemInit() + // Let LUMemInit() deals with it. + return -1; + } + if (keep_prev) + { + // In this case, the memory length should not not be reduced + return new_len; + } + else + { + // Reduce the size and increase again + Index tries = 0; // Number of attempts + do + { + alpha = (alpha + 1)/2; + new_len = (std::max)(length+1,Index(alpha * length)); +#ifdef EIGEN_EXCEPTIONS + try +#endif + { + vec.resize(new_len); + } +#ifdef EIGEN_EXCEPTIONS + catch(std::bad_alloc& ) +#else + if (!vec.size()) +#endif + { + tries += 1; + if ( tries > 10) return new_len; + } + } while (!vec.size()); + } + } + //Copy the previous values to the newly allocated space + if (nbElts > 0) + vec.segment(0, nbElts) = old_vec; + + + length = new_len; + if(num_expansions) ++num_expansions; + return 0; +} + +/** + * \brief Allocate various working space for the numerical factorization phase. + * \param m number of rows of the input matrix + * \param n number of columns + * \param annz number of initial nonzeros in the matrix + * \param lwork if lwork=-1, this routine returns an estimated size of the required memory + * \param glu persistent data to facilitate multiple factors : will be deleted later ?? + * \param fillratio estimated ratio of fill in the factors + * \param panel_size Size of a panel + * \return an estimated size of the required memory if lwork = -1; otherwise, return the size of actually allocated memory when allocation failed, and 0 on success + * \note Unlike SuperLU, this routine does not support successive factorization with the same pattern and the same row permutation + */ +template +Index SparseLUImpl::memInit(Index m, Index n, Index annz, Index lwork, Index fillratio, Index panel_size, GlobalLU_t& glu) +{ + Index& num_expansions = glu.num_expansions; //No memory expansions so far + num_expansions = 0; + glu.nzumax = glu.nzlumax = (std::min)(fillratio * (annz+1) / n, m) * n; // estimated number of nonzeros in U + glu.nzlmax = (std::max)(Index(4), fillratio) * (annz+1) / 4; // estimated nnz in L factor + // Return the estimated size to the user if necessary + Index tempSpace; + tempSpace = (2*panel_size + 4 + LUNoMarker) * m * sizeof(Index) + (panel_size + 1) * m * sizeof(Scalar); + if (lwork == emptyIdxLU) + { + Index estimated_size; + estimated_size = (5 * n + 5) * sizeof(Index) + tempSpace + + (glu.nzlmax + glu.nzumax) * sizeof(Index) + (glu.nzlumax+glu.nzumax) * sizeof(Scalar) + n; + return estimated_size; + } + + // Setup the required space + + // First allocate Integer pointers for L\U factors + glu.xsup.resize(n+1); + glu.supno.resize(n+1); + glu.xlsub.resize(n+1); + glu.xlusup.resize(n+1); + glu.xusub.resize(n+1); + + // Reserve memory for L/U factors + do + { + if( (expand(glu.lusup, glu.nzlumax, 0, 0, num_expansions)<0) + || (expand(glu.ucol, glu.nzumax, 0, 0, num_expansions)<0) + || (expand (glu.lsub, glu.nzlmax, 0, 0, num_expansions)<0) + || (expand (glu.usub, glu.nzumax, 0, 1, num_expansions)<0) ) + { + //Reduce the estimated size and retry + glu.nzlumax /= 2; + glu.nzumax /= 2; + glu.nzlmax /= 2; + if (glu.nzlumax < annz ) return glu.nzlumax; + } + } while (!glu.lusup.size() || !glu.ucol.size() || !glu.lsub.size() || !glu.usub.size()); + + ++num_expansions; + return 0; + +} // end LuMemInit + +/** + * \brief Expand the existing storage + * \param vec vector to expand + * \param[in,out] maxlen On input, previous size of vec (Number of elements to copy ). on output, new size + * \param nbElts current number of elements in the vector. + * \param memtype Type of the element to expand + * \param num_expansions Number of expansions + * \return 0 on success, > 0 size of the memory allocated so far + */ +template +template +Index SparseLUImpl::memXpand(VectorType& vec, Index& maxlen, Index nbElts, MemType memtype, Index& num_expansions) +{ + Index failed_size; + if (memtype == USUB) + failed_size = this->expand(vec, maxlen, nbElts, 1, num_expansions); + else + failed_size = this->expand(vec, maxlen, nbElts, 0, num_expansions); + + if (failed_size) + return failed_size; + + return 0 ; +} + +} // end namespace internal + +} // end namespace Eigen +#endif // EIGEN_SPARSELU_MEMORY diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Structs.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Structs.h new file mode 100644 index 0000000000000000000000000000000000000000..cf5ec449bec3474860b49c3348a90c15cb15fed2 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Structs.h @@ -0,0 +1,110 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + * NOTE: This file comes from a partly modified version of files slu_[s,d,c,z]defs.h + * -- SuperLU routine (version 4.1) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November, 2010 + * + * Global data structures used in LU factorization - + * + * nsuper: #supernodes = nsuper + 1, numbered [0, nsuper]. + * (xsup,supno): supno[i] is the supernode no to which i belongs; + * xsup(s) points to the beginning of the s-th supernode. + * e.g. supno 0 1 2 2 3 3 3 4 4 4 4 4 (n=12) + * xsup 0 1 2 4 7 12 + * Note: dfs will be performed on supernode rep. relative to the new + * row pivoting ordering + * + * (xlsub,lsub): lsub[*] contains the compressed subscript of + * rectangular supernodes; xlsub[j] points to the starting + * location of the j-th column in lsub[*]. Note that xlsub + * is indexed by column. + * Storage: original row subscripts + * + * During the course of sparse LU factorization, we also use + * (xlsub,lsub) for the purpose of symmetric pruning. For each + * supernode {s,s+1,...,t=s+r} with first column s and last + * column t, the subscript set + * lsub[j], j=xlsub[s], .., xlsub[s+1]-1 + * is the structure of column s (i.e. structure of this supernode). + * It is used for the storage of numerical values. + * Furthermore, + * lsub[j], j=xlsub[t], .., xlsub[t+1]-1 + * is the structure of the last column t of this supernode. + * It is for the purpose of symmetric pruning. Therefore, the + * structural subscripts can be rearranged without making physical + * interchanges among the numerical values. + * + * However, if the supernode has only one column, then we + * only keep one set of subscripts. For any subscript interchange + * performed, similar interchange must be done on the numerical + * values. + * + * The last column structures (for pruning) will be removed + * after the numercial LU factorization phase. + * + * (xlusup,lusup): lusup[*] contains the numerical values of the + * rectangular supernodes; xlusup[j] points to the starting + * location of the j-th column in storage vector lusup[*] + * Note: xlusup is indexed by column. + * Each rectangular supernode is stored by column-major + * scheme, consistent with Fortran 2-dim array storage. + * + * (xusub,ucol,usub): ucol[*] stores the numerical values of + * U-columns outside the rectangular supernodes. The row + * subscript of nonzero ucol[k] is stored in usub[k]. + * xusub[i] points to the starting location of column i in ucol. + * Storage: new row subscripts; that is subscripts of PA. + */ + +#ifndef EIGEN_LU_STRUCTS +#define EIGEN_LU_STRUCTS +namespace Eigen { +namespace internal { + +typedef enum {LUSUP, UCOL, LSUB, USUB, LLVL, ULVL} MemType; + +template +struct LU_GlobalLU_t { + typedef typename IndexVector::Scalar StorageIndex; + IndexVector xsup; //First supernode column ... xsup(s) points to the beginning of the s-th supernode + IndexVector supno; // Supernode number corresponding to this column (column to supernode mapping) + ScalarVector lusup; // nonzero values of L ordered by columns + IndexVector lsub; // Compressed row indices of L rectangular supernodes. + IndexVector xlusup; // pointers to the beginning of each column in lusup + IndexVector xlsub; // pointers to the beginning of each column in lsub + Index nzlmax; // Current max size of lsub + Index nzlumax; // Current max size of lusup + ScalarVector ucol; // nonzero values of U ordered by columns + IndexVector usub; // row indices of U columns in ucol + IndexVector xusub; // Pointers to the beginning of each column of U in ucol + Index nzumax; // Current max size of ucol + Index n; // Number of columns in the matrix + Index num_expansions; +}; + +// Values to set for performance +struct perfvalues { + Index panel_size; // a panel consists of at most consecutive columns + Index relax; // To control degree of relaxing supernodes. If the number of nodes (columns) + // in a subtree of the elimination tree is less than relax, this subtree is considered + // as one supernode regardless of the row structures of those columns + Index maxsuper; // The maximum size for a supernode in complete LU + Index rowblk; // The minimum row dimension for 2-D blocking to be used; + Index colblk; // The minimum column dimension for 2-D blocking to be used; + Index fillfactor; // The estimated fills factors for L and U, compared with A +}; + +} // end namespace internal + +} // end namespace Eigen +#endif // EIGEN_LU_STRUCTS diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..0be293d17fa51110a211fb99b22ad3e8c67c4560 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h @@ -0,0 +1,375 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSELU_SUPERNODAL_MATRIX_H +#define EIGEN_SPARSELU_SUPERNODAL_MATRIX_H + +namespace Eigen { +namespace internal { + +/** \ingroup SparseLU_Module + * \brief a class to manipulate the L supernodal factor from the SparseLU factorization + * + * This class contain the data to easily store + * and manipulate the supernodes during the factorization and solution phase of Sparse LU. + * Only the lower triangular matrix has supernodes. + * + * NOTE : This class corresponds to the SCformat structure in SuperLU + * + */ +/* TODO + * InnerIterator as for sparsematrix + * SuperInnerIterator to iterate through all supernodes + * Function for triangular solve + */ +template +class MappedSuperNodalMatrix +{ + public: + typedef _Scalar Scalar; + typedef _StorageIndex StorageIndex; + typedef Matrix IndexVector; + typedef Matrix ScalarVector; + public: + MappedSuperNodalMatrix() + { + + } + MappedSuperNodalMatrix(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, + IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) + { + setInfos(m, n, nzval, nzval_colptr, rowind, rowind_colptr, col_to_sup, sup_to_col); + } + + ~MappedSuperNodalMatrix() + { + + } + /** + * Set appropriate pointers for the lower triangular supernodal matrix + * These infos are available at the end of the numerical factorization + * FIXME This class will be modified such that it can be use in the course + * of the factorization. + */ + void setInfos(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, + IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) + { + m_row = m; + m_col = n; + m_nzval = nzval.data(); + m_nzval_colptr = nzval_colptr.data(); + m_rowind = rowind.data(); + m_rowind_colptr = rowind_colptr.data(); + m_nsuper = col_to_sup(n); + m_col_to_sup = col_to_sup.data(); + m_sup_to_col = sup_to_col.data(); + } + + /** + * Number of rows + */ + Index rows() const { return m_row; } + + /** + * Number of columns + */ + Index cols() const { return m_col; } + + /** + * Return the array of nonzero values packed by column + * + * The size is nnz + */ + Scalar* valuePtr() { return m_nzval; } + + const Scalar* valuePtr() const + { + return m_nzval; + } + /** + * Return the pointers to the beginning of each column in \ref valuePtr() + */ + StorageIndex* colIndexPtr() + { + return m_nzval_colptr; + } + + const StorageIndex* colIndexPtr() const + { + return m_nzval_colptr; + } + + /** + * Return the array of compressed row indices of all supernodes + */ + StorageIndex* rowIndex() { return m_rowind; } + + const StorageIndex* rowIndex() const + { + return m_rowind; + } + + /** + * Return the location in \em rowvaluePtr() which starts each column + */ + StorageIndex* rowIndexPtr() { return m_rowind_colptr; } + + const StorageIndex* rowIndexPtr() const + { + return m_rowind_colptr; + } + + /** + * Return the array of column-to-supernode mapping + */ + StorageIndex* colToSup() { return m_col_to_sup; } + + const StorageIndex* colToSup() const + { + return m_col_to_sup; + } + /** + * Return the array of supernode-to-column mapping + */ + StorageIndex* supToCol() { return m_sup_to_col; } + + const StorageIndex* supToCol() const + { + return m_sup_to_col; + } + + /** + * Return the number of supernodes + */ + Index nsuper() const + { + return m_nsuper; + } + + class InnerIterator; + template + void solveInPlace( MatrixBase&X) const; + template + void solveTransposedInPlace( MatrixBase&X) const; + + + + + + protected: + Index m_row; // Number of rows + Index m_col; // Number of columns + Index m_nsuper; // Number of supernodes + Scalar* m_nzval; //array of nonzero values packed by column + StorageIndex* m_nzval_colptr; //nzval_colptr[j] Stores the location in nzval[] which starts column j + StorageIndex* m_rowind; // Array of compressed row indices of rectangular supernodes + StorageIndex* m_rowind_colptr; //rowind_colptr[j] stores the location in rowind[] which starts column j + StorageIndex* m_col_to_sup; // col_to_sup[j] is the supernode number to which column j belongs + StorageIndex* m_sup_to_col; //sup_to_col[s] points to the starting column of the s-th supernode + + private : +}; + +/** + * \brief InnerIterator class to iterate over nonzero values of the current column in the supernodal matrix L + * + */ +template +class MappedSuperNodalMatrix::InnerIterator +{ + public: + InnerIterator(const MappedSuperNodalMatrix& mat, Index outer) + : m_matrix(mat), + m_outer(outer), + m_supno(mat.colToSup()[outer]), + m_idval(mat.colIndexPtr()[outer]), + m_startidval(m_idval), + m_endidval(mat.colIndexPtr()[outer+1]), + m_idrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]]), + m_endidrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]+1]) + {} + inline InnerIterator& operator++() + { + m_idval++; + m_idrow++; + return *this; + } + inline Scalar value() const { return m_matrix.valuePtr()[m_idval]; } + + inline Scalar& valueRef() { return const_cast(m_matrix.valuePtr()[m_idval]); } + + inline Index index() const { return m_matrix.rowIndex()[m_idrow]; } + inline Index row() const { return index(); } + inline Index col() const { return m_outer; } + + inline Index supIndex() const { return m_supno; } + + inline operator bool() const + { + return ( (m_idval < m_endidval) && (m_idval >= m_startidval) + && (m_idrow < m_endidrow) ); + } + + protected: + const MappedSuperNodalMatrix& m_matrix; // Supernodal lower triangular matrix + const Index m_outer; // Current column + const Index m_supno; // Current SuperNode number + Index m_idval; // Index to browse the values in the current column + const Index m_startidval; // Start of the column value + const Index m_endidval; // End of the column value + Index m_idrow; // Index to browse the row indices + Index m_endidrow; // End index of row indices of the current column +}; + +/** + * \brief Solve with the supernode triangular matrix + * + */ +template +template +void MappedSuperNodalMatrix::solveInPlace( MatrixBase&X) const +{ + /* Explicit type conversion as the Index type of MatrixBase may be wider than Index */ +// eigen_assert(X.rows() <= NumTraits::highest()); +// eigen_assert(X.cols() <= NumTraits::highest()); + Index n = int(X.rows()); + Index nrhs = Index(X.cols()); + const Scalar * Lval = valuePtr(); // Nonzero values + Matrix work(n, nrhs); // working vector + work.setZero(); + for (Index k = 0; k <= nsuper(); k ++) + { + Index fsupc = supToCol()[k]; // First column of the current supernode + Index istart = rowIndexPtr()[fsupc]; // Pointer index to the subscript of the current column + Index nsupr = rowIndexPtr()[fsupc+1] - istart; // Number of rows in the current supernode + Index nsupc = supToCol()[k+1] - fsupc; // Number of columns in the current supernode + Index nrow = nsupr - nsupc; // Number of rows in the non-diagonal part of the supernode + Index irow; //Current index row + + if (nsupc == 1 ) + { + for (Index j = 0; j < nrhs; j++) + { + InnerIterator it(*this, fsupc); + ++it; // Skip the diagonal element + for (; it; ++it) + { + irow = it.row(); + X(irow, j) -= X(fsupc, j) * it.value(); + } + } + } + else + { + // The supernode has more than one column + Index luptr = colIndexPtr()[fsupc]; + Index lda = colIndexPtr()[fsupc+1] - luptr; + + // Triangular solve + Map, 0, OuterStride<> > A( &(Lval[luptr]), nsupc, nsupc, OuterStride<>(lda) ); + Map< Matrix, 0, OuterStride<> > U (&(X(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); + U = A.template triangularView().solve(U); + + // Matrix-vector product + new (&A) Map, 0, OuterStride<> > ( &(Lval[luptr+nsupc]), nrow, nsupc, OuterStride<>(lda) ); + work.topRows(nrow).noalias() = A * U; + + //Begin Scatter + for (Index j = 0; j < nrhs; j++) + { + Index iptr = istart + nsupc; + for (Index i = 0; i < nrow; i++) + { + irow = rowIndex()[iptr]; + X(irow, j) -= work(i, j); // Scatter operation + work(i, j) = Scalar(0); + iptr++; + } + } + } + } +} + +template +template +void MappedSuperNodalMatrix::solveTransposedInPlace( MatrixBase&X) const +{ + using numext::conj; + Index n = int(X.rows()); + Index nrhs = Index(X.cols()); + const Scalar * Lval = valuePtr(); // Nonzero values + Matrix work(n, nrhs); // working vector + work.setZero(); + for (Index k = nsuper(); k >= 0; k--) + { + Index fsupc = supToCol()[k]; // First column of the current supernode + Index istart = rowIndexPtr()[fsupc]; // Pointer index to the subscript of the current column + Index nsupr = rowIndexPtr()[fsupc+1] - istart; // Number of rows in the current supernode + Index nsupc = supToCol()[k+1] - fsupc; // Number of columns in the current supernode + Index nrow = nsupr - nsupc; // Number of rows in the non-diagonal part of the supernode + Index irow; //Current index row + + if (nsupc == 1 ) + { + for (Index j = 0; j < nrhs; j++) + { + InnerIterator it(*this, fsupc); + ++it; // Skip the diagonal element + for (; it; ++it) + { + irow = it.row(); + X(fsupc,j) -= X(irow, j) * (Conjugate?conj(it.value()):it.value()); + } + } + } + else + { + // The supernode has more than one column + Index luptr = colIndexPtr()[fsupc]; + Index lda = colIndexPtr()[fsupc+1] - luptr; + + //Begin Gather + for (Index j = 0; j < nrhs; j++) + { + Index iptr = istart + nsupc; + for (Index i = 0; i < nrow; i++) + { + irow = rowIndex()[iptr]; + work.topRows(nrow)(i,j)= X(irow,j); // Gather operation + iptr++; + } + } + + // Matrix-vector product with transposed submatrix + Map, 0, OuterStride<> > A( &(Lval[luptr+nsupc]), nrow, nsupc, OuterStride<>(lda) ); + Map< Matrix, 0, OuterStride<> > U (&(X(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); + if(Conjugate) + U = U - A.adjoint() * work.topRows(nrow); + else + U = U - A.transpose() * work.topRows(nrow); + + // Triangular solve (of transposed diagonal block) + new (&A) Map, 0, OuterStride<> > ( &(Lval[luptr]), nsupc, nsupc, OuterStride<>(lda) ); + if(Conjugate) + U = A.adjoint().template triangularView().solve(U); + else + U = A.transpose().template triangularView().solve(U); + + } + + } +} + + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPARSELU_MATRIX_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Utils.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..9e3dab44d99986b0c2365d208d2eda47a125c5c2 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_Utils.h @@ -0,0 +1,80 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_SPARSELU_UTILS_H +#define EIGEN_SPARSELU_UTILS_H + +namespace Eigen { +namespace internal { + +/** + * \brief Count Nonzero elements in the factors + */ +template +void SparseLUImpl::countnz(const Index n, Index& nnzL, Index& nnzU, GlobalLU_t& glu) +{ + nnzL = 0; + nnzU = (glu.xusub)(n); + Index nsuper = (glu.supno)(n); + Index jlen; + Index i, j, fsupc; + if (n <= 0 ) return; + // For each supernode + for (i = 0; i <= nsuper; i++) + { + fsupc = glu.xsup(i); + jlen = glu.xlsub(fsupc+1) - glu.xlsub(fsupc); + + for (j = fsupc; j < glu.xsup(i+1); j++) + { + nnzL += jlen; + nnzU += j - fsupc + 1; + jlen--; + } + } +} + +/** + * \brief Fix up the data storage lsub for L-subscripts. + * + * It removes the subscripts sets for structural pruning, + * and applies permutation to the remaining subscripts + * + */ +template +void SparseLUImpl::fixupL(const Index n, const IndexVector& perm_r, GlobalLU_t& glu) +{ + Index fsupc, i, j, k, jstart; + + StorageIndex nextl = 0; + Index nsuper = (glu.supno)(n); + + // For each supernode + for (i = 0; i <= nsuper; i++) + { + fsupc = glu.xsup(i); + jstart = glu.xlsub(fsupc); + glu.xlsub(fsupc) = nextl; + for (j = jstart; j < glu.xlsub(fsupc + 1); j++) + { + glu.lsub(nextl) = perm_r(glu.lsub(j)); // Now indexed into P*A + nextl++; + } + for (k = fsupc+1; k < glu.xsup(i+1); k++) + glu.xlsub(k) = nextl; // other columns in supernode i + } + + glu.xlsub(n) = nextl; +} + +} // end namespace internal + +} // end namespace Eigen +#endif // EIGEN_SPARSELU_UTILS_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_bmod.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_bmod.h new file mode 100644 index 0000000000000000000000000000000000000000..b57f06802e2b78fe8e8a993576a1ab904315f7bf --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_bmod.h @@ -0,0 +1,181 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of xcolumn_bmod.c file in SuperLU + + * -- SuperLU routine (version 3.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * October 15, 2003 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_COLUMN_BMOD_H +#define SPARSELU_COLUMN_BMOD_H + +namespace Eigen { + +namespace internal { +/** + * \brief Performs numeric block updates (sup-col) in topological order + * + * \param jcol current column to update + * \param nseg Number of segments in the U part + * \param dense Store the full representation of the column + * \param tempv working array + * \param segrep segment representative ... + * \param repfnz ??? First nonzero column in each row ??? ... + * \param fpanelc First column in the current panel + * \param glu Global LU data. + * \return 0 - successful return + * > 0 - number of bytes allocated when run out of space + * + */ +template +Index SparseLUImpl::column_bmod(const Index jcol, const Index nseg, BlockScalarVector dense, ScalarVector& tempv, + BlockIndexVector segrep, BlockIndexVector repfnz, Index fpanelc, GlobalLU_t& glu) +{ + Index jsupno, k, ksub, krep, ksupno; + Index lptr, nrow, isub, irow, nextlu, new_next, ufirst; + Index fsupc, nsupc, nsupr, luptr, kfnz, no_zeros; + /* krep = representative of current k-th supernode + * fsupc = first supernodal column + * nsupc = number of columns in a supernode + * nsupr = number of rows in a supernode + * luptr = location of supernodal LU-block in storage + * kfnz = first nonz in the k-th supernodal segment + * no_zeros = no lf leading zeros in a supernodal U-segment + */ + + jsupno = glu.supno(jcol); + // For each nonzero supernode segment of U[*,j] in topological order + k = nseg - 1; + Index d_fsupc; // distance between the first column of the current panel and the + // first column of the current snode + Index fst_col; // First column within small LU update + Index segsize; + for (ksub = 0; ksub < nseg; ksub++) + { + krep = segrep(k); k--; + ksupno = glu.supno(krep); + if (jsupno != ksupno ) + { + // outside the rectangular supernode + fsupc = glu.xsup(ksupno); + fst_col = (std::max)(fsupc, fpanelc); + + // Distance from the current supernode to the current panel; + // d_fsupc = 0 if fsupc > fpanelc + d_fsupc = fst_col - fsupc; + + luptr = glu.xlusup(fst_col) + d_fsupc; + lptr = glu.xlsub(fsupc) + d_fsupc; + + kfnz = repfnz(krep); + kfnz = (std::max)(kfnz, fpanelc); + + segsize = krep - kfnz + 1; + nsupc = krep - fst_col + 1; + nsupr = glu.xlsub(fsupc+1) - glu.xlsub(fsupc); + nrow = nsupr - d_fsupc - nsupc; + Index lda = glu.xlusup(fst_col+1) - glu.xlusup(fst_col); + + + // Perform a triangular solver and block update, + // then scatter the result of sup-col update to dense + no_zeros = kfnz - fst_col; + if(segsize==1) + LU_kernel_bmod<1>::run(segsize, dense, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + else + LU_kernel_bmod::run(segsize, dense, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + } // end if jsupno + } // end for each segment + + // Process the supernodal portion of L\U[*,j] + nextlu = glu.xlusup(jcol); + fsupc = glu.xsup(jsupno); + + // copy the SPA dense into L\U[*,j] + Index mem; + new_next = nextlu + glu.xlsub(fsupc + 1) - glu.xlsub(fsupc); + Index offset = internal::first_multiple(new_next, internal::packet_traits::size) - new_next; + if(offset) + new_next += offset; + while (new_next > glu.nzlumax ) + { + mem = memXpand(glu.lusup, glu.nzlumax, nextlu, LUSUP, glu.num_expansions); + if (mem) return mem; + } + + for (isub = glu.xlsub(fsupc); isub < glu.xlsub(fsupc+1); isub++) + { + irow = glu.lsub(isub); + glu.lusup(nextlu) = dense(irow); + dense(irow) = Scalar(0.0); + ++nextlu; + } + + if(offset) + { + glu.lusup.segment(nextlu,offset).setZero(); + nextlu += offset; + } + glu.xlusup(jcol + 1) = StorageIndex(nextlu); // close L\U(*,jcol); + + /* For more updates within the panel (also within the current supernode), + * should start from the first column of the panel, or the first column + * of the supernode, whichever is bigger. There are two cases: + * 1) fsupc < fpanelc, then fst_col <-- fpanelc + * 2) fsupc >= fpanelc, then fst_col <-- fsupc + */ + fst_col = (std::max)(fsupc, fpanelc); + + if (fst_col < jcol) + { + // Distance between the current supernode and the current panel + // d_fsupc = 0 if fsupc >= fpanelc + d_fsupc = fst_col - fsupc; + + lptr = glu.xlsub(fsupc) + d_fsupc; + luptr = glu.xlusup(fst_col) + d_fsupc; + nsupr = glu.xlsub(fsupc+1) - glu.xlsub(fsupc); // leading dimension + nsupc = jcol - fst_col; // excluding jcol + nrow = nsupr - d_fsupc - nsupc; + + // points to the beginning of jcol in snode L\U(jsupno) + ufirst = glu.xlusup(jcol) + d_fsupc; + Index lda = glu.xlusup(jcol+1) - glu.xlusup(jcol); + MappedMatrixBlock A( &(glu.lusup.data()[luptr]), nsupc, nsupc, OuterStride<>(lda) ); + VectorBlock u(glu.lusup, ufirst, nsupc); + u = A.template triangularView().solve(u); + + new (&A) MappedMatrixBlock ( &(glu.lusup.data()[luptr+nsupc]), nrow, nsupc, OuterStride<>(lda) ); + VectorBlock l(glu.lusup, ufirst+nsupc, nrow); + l.noalias() -= A * u; + + } // End if fst_col + return 0; +} + +} // end namespace internal +} // end namespace Eigen + +#endif // SPARSELU_COLUMN_BMOD_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_dfs.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_dfs.h new file mode 100644 index 0000000000000000000000000000000000000000..5a2c941b4ab8123739e6a09c3dc523c0a475e36d --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_column_dfs.h @@ -0,0 +1,179 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of [s,d,c,z]column_dfs.c file in SuperLU + + * -- SuperLU routine (version 2.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November 15, 1997 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_COLUMN_DFS_H +#define SPARSELU_COLUMN_DFS_H + +template class SparseLUImpl; +namespace Eigen { + +namespace internal { + +template +struct column_dfs_traits : no_assignment_operator +{ + typedef typename ScalarVector::Scalar Scalar; + typedef typename IndexVector::Scalar StorageIndex; + column_dfs_traits(Index jcol, Index& jsuper, typename SparseLUImpl::GlobalLU_t& glu, SparseLUImpl& luImpl) + : m_jcol(jcol), m_jsuper_ref(jsuper), m_glu(glu), m_luImpl(luImpl) + {} + bool update_segrep(Index /*krep*/, Index /*jj*/) + { + return true; + } + void mem_expand(IndexVector& lsub, Index& nextl, Index chmark) + { + if (nextl >= m_glu.nzlmax) + m_luImpl.memXpand(lsub, m_glu.nzlmax, nextl, LSUB, m_glu.num_expansions); + if (chmark != (m_jcol-1)) m_jsuper_ref = emptyIdxLU; + } + enum { ExpandMem = true }; + + Index m_jcol; + Index& m_jsuper_ref; + typename SparseLUImpl::GlobalLU_t& m_glu; + SparseLUImpl& m_luImpl; +}; + + +/** + * \brief Performs a symbolic factorization on column jcol and decide the supernode boundary + * + * A supernode representative is the last column of a supernode. + * The nonzeros in U[*,j] are segments that end at supernodes representatives. + * The routine returns a list of the supernodal representatives + * in topological order of the dfs that generates them. + * The location of the first nonzero in each supernodal segment + * (supernodal entry location) is also returned. + * + * \param m number of rows in the matrix + * \param jcol Current column + * \param perm_r Row permutation + * \param maxsuper Maximum number of column allowed in a supernode + * \param [in,out] nseg Number of segments in current U[*,j] - new segments appended + * \param lsub_col defines the rhs vector to start the dfs + * \param [in,out] segrep Segment representatives - new segments appended + * \param repfnz First nonzero location in each row + * \param xprune + * \param marker marker[i] == jj, if i was visited during dfs of current column jj; + * \param parent + * \param xplore working array + * \param glu global LU data + * \return 0 success + * > 0 number of bytes allocated when run out of space + * + */ +template +Index SparseLUImpl::column_dfs(const Index m, const Index jcol, IndexVector& perm_r, Index maxsuper, Index& nseg, + BlockIndexVector lsub_col, IndexVector& segrep, BlockIndexVector repfnz, IndexVector& xprune, + IndexVector& marker, IndexVector& parent, IndexVector& xplore, GlobalLU_t& glu) +{ + + Index jsuper = glu.supno(jcol); + Index nextl = glu.xlsub(jcol); + VectorBlock marker2(marker, 2*m, m); + + + column_dfs_traits traits(jcol, jsuper, glu, *this); + + // For each nonzero in A(*,jcol) do dfs + for (Index k = 0; ((k < m) ? lsub_col[k] != emptyIdxLU : false) ; k++) + { + Index krow = lsub_col(k); + lsub_col(k) = emptyIdxLU; + Index kmark = marker2(krow); + + // krow was visited before, go to the next nonz; + if (kmark == jcol) continue; + + dfs_kernel(StorageIndex(jcol), perm_r, nseg, glu.lsub, segrep, repfnz, xprune, marker2, parent, + xplore, glu, nextl, krow, traits); + } // for each nonzero ... + + Index fsupc; + StorageIndex nsuper = glu.supno(jcol); + StorageIndex jcolp1 = StorageIndex(jcol) + 1; + Index jcolm1 = jcol - 1; + + // check to see if j belongs in the same supernode as j-1 + if ( jcol == 0 ) + { // Do nothing for column 0 + nsuper = glu.supno(0) = 0 ; + } + else + { + fsupc = glu.xsup(nsuper); + StorageIndex jptr = glu.xlsub(jcol); // Not yet compressed + StorageIndex jm1ptr = glu.xlsub(jcolm1); + + // Use supernodes of type T2 : see SuperLU paper + if ( (nextl-jptr != jptr-jm1ptr-1) ) jsuper = emptyIdxLU; + + // Make sure the number of columns in a supernode doesn't + // exceed threshold + if ( (jcol - fsupc) >= maxsuper) jsuper = emptyIdxLU; + + /* If jcol starts a new supernode, reclaim storage space in + * glu.lsub from previous supernode. Note we only store + * the subscript set of the first and last columns of + * a supernode. (first for num values, last for pruning) + */ + if (jsuper == emptyIdxLU) + { // starts a new supernode + if ( (fsupc < jcolm1-1) ) + { // >= 3 columns in nsuper + StorageIndex ito = glu.xlsub(fsupc+1); + glu.xlsub(jcolm1) = ito; + StorageIndex istop = ito + jptr - jm1ptr; + xprune(jcolm1) = istop; // initialize xprune(jcol-1) + glu.xlsub(jcol) = istop; + + for (StorageIndex ifrom = jm1ptr; ifrom < nextl; ++ifrom, ++ito) + glu.lsub(ito) = glu.lsub(ifrom); + nextl = ito; // = istop + length(jcol) + } + nsuper++; + glu.supno(jcol) = nsuper; + } // if a new supernode + } // end else: jcol > 0 + + // Tidy up the pointers before exit + glu.xsup(nsuper+1) = jcolp1; + glu.supno(jcolp1) = nsuper; + xprune(jcol) = StorageIndex(nextl); // Initialize upper bound for pruning + glu.xlsub(jcolp1) = StorageIndex(nextl); + + return 0; +} + +} // end namespace internal + +} // end namespace Eigen + +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_copy_to_ucol.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_copy_to_ucol.h new file mode 100644 index 0000000000000000000000000000000000000000..c32d8d8b14b645cd1824432cf5284a8e448557a9 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_copy_to_ucol.h @@ -0,0 +1,107 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +/* + + * NOTE: This file is the modified version of [s,d,c,z]copy_to_ucol.c file in SuperLU + + * -- SuperLU routine (version 2.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November 15, 1997 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_COPY_TO_UCOL_H +#define SPARSELU_COPY_TO_UCOL_H + +namespace Eigen { +namespace internal { + +/** + * \brief Performs numeric block updates (sup-col) in topological order + * + * \param jcol current column to update + * \param nseg Number of segments in the U part + * \param segrep segment representative ... + * \param repfnz First nonzero column in each row ... + * \param perm_r Row permutation + * \param dense Store the full representation of the column + * \param glu Global LU data. + * \return 0 - successful return + * > 0 - number of bytes allocated when run out of space + * + */ +template +Index SparseLUImpl::copy_to_ucol(const Index jcol, const Index nseg, IndexVector& segrep, + BlockIndexVector repfnz ,IndexVector& perm_r, BlockScalarVector dense, GlobalLU_t& glu) +{ + Index ksub, krep, ksupno; + + Index jsupno = glu.supno(jcol); + + // For each nonzero supernode segment of U[*,j] in topological order + Index k = nseg - 1, i; + StorageIndex nextu = glu.xusub(jcol); + Index kfnz, isub, segsize; + Index new_next,irow; + Index fsupc, mem; + for (ksub = 0; ksub < nseg; ksub++) + { + krep = segrep(k); k--; + ksupno = glu.supno(krep); + if (jsupno != ksupno ) // should go into ucol(); + { + kfnz = repfnz(krep); + if (kfnz != emptyIdxLU) + { // Nonzero U-segment + fsupc = glu.xsup(ksupno); + isub = glu.xlsub(fsupc) + kfnz - fsupc; + segsize = krep - kfnz + 1; + new_next = nextu + segsize; + while (new_next > glu.nzumax) + { + mem = memXpand(glu.ucol, glu.nzumax, nextu, UCOL, glu.num_expansions); + if (mem) return mem; + mem = memXpand(glu.usub, glu.nzumax, nextu, USUB, glu.num_expansions); + if (mem) return mem; + + } + + for (i = 0; i < segsize; i++) + { + irow = glu.lsub(isub); + glu.usub(nextu) = perm_r(irow); // Unlike the L part, the U part is stored in its final order + glu.ucol(nextu) = dense(irow); + dense(irow) = Scalar(0.0); + nextu++; + isub++; + } + + } // end nonzero U-segment + + } // end if jsupno + + } // end for each segment + glu.xusub(jcol + 1) = nextu; // close U(*,jcol) + return 0; +} + +} // namespace internal +} // end namespace Eigen + +#endif // SPARSELU_COPY_TO_UCOL_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_gemm_kernel.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_gemm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e37c2fe0d028482549db8186a6650745ce0f6db7 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_gemm_kernel.h @@ -0,0 +1,280 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSELU_GEMM_KERNEL_H +#define EIGEN_SPARSELU_GEMM_KERNEL_H + +namespace Eigen { + +namespace internal { + + +/** \internal + * A general matrix-matrix product kernel optimized for the SparseLU factorization. + * - A, B, and C must be column major + * - lda and ldc must be multiples of the respective packet size + * - C must have the same alignment as A + */ +template +EIGEN_DONT_INLINE +void sparselu_gemm(Index m, Index n, Index d, const Scalar* A, Index lda, const Scalar* B, Index ldb, Scalar* C, Index ldc) +{ + using namespace Eigen::internal; + + typedef typename packet_traits::type Packet; + enum { + NumberOfRegisters = EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS, + PacketSize = packet_traits::size, + PM = 8, // peeling in M + RN = 2, // register blocking + RK = NumberOfRegisters>=16 ? 4 : 2, // register blocking + BM = 4096/sizeof(Scalar), // number of rows of A-C per chunk + SM = PM*PacketSize // step along M + }; + Index d_end = (d/RK)*RK; // number of columns of A (rows of B) suitable for full register blocking + Index n_end = (n/RN)*RN; // number of columns of B-C suitable for processing RN columns at once + Index i0 = internal::first_default_aligned(A,m); + + eigen_internal_assert(((lda%PacketSize)==0) && ((ldc%PacketSize)==0) && (i0==internal::first_default_aligned(C,m))); + + // handle the non aligned rows of A and C without any optimization: + for(Index i=0; i(BM, m-ib); // actual number of rows + Index actual_b_end1 = (actual_b/SM)*SM; // actual number of rows suitable for peeling + Index actual_b_end2 = (actual_b/PacketSize)*PacketSize; // actual number of rows suitable for vectorization + + // Let's process two columns of B-C at once + for(Index j=0; j(Bc0[0]); } + { b10 = pset1(Bc0[1]); } + if(RK==4) { b20 = pset1(Bc0[2]); } + if(RK==4) { b30 = pset1(Bc0[3]); } + { b01 = pset1(Bc1[0]); } + { b11 = pset1(Bc1[1]); } + if(RK==4) { b21 = pset1(Bc1[2]); } + if(RK==4) { b31 = pset1(Bc1[3]); } + + Packet a0, a1, a2, a3, c0, c1, t0, t1; + + const Scalar* A0 = A+ib+(k+0)*lda; + const Scalar* A1 = A+ib+(k+1)*lda; + const Scalar* A2 = A+ib+(k+2)*lda; + const Scalar* A3 = A+ib+(k+3)*lda; + + Scalar* C0 = C+ib+(j+0)*ldc; + Scalar* C1 = C+ib+(j+1)*ldc; + + a0 = pload(A0); + a1 = pload(A1); + if(RK==4) + { + a2 = pload(A2); + a3 = pload(A3); + } + else + { + // workaround "may be used uninitialized in this function" warning + a2 = a3 = a0; + } + +#define KMADD(c, a, b, tmp) {tmp = b; tmp = pmul(a,tmp); c = padd(c,tmp);} +#define WORK(I) \ + c0 = pload(C0+i+(I)*PacketSize); \ + c1 = pload(C1+i+(I)*PacketSize); \ + KMADD(c0, a0, b00, t0) \ + KMADD(c1, a0, b01, t1) \ + a0 = pload(A0+i+(I+1)*PacketSize); \ + KMADD(c0, a1, b10, t0) \ + KMADD(c1, a1, b11, t1) \ + a1 = pload(A1+i+(I+1)*PacketSize); \ + if(RK==4){ KMADD(c0, a2, b20, t0) }\ + if(RK==4){ KMADD(c1, a2, b21, t1) }\ + if(RK==4){ a2 = pload(A2+i+(I+1)*PacketSize); }\ + if(RK==4){ KMADD(c0, a3, b30, t0) }\ + if(RK==4){ KMADD(c1, a3, b31, t1) }\ + if(RK==4){ a3 = pload(A3+i+(I+1)*PacketSize); }\ + pstore(C0+i+(I)*PacketSize, c0); \ + pstore(C1+i+(I)*PacketSize, c1) + + // process rows of A' - C' with aggressive vectorization and peeling + for(Index i=0; i0) + { + const Scalar* Bc0 = B+(n-1)*ldb; + + for(Index k=0; k(Bc0[0]); + b10 = pset1(Bc0[1]); + if(RK==4) b20 = pset1(Bc0[2]); + if(RK==4) b30 = pset1(Bc0[3]); + + Packet a0, a1, a2, a3, c0, t0/*, t1*/; + + const Scalar* A0 = A+ib+(k+0)*lda; + const Scalar* A1 = A+ib+(k+1)*lda; + const Scalar* A2 = A+ib+(k+2)*lda; + const Scalar* A3 = A+ib+(k+3)*lda; + + Scalar* C0 = C+ib+(n_end)*ldc; + + a0 = pload(A0); + a1 = pload(A1); + if(RK==4) + { + a2 = pload(A2); + a3 = pload(A3); + } + else + { + // workaround "may be used uninitialized in this function" warning + a2 = a3 = a0; + } + +#define WORK(I) \ + c0 = pload(C0+i+(I)*PacketSize); \ + KMADD(c0, a0, b00, t0) \ + a0 = pload(A0+i+(I+1)*PacketSize); \ + KMADD(c0, a1, b10, t0) \ + a1 = pload(A1+i+(I+1)*PacketSize); \ + if(RK==4){ KMADD(c0, a2, b20, t0) }\ + if(RK==4){ a2 = pload(A2+i+(I+1)*PacketSize); }\ + if(RK==4){ KMADD(c0, a3, b30, t0) }\ + if(RK==4){ a3 = pload(A3+i+(I+1)*PacketSize); }\ + pstore(C0+i+(I)*PacketSize, c0); + + // aggressive vectorization and peeling + for(Index i=0; i0) + { + for(Index j=0; j1 ? Aligned : 0 + }; + typedef Map, Alignment > MapVector; + typedef Map, Alignment > ConstMapVector; + if(rd==1) MapVector(C+j*ldc+ib,actual_b) += B[0+d_end+j*ldb] * ConstMapVector(A+(d_end+0)*lda+ib, actual_b); + + else if(rd==2) MapVector(C+j*ldc+ib,actual_b) += B[0+d_end+j*ldb] * ConstMapVector(A+(d_end+0)*lda+ib, actual_b) + + B[1+d_end+j*ldb] * ConstMapVector(A+(d_end+1)*lda+ib, actual_b); + + else MapVector(C+j*ldc+ib,actual_b) += B[0+d_end+j*ldb] * ConstMapVector(A+(d_end+0)*lda+ib, actual_b) + + B[1+d_end+j*ldb] * ConstMapVector(A+(d_end+1)*lda+ib, actual_b) + + B[2+d_end+j*ldb] * ConstMapVector(A+(d_end+2)*lda+ib, actual_b); + } + } + + } // blocking on the rows of A and C +} +#undef KMADD + +} // namespace internal + +} // namespace Eigen + +#endif // EIGEN_SPARSELU_GEMM_KERNEL_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h new file mode 100644 index 0000000000000000000000000000000000000000..6f75d500e5f831f414175ce46dbceffa0acd5539 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h @@ -0,0 +1,126 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* This file is a modified version of heap_relax_snode.c file in SuperLU + * -- SuperLU routine (version 3.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * October 15, 2003 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ + +#ifndef SPARSELU_HEAP_RELAX_SNODE_H +#define SPARSELU_HEAP_RELAX_SNODE_H + +namespace Eigen { +namespace internal { + +/** + * \brief Identify the initial relaxed supernodes + * + * This routine applied to a symmetric elimination tree. + * It assumes that the matrix has been reordered according to the postorder of the etree + * \param n The number of columns + * \param et elimination tree + * \param relax_columns Maximum number of columns allowed in a relaxed snode + * \param descendants Number of descendants of each node in the etree + * \param relax_end last column in a supernode + */ +template +void SparseLUImpl::heap_relax_snode (const Index n, IndexVector& et, const Index relax_columns, IndexVector& descendants, IndexVector& relax_end) +{ + + // The etree may not be postordered, but its heap ordered + IndexVector post; + internal::treePostorder(StorageIndex(n), et, post); // Post order etree + IndexVector inv_post(n+1); + for (StorageIndex i = 0; i < n+1; ++i) inv_post(post(i)) = i; // inv_post = post.inverse()??? + + // Renumber etree in postorder + IndexVector iwork(n); + IndexVector et_save(n+1); + for (Index i = 0; i < n; ++i) + { + iwork(post(i)) = post(et(i)); + } + et_save = et; // Save the original etree + et = iwork; + + // compute the number of descendants of each node in the etree + relax_end.setConstant(emptyIdxLU); + Index j, parent; + descendants.setZero(); + for (j = 0; j < n; j++) + { + parent = et(j); + if (parent != n) // not the dummy root + descendants(parent) += descendants(j) + 1; + } + // Identify the relaxed supernodes by postorder traversal of the etree + Index snode_start; // beginning of a snode + StorageIndex k; + Index nsuper_et_post = 0; // Number of relaxed snodes in postordered etree + Index nsuper_et = 0; // Number of relaxed snodes in the original etree + StorageIndex l; + for (j = 0; j < n; ) + { + parent = et(j); + snode_start = j; + while ( parent != n && descendants(parent) < relax_columns ) + { + j = parent; + parent = et(j); + } + // Found a supernode in postordered etree, j is the last column + ++nsuper_et_post; + k = StorageIndex(n); + for (Index i = snode_start; i <= j; ++i) + k = (std::min)(k, inv_post(i)); + l = inv_post(j); + if ( (l - k) == (j - snode_start) ) // Same number of columns in the snode + { + // This is also a supernode in the original etree + relax_end(k) = l; // Record last column + ++nsuper_et; + } + else + { + for (Index i = snode_start; i <= j; ++i) + { + l = inv_post(i); + if (descendants(i) == 0) + { + relax_end(l) = l; + ++nsuper_et; + } + } + } + j++; + // Search for a new leaf + while (descendants(j) != 0 && j < n) j++; + } // End postorder traversal of the etree + + // Recover the original etree + et = et_save; +} + +} // end namespace internal + +} // end namespace Eigen +#endif // SPARSELU_HEAP_RELAX_SNODE_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_kernel_bmod.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_kernel_bmod.h new file mode 100644 index 0000000000000000000000000000000000000000..8c1b3e8bc67c89ea80b81f22691695cf6cebf90c --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_kernel_bmod.h @@ -0,0 +1,130 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef SPARSELU_KERNEL_BMOD_H +#define SPARSELU_KERNEL_BMOD_H + +namespace Eigen { +namespace internal { + +template struct LU_kernel_bmod +{ + /** \internal + * \brief Performs numeric block updates from a given supernode to a single column + * + * \param segsize Size of the segment (and blocks ) to use for updates + * \param[in,out] dense Packed values of the original matrix + * \param tempv temporary vector to use for updates + * \param lusup array containing the supernodes + * \param lda Leading dimension in the supernode + * \param nrow Number of rows in the rectangular part of the supernode + * \param lsub compressed row subscripts of supernodes + * \param lptr pointer to the first column of the current supernode in lsub + * \param no_zeros Number of nonzeros elements before the diagonal part of the supernode + */ + template + static EIGEN_DONT_INLINE void run(const Index segsize, BlockScalarVector& dense, ScalarVector& tempv, ScalarVector& lusup, Index& luptr, const Index lda, + const Index nrow, IndexVector& lsub, const Index lptr, const Index no_zeros); +}; + +template +template +EIGEN_DONT_INLINE void LU_kernel_bmod::run(const Index segsize, BlockScalarVector& dense, ScalarVector& tempv, ScalarVector& lusup, Index& luptr, const Index lda, + const Index nrow, IndexVector& lsub, const Index lptr, const Index no_zeros) +{ + typedef typename ScalarVector::Scalar Scalar; + // First, copy U[*,j] segment from dense(*) to tempv(*) + // The result of triangular solve is in tempv[*]; + // The result of matric-vector update is in dense[*] + Index isub = lptr + no_zeros; + Index i; + Index irow; + for (i = 0; i < ((SegSizeAtCompileTime==Dynamic)?segsize:SegSizeAtCompileTime); i++) + { + irow = lsub(isub); + tempv(i) = dense(irow); + ++isub; + } + // Dense triangular solve -- start effective triangle + luptr += lda * no_zeros + no_zeros; + // Form Eigen matrix and vector + Map, 0, OuterStride<> > A( &(lusup.data()[luptr]), segsize, segsize, OuterStride<>(lda) ); + Map > u(tempv.data(), segsize); + + u = A.template triangularView().solve(u); + + // Dense matrix-vector product y <-- B*x + luptr += segsize; + const Index PacketSize = internal::packet_traits::size; + Index ldl = internal::first_multiple(nrow, PacketSize); + Map, 0, OuterStride<> > B( &(lusup.data()[luptr]), nrow, segsize, OuterStride<>(lda) ); + Index aligned_offset = internal::first_default_aligned(tempv.data()+segsize, PacketSize); + Index aligned_with_B_offset = (PacketSize-internal::first_default_aligned(B.data(), PacketSize))%PacketSize; + Map, 0, OuterStride<> > l(tempv.data()+segsize+aligned_offset+aligned_with_B_offset, nrow, OuterStride<>(ldl) ); + + l.setZero(); + internal::sparselu_gemm(l.rows(), l.cols(), B.cols(), B.data(), B.outerStride(), u.data(), u.outerStride(), l.data(), l.outerStride()); + + // Scatter tempv[] into SPA dense[] as a temporary storage + isub = lptr + no_zeros; + for (i = 0; i < ((SegSizeAtCompileTime==Dynamic)?segsize:SegSizeAtCompileTime); i++) + { + irow = lsub(isub++); + dense(irow) = tempv(i); + } + + // Scatter l into SPA dense[] + for (i = 0; i < nrow; i++) + { + irow = lsub(isub++); + dense(irow) -= l(i); + } +} + +template <> struct LU_kernel_bmod<1> +{ + template + static EIGEN_DONT_INLINE void run(const Index /*segsize*/, BlockScalarVector& dense, ScalarVector& /*tempv*/, ScalarVector& lusup, Index& luptr, + const Index lda, const Index nrow, IndexVector& lsub, const Index lptr, const Index no_zeros); +}; + + +template +EIGEN_DONT_INLINE void LU_kernel_bmod<1>::run(const Index /*segsize*/, BlockScalarVector& dense, ScalarVector& /*tempv*/, ScalarVector& lusup, Index& luptr, + const Index lda, const Index nrow, IndexVector& lsub, const Index lptr, const Index no_zeros) +{ + typedef typename ScalarVector::Scalar Scalar; + typedef typename IndexVector::Scalar StorageIndex; + Scalar f = dense(lsub(lptr + no_zeros)); + luptr += lda * no_zeros + no_zeros + 1; + const Scalar* a(lusup.data() + luptr); + const StorageIndex* irow(lsub.data()+lptr + no_zeros + 1); + Index i = 0; + for (; i+1 < nrow; i+=2) + { + Index i0 = *(irow++); + Index i1 = *(irow++); + Scalar a0 = *(a++); + Scalar a1 = *(a++); + Scalar d0 = dense.coeff(i0); + Scalar d1 = dense.coeff(i1); + d0 -= f*a0; + d1 -= f*a1; + dense.coeffRef(i0) = d0; + dense.coeffRef(i1) = d1; + } + if(i +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of [s,d,c,z]panel_bmod.c file in SuperLU + + * -- SuperLU routine (version 3.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * October 15, 2003 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_PANEL_BMOD_H +#define SPARSELU_PANEL_BMOD_H + +namespace Eigen { +namespace internal { + +/** + * \brief Performs numeric block updates (sup-panel) in topological order. + * + * Before entering this routine, the original nonzeros in the panel + * were already copied into the spa[m,w] + * + * \param m number of rows in the matrix + * \param w Panel size + * \param jcol Starting column of the panel + * \param nseg Number of segments in the U part + * \param dense Store the full representation of the panel + * \param tempv working array + * \param segrep segment representative... first row in the segment + * \param repfnz First nonzero rows + * \param glu Global LU data. + * + * + */ +template +void SparseLUImpl::panel_bmod(const Index m, const Index w, const Index jcol, + const Index nseg, ScalarVector& dense, ScalarVector& tempv, + IndexVector& segrep, IndexVector& repfnz, GlobalLU_t& glu) +{ + + Index ksub,jj,nextl_col; + Index fsupc, nsupc, nsupr, nrow; + Index krep, kfnz; + Index lptr; // points to the row subscripts of a supernode + Index luptr; // ... + Index segsize,no_zeros ; + // For each nonz supernode segment of U[*,j] in topological order + Index k = nseg - 1; + const Index PacketSize = internal::packet_traits::size; + + for (ksub = 0; ksub < nseg; ksub++) + { // For each updating supernode + /* krep = representative of current k-th supernode + * fsupc = first supernodal column + * nsupc = number of columns in a supernode + * nsupr = number of rows in a supernode + */ + krep = segrep(k); k--; + fsupc = glu.xsup(glu.supno(krep)); + nsupc = krep - fsupc + 1; + nsupr = glu.xlsub(fsupc+1) - glu.xlsub(fsupc); + nrow = nsupr - nsupc; + lptr = glu.xlsub(fsupc); + + // loop over the panel columns to detect the actual number of columns and rows + Index u_rows = 0; + Index u_cols = 0; + for (jj = jcol; jj < jcol + w; jj++) + { + nextl_col = (jj-jcol) * m; + VectorBlock repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row + + kfnz = repfnz_col(krep); + if ( kfnz == emptyIdxLU ) + continue; // skip any zero segment + + segsize = krep - kfnz + 1; + u_cols++; + u_rows = (std::max)(segsize,u_rows); + } + + if(nsupc >= 2) + { + Index ldu = internal::first_multiple(u_rows, PacketSize); + Map > U(tempv.data(), u_rows, u_cols, OuterStride<>(ldu)); + + // gather U + Index u_col = 0; + for (jj = jcol; jj < jcol + w; jj++) + { + nextl_col = (jj-jcol) * m; + VectorBlock repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row + VectorBlock dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here + + kfnz = repfnz_col(krep); + if ( kfnz == emptyIdxLU ) + continue; // skip any zero segment + + segsize = krep - kfnz + 1; + luptr = glu.xlusup(fsupc); + no_zeros = kfnz - fsupc; + + Index isub = lptr + no_zeros; + Index off = u_rows-segsize; + for (Index i = 0; i < off; i++) U(i,u_col) = 0; + for (Index i = 0; i < segsize; i++) + { + Index irow = glu.lsub(isub); + U(i+off,u_col) = dense_col(irow); + ++isub; + } + u_col++; + } + // solve U = A^-1 U + luptr = glu.xlusup(fsupc); + Index lda = glu.xlusup(fsupc+1) - glu.xlusup(fsupc); + no_zeros = (krep - u_rows + 1) - fsupc; + luptr += lda * no_zeros + no_zeros; + MappedMatrixBlock A(glu.lusup.data()+luptr, u_rows, u_rows, OuterStride<>(lda) ); + U = A.template triangularView().solve(U); + + // update + luptr += u_rows; + MappedMatrixBlock B(glu.lusup.data()+luptr, nrow, u_rows, OuterStride<>(lda) ); + eigen_assert(tempv.size()>w*ldu + nrow*w + 1); + + Index ldl = internal::first_multiple(nrow, PacketSize); + Index offset = (PacketSize-internal::first_default_aligned(B.data(), PacketSize)) % PacketSize; + MappedMatrixBlock L(tempv.data()+w*ldu+offset, nrow, u_cols, OuterStride<>(ldl)); + + L.setZero(); + internal::sparselu_gemm(L.rows(), L.cols(), B.cols(), B.data(), B.outerStride(), U.data(), U.outerStride(), L.data(), L.outerStride()); + + // scatter U and L + u_col = 0; + for (jj = jcol; jj < jcol + w; jj++) + { + nextl_col = (jj-jcol) * m; + VectorBlock repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row + VectorBlock dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here + + kfnz = repfnz_col(krep); + if ( kfnz == emptyIdxLU ) + continue; // skip any zero segment + + segsize = krep - kfnz + 1; + no_zeros = kfnz - fsupc; + Index isub = lptr + no_zeros; + + Index off = u_rows-segsize; + for (Index i = 0; i < segsize; i++) + { + Index irow = glu.lsub(isub++); + dense_col(irow) = U.coeff(i+off,u_col); + U.coeffRef(i+off,u_col) = 0; + } + + // Scatter l into SPA dense[] + for (Index i = 0; i < nrow; i++) + { + Index irow = glu.lsub(isub++); + dense_col(irow) -= L.coeff(i,u_col); + L.coeffRef(i,u_col) = 0; + } + u_col++; + } + } + else // level 2 only + { + // Sequence through each column in the panel + for (jj = jcol; jj < jcol + w; jj++) + { + nextl_col = (jj-jcol) * m; + VectorBlock repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row + VectorBlock dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here + + kfnz = repfnz_col(krep); + if ( kfnz == emptyIdxLU ) + continue; // skip any zero segment + + segsize = krep - kfnz + 1; + luptr = glu.xlusup(fsupc); + + Index lda = glu.xlusup(fsupc+1)-glu.xlusup(fsupc);// nsupr + + // Perform a trianglar solve and block update, + // then scatter the result of sup-col update to dense[] + no_zeros = kfnz - fsupc; + if(segsize==1) LU_kernel_bmod<1>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + else if(segsize==2) LU_kernel_bmod<2>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + else if(segsize==3) LU_kernel_bmod<3>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + else LU_kernel_bmod::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros); + } // End for each column in the panel + } + + } // End for each updating supernode +} // end panel bmod + +} // end namespace internal + +} // end namespace Eigen + +#endif // SPARSELU_PANEL_BMOD_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_panel_dfs.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_panel_dfs.h new file mode 100644 index 0000000000000000000000000000000000000000..155df73368783affbec7d7d6eb81562ae752ee16 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_panel_dfs.h @@ -0,0 +1,258 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of [s,d,c,z]panel_dfs.c file in SuperLU + + * -- SuperLU routine (version 2.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November 15, 1997 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_PANEL_DFS_H +#define SPARSELU_PANEL_DFS_H + +namespace Eigen { + +namespace internal { + +template +struct panel_dfs_traits +{ + typedef typename IndexVector::Scalar StorageIndex; + panel_dfs_traits(Index jcol, StorageIndex* marker) + : m_jcol(jcol), m_marker(marker) + {} + bool update_segrep(Index krep, StorageIndex jj) + { + if(m_marker[krep] +template +void SparseLUImpl::dfs_kernel(const StorageIndex jj, IndexVector& perm_r, + Index& nseg, IndexVector& panel_lsub, IndexVector& segrep, + Ref repfnz_col, IndexVector& xprune, Ref marker, IndexVector& parent, + IndexVector& xplore, GlobalLU_t& glu, + Index& nextl_col, Index krow, Traits& traits + ) +{ + + StorageIndex kmark = marker(krow); + + // For each unmarked krow of jj + marker(krow) = jj; + StorageIndex kperm = perm_r(krow); + if (kperm == emptyIdxLU ) { + // krow is in L : place it in structure of L(*, jj) + panel_lsub(nextl_col++) = StorageIndex(krow); // krow is indexed into A + + traits.mem_expand(panel_lsub, nextl_col, kmark); + } + else + { + // krow is in U : if its supernode-representative krep + // has been explored, update repfnz(*) + // krep = supernode representative of the current row + StorageIndex krep = glu.xsup(glu.supno(kperm)+1) - 1; + // First nonzero element in the current column: + StorageIndex myfnz = repfnz_col(krep); + + if (myfnz != emptyIdxLU ) + { + // Representative visited before + if (myfnz > kperm ) repfnz_col(krep) = kperm; + + } + else + { + // Otherwise, perform dfs starting at krep + StorageIndex oldrep = emptyIdxLU; + parent(krep) = oldrep; + repfnz_col(krep) = kperm; + StorageIndex xdfs = glu.xlsub(krep); + Index maxdfs = xprune(krep); + + StorageIndex kpar; + do + { + // For each unmarked kchild of krep + while (xdfs < maxdfs) + { + StorageIndex kchild = glu.lsub(xdfs); + xdfs++; + StorageIndex chmark = marker(kchild); + + if (chmark != jj ) + { + marker(kchild) = jj; + StorageIndex chperm = perm_r(kchild); + + if (chperm == emptyIdxLU) + { + // case kchild is in L: place it in L(*, j) + panel_lsub(nextl_col++) = kchild; + traits.mem_expand(panel_lsub, nextl_col, chmark); + } + else + { + // case kchild is in U : + // chrep = its supernode-rep. If its rep has been explored, + // update its repfnz(*) + StorageIndex chrep = glu.xsup(glu.supno(chperm)+1) - 1; + myfnz = repfnz_col(chrep); + + if (myfnz != emptyIdxLU) + { // Visited before + if (myfnz > chperm) + repfnz_col(chrep) = chperm; + } + else + { // Cont. dfs at snode-rep of kchild + xplore(krep) = xdfs; + oldrep = krep; + krep = chrep; // Go deeper down G(L) + parent(krep) = oldrep; + repfnz_col(krep) = chperm; + xdfs = glu.xlsub(krep); + maxdfs = xprune(krep); + + } // end if myfnz != -1 + } // end if chperm == -1 + + } // end if chmark !=jj + } // end while xdfs < maxdfs + + // krow has no more unexplored nbrs : + // Place snode-rep krep in postorder DFS, if this + // segment is seen for the first time. (Note that + // "repfnz(krep)" may change later.) + // Baktrack dfs to its parent + if(traits.update_segrep(krep,jj)) + //if (marker1(krep) < jcol ) + { + segrep(nseg) = krep; + ++nseg; + //marker1(krep) = jj; + } + + kpar = parent(krep); // Pop recursion, mimic recursion + if (kpar == emptyIdxLU) + break; // dfs done + krep = kpar; + xdfs = xplore(krep); + maxdfs = xprune(krep); + + } while (kpar != emptyIdxLU); // Do until empty stack + + } // end if (myfnz = -1) + + } // end if (kperm == -1) +} + +/** + * \brief Performs a symbolic factorization on a panel of columns [jcol, jcol+w) + * + * A supernode representative is the last column of a supernode. + * The nonzeros in U[*,j] are segments that end at supernodes representatives + * + * The routine returns a list of the supernodal representatives + * in topological order of the dfs that generates them. This list is + * a superset of the topological order of each individual column within + * the panel. + * The location of the first nonzero in each supernodal segment + * (supernodal entry location) is also returned. Each column has + * a separate list for this purpose. + * + * Two markers arrays are used for dfs : + * marker[i] == jj, if i was visited during dfs of current column jj; + * marker1[i] >= jcol, if i was visited by earlier columns in this panel; + * + * \param[in] m number of rows in the matrix + * \param[in] w Panel size + * \param[in] jcol Starting column of the panel + * \param[in] A Input matrix in column-major storage + * \param[in] perm_r Row permutation + * \param[out] nseg Number of U segments + * \param[out] dense Accumulate the column vectors of the panel + * \param[out] panel_lsub Subscripts of the row in the panel + * \param[out] segrep Segment representative i.e first nonzero row of each segment + * \param[out] repfnz First nonzero location in each row + * \param[out] xprune The pruned elimination tree + * \param[out] marker work vector + * \param parent The elimination tree + * \param xplore work vector + * \param glu The global data structure + * + */ + +template +void SparseLUImpl::panel_dfs(const Index m, const Index w, const Index jcol, MatrixType& A, IndexVector& perm_r, Index& nseg, ScalarVector& dense, IndexVector& panel_lsub, IndexVector& segrep, IndexVector& repfnz, IndexVector& xprune, IndexVector& marker, IndexVector& parent, IndexVector& xplore, GlobalLU_t& glu) +{ + Index nextl_col; // Next available position in panel_lsub[*,jj] + + // Initialize pointers + VectorBlock marker1(marker, m, m); + nseg = 0; + + panel_dfs_traits traits(jcol, marker1.data()); + + // For each column in the panel + for (StorageIndex jj = StorageIndex(jcol); jj < jcol + w; jj++) + { + nextl_col = (jj - jcol) * m; + + VectorBlock repfnz_col(repfnz, nextl_col, m); // First nonzero location in each row + VectorBlock dense_col(dense,nextl_col, m); // Accumulate a column vector here + + + // For each nnz in A[*, jj] do depth first search + for (typename MatrixType::InnerIterator it(A, jj); it; ++it) + { + Index krow = it.row(); + dense_col(krow) = it.value(); + + StorageIndex kmark = marker(krow); + if (kmark == jj) + continue; // krow visited before, go to the next nonzero + + dfs_kernel(jj, perm_r, nseg, panel_lsub, segrep, repfnz_col, xprune, marker, parent, + xplore, glu, nextl_col, krow, traits); + }// end for nonzeros in column jj + + } // end for column jj +} + +} // end namespace internal +} // end namespace Eigen + +#endif // SPARSELU_PANEL_DFS_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pivotL.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pivotL.h new file mode 100644 index 0000000000000000000000000000000000000000..a86dac93fa9b384d49fa61bd37e9b31a625dcdfb --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pivotL.h @@ -0,0 +1,137 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of xpivotL.c file in SuperLU + + * -- SuperLU routine (version 3.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * October 15, 2003 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_PIVOTL_H +#define SPARSELU_PIVOTL_H + +namespace Eigen { +namespace internal { + +/** + * \brief Performs the numerical pivotin on the current column of L, and the CDIV operation. + * + * Pivot policy : + * (1) Compute thresh = u * max_(i>=j) abs(A_ij); + * (2) IF user specifies pivot row k and abs(A_kj) >= thresh THEN + * pivot row = k; + * ELSE IF abs(A_jj) >= thresh THEN + * pivot row = j; + * ELSE + * pivot row = m; + * + * Note: If you absolutely want to use a given pivot order, then set u=0.0. + * + * \param jcol The current column of L + * \param diagpivotthresh diagonal pivoting threshold + * \param[in,out] perm_r Row permutation (threshold pivoting) + * \param[in] iperm_c column permutation - used to finf diagonal of Pc*A*Pc' + * \param[out] pivrow The pivot row + * \param glu Global LU data + * \return 0 if success, i > 0 if U(i,i) is exactly zero + * + */ +template +Index SparseLUImpl::pivotL(const Index jcol, const RealScalar& diagpivotthresh, IndexVector& perm_r, IndexVector& iperm_c, Index& pivrow, GlobalLU_t& glu) +{ + + Index fsupc = (glu.xsup)((glu.supno)(jcol)); // First column in the supernode containing the column jcol + Index nsupc = jcol - fsupc; // Number of columns in the supernode portion, excluding jcol; nsupc >=0 + Index lptr = glu.xlsub(fsupc); // pointer to the starting location of the row subscripts for this supernode portion + Index nsupr = glu.xlsub(fsupc+1) - lptr; // Number of rows in the supernode + Index lda = glu.xlusup(fsupc+1) - glu.xlusup(fsupc); // leading dimension + Scalar* lu_sup_ptr = &(glu.lusup.data()[glu.xlusup(fsupc)]); // Start of the current supernode + Scalar* lu_col_ptr = &(glu.lusup.data()[glu.xlusup(jcol)]); // Start of jcol in the supernode + StorageIndex* lsub_ptr = &(glu.lsub.data()[lptr]); // Start of row indices of the supernode + + // Determine the largest abs numerical value for partial pivoting + Index diagind = iperm_c(jcol); // diagonal index + RealScalar pivmax(-1.0); + Index pivptr = nsupc; + Index diag = emptyIdxLU; + RealScalar rtemp; + Index isub, icol, itemp, k; + for (isub = nsupc; isub < nsupr; ++isub) { + using std::abs; + rtemp = abs(lu_col_ptr[isub]); + if (rtemp > pivmax) { + pivmax = rtemp; + pivptr = isub; + } + if (lsub_ptr[isub] == diagind) diag = isub; + } + + // Test for singularity + if ( pivmax <= RealScalar(0.0) ) { + // if pivmax == -1, the column is structurally empty, otherwise it is only numerically zero + pivrow = pivmax < RealScalar(0.0) ? diagind : lsub_ptr[pivptr]; + perm_r(pivrow) = StorageIndex(jcol); + return (jcol+1); + } + + RealScalar thresh = diagpivotthresh * pivmax; + + // Choose appropriate pivotal element + + { + // Test if the diagonal element can be used as a pivot (given the threshold value) + if (diag >= 0 ) + { + // Diagonal element exists + using std::abs; + rtemp = abs(lu_col_ptr[diag]); + if (rtemp != RealScalar(0.0) && rtemp >= thresh) pivptr = diag; + } + pivrow = lsub_ptr[pivptr]; + } + + // Record pivot row + perm_r(pivrow) = StorageIndex(jcol); + // Interchange row subscripts + if (pivptr != nsupc ) + { + std::swap( lsub_ptr[pivptr], lsub_ptr[nsupc] ); + // Interchange numerical values as well, for the two rows in the whole snode + // such that L is indexed the same way as A + for (icol = 0; icol <= nsupc; icol++) + { + itemp = pivptr + icol * lda; + std::swap(lu_sup_ptr[itemp], lu_sup_ptr[nsupc + icol * lda]); + } + } + // cdiv operations + Scalar temp = Scalar(1.0) / lu_col_ptr[nsupc]; + for (k = nsupc+1; k < nsupr; k++) + lu_col_ptr[k] *= temp; + return 0; +} + +} // end namespace internal +} // end namespace Eigen + +#endif // SPARSELU_PIVOTL_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pruneL.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pruneL.h new file mode 100644 index 0000000000000000000000000000000000000000..ad32fed5e6b768384103d7321e57eea2d0421056 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_pruneL.h @@ -0,0 +1,136 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + * NOTE: This file is the modified version of [s,d,c,z]pruneL.c file in SuperLU + + * -- SuperLU routine (version 2.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November 15, 1997 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ +#ifndef SPARSELU_PRUNEL_H +#define SPARSELU_PRUNEL_H + +namespace Eigen { +namespace internal { + +/** + * \brief Prunes the L-structure. + * + * It prunes the L-structure of supernodes whose L-structure contains the current pivot row "pivrow" + * + * + * \param jcol The current column of L + * \param[in] perm_r Row permutation + * \param[out] pivrow The pivot row + * \param nseg Number of segments + * \param segrep + * \param repfnz + * \param[out] xprune + * \param glu Global LU data + * + */ +template +void SparseLUImpl::pruneL(const Index jcol, const IndexVector& perm_r, const Index pivrow, const Index nseg, + const IndexVector& segrep, BlockIndexVector repfnz, IndexVector& xprune, GlobalLU_t& glu) +{ + // For each supernode-rep irep in U(*,j] + Index jsupno = glu.supno(jcol); + Index i,irep,irep1; + bool movnum, do_prune = false; + Index kmin = 0, kmax = 0, minloc, maxloc,krow; + for (i = 0; i < nseg; i++) + { + irep = segrep(i); + irep1 = irep + 1; + do_prune = false; + + // Don't prune with a zero U-segment + if (repfnz(irep) == emptyIdxLU) continue; + + // If a snode overlaps with the next panel, then the U-segment + // is fragmented into two parts -- irep and irep1. We should let + // pruning occur at the rep-column in irep1s snode. + if (glu.supno(irep) == glu.supno(irep1) ) continue; // don't prune + + // If it has not been pruned & it has a nonz in row L(pivrow,i) + if (glu.supno(irep) != jsupno ) + { + if ( xprune (irep) >= glu.xlsub(irep1) ) + { + kmin = glu.xlsub(irep); + kmax = glu.xlsub(irep1) - 1; + for (krow = kmin; krow <= kmax; krow++) + { + if (glu.lsub(krow) == pivrow) + { + do_prune = true; + break; + } + } + } + + if (do_prune) + { + // do a quicksort-type partition + // movnum=true means that the num values have to be exchanged + movnum = false; + if (irep == glu.xsup(glu.supno(irep)) ) // Snode of size 1 + movnum = true; + + while (kmin <= kmax) + { + if (perm_r(glu.lsub(kmax)) == emptyIdxLU) + kmax--; + else if ( perm_r(glu.lsub(kmin)) != emptyIdxLU) + kmin++; + else + { + // kmin below pivrow (not yet pivoted), and kmax + // above pivrow: interchange the two suscripts + std::swap(glu.lsub(kmin), glu.lsub(kmax)); + + // If the supernode has only one column, then we + // only keep one set of subscripts. For any subscript + // intercnahge performed, similar interchange must be + // done on the numerical values. + if (movnum) + { + minloc = glu.xlusup(irep) + ( kmin - glu.xlsub(irep) ); + maxloc = glu.xlusup(irep) + ( kmax - glu.xlsub(irep) ); + std::swap(glu.lusup(minloc), glu.lusup(maxloc)); + } + kmin++; + kmax--; + } + } // end while + + xprune(irep) = StorageIndex(kmin); //Pruning + } // end if do_prune + } // end pruning + } // End for each U-segment +} + +} // end namespace internal +} // end namespace Eigen + +#endif // SPARSELU_PRUNEL_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_relax_snode.h b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_relax_snode.h new file mode 100644 index 0000000000000000000000000000000000000000..c408d01b406941e273e4cd4627ef3ca447cb0554 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SparseLU/SparseLU_relax_snode.h @@ -0,0 +1,83 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* This file is a modified version of heap_relax_snode.c file in SuperLU + * -- SuperLU routine (version 3.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * October 15, 2003 + * + * Copyright (c) 1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program for any + * purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is + * granted, provided the above notices are retained, and a notice that + * the code was modified is included with the above copyright notice. + */ + +#ifndef SPARSELU_RELAX_SNODE_H +#define SPARSELU_RELAX_SNODE_H + +namespace Eigen { + +namespace internal { + +/** + * \brief Identify the initial relaxed supernodes + * + * This routine is applied to a column elimination tree. + * It assumes that the matrix has been reordered according to the postorder of the etree + * \param n the number of columns + * \param et elimination tree + * \param relax_columns Maximum number of columns allowed in a relaxed snode + * \param descendants Number of descendants of each node in the etree + * \param relax_end last column in a supernode + */ +template +void SparseLUImpl::relax_snode (const Index n, IndexVector& et, const Index relax_columns, IndexVector& descendants, IndexVector& relax_end) +{ + + // compute the number of descendants of each node in the etree + Index parent; + relax_end.setConstant(emptyIdxLU); + descendants.setZero(); + for (Index j = 0; j < n; j++) + { + parent = et(j); + if (parent != n) // not the dummy root + descendants(parent) += descendants(j) + 1; + } + // Identify the relaxed supernodes by postorder traversal of the etree + Index snode_start; // beginning of a snode + for (Index j = 0; j < n; ) + { + parent = et(j); + snode_start = j; + while ( parent != n && descendants(parent) < relax_columns ) + { + j = parent; + parent = et(j); + } + // Found a supernode in postordered etree, j is the last column + relax_end(snode_start) = StorageIndex(j); // Record last column + j++; + // Search for a new leaf + while (descendants(j) != 0 && j < n) j++; + } // End postorder traversal of the etree + +} + +} // end namespace internal + +} // end namespace Eigen +#endif diff --git a/vendor/eigen/include/eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h b/vendor/eigen/include/eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..d1d3ad7f192915d146fe1eaba403e02c716d22e9 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/SuperLUSupport/SuperLUSupport.h @@ -0,0 +1,1025 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SUPERLUSUPPORT_H +#define EIGEN_SUPERLUSUPPORT_H + +namespace Eigen { + +#if defined(SUPERLU_MAJOR_VERSION) && (SUPERLU_MAJOR_VERSION >= 5) +#define DECL_GSSVX(PREFIX,FLOATTYPE,KEYTYPE) \ + extern "C" { \ + extern void PREFIX##gssvx(superlu_options_t *, SuperMatrix *, int *, int *, int *, \ + char *, FLOATTYPE *, FLOATTYPE *, SuperMatrix *, SuperMatrix *, \ + void *, int, SuperMatrix *, SuperMatrix *, \ + FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, \ + GlobalLU_t *, mem_usage_t *, SuperLUStat_t *, int *); \ + } \ + inline float SuperLU_gssvx(superlu_options_t *options, SuperMatrix *A, \ + int *perm_c, int *perm_r, int *etree, char *equed, \ + FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \ + SuperMatrix *U, void *work, int lwork, \ + SuperMatrix *B, SuperMatrix *X, \ + FLOATTYPE *recip_pivot_growth, \ + FLOATTYPE *rcond, FLOATTYPE *ferr, FLOATTYPE *berr, \ + SuperLUStat_t *stats, int *info, KEYTYPE) { \ + mem_usage_t mem_usage; \ + GlobalLU_t gLU; \ + PREFIX##gssvx(options, A, perm_c, perm_r, etree, equed, R, C, L, \ + U, work, lwork, B, X, recip_pivot_growth, rcond, \ + ferr, berr, &gLU, &mem_usage, stats, info); \ + return mem_usage.for_lu; /* bytes used by the factor storage */ \ + } +#else // version < 5.0 +#define DECL_GSSVX(PREFIX,FLOATTYPE,KEYTYPE) \ + extern "C" { \ + extern void PREFIX##gssvx(superlu_options_t *, SuperMatrix *, int *, int *, int *, \ + char *, FLOATTYPE *, FLOATTYPE *, SuperMatrix *, SuperMatrix *, \ + void *, int, SuperMatrix *, SuperMatrix *, \ + FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, FLOATTYPE *, \ + mem_usage_t *, SuperLUStat_t *, int *); \ + } \ + inline float SuperLU_gssvx(superlu_options_t *options, SuperMatrix *A, \ + int *perm_c, int *perm_r, int *etree, char *equed, \ + FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \ + SuperMatrix *U, void *work, int lwork, \ + SuperMatrix *B, SuperMatrix *X, \ + FLOATTYPE *recip_pivot_growth, \ + FLOATTYPE *rcond, FLOATTYPE *ferr, FLOATTYPE *berr, \ + SuperLUStat_t *stats, int *info, KEYTYPE) { \ + mem_usage_t mem_usage; \ + PREFIX##gssvx(options, A, perm_c, perm_r, etree, equed, R, C, L, \ + U, work, lwork, B, X, recip_pivot_growth, rcond, \ + ferr, berr, &mem_usage, stats, info); \ + return mem_usage.for_lu; /* bytes used by the factor storage */ \ + } +#endif + +DECL_GSSVX(s,float,float) +DECL_GSSVX(c,float,std::complex) +DECL_GSSVX(d,double,double) +DECL_GSSVX(z,double,std::complex) + +#ifdef MILU_ALPHA +#define EIGEN_SUPERLU_HAS_ILU +#endif + +#ifdef EIGEN_SUPERLU_HAS_ILU + +// similarly for the incomplete factorization using gsisx +#define DECL_GSISX(PREFIX,FLOATTYPE,KEYTYPE) \ + extern "C" { \ + extern void PREFIX##gsisx(superlu_options_t *, SuperMatrix *, int *, int *, int *, \ + char *, FLOATTYPE *, FLOATTYPE *, SuperMatrix *, SuperMatrix *, \ + void *, int, SuperMatrix *, SuperMatrix *, FLOATTYPE *, FLOATTYPE *, \ + mem_usage_t *, SuperLUStat_t *, int *); \ + } \ + inline float SuperLU_gsisx(superlu_options_t *options, SuperMatrix *A, \ + int *perm_c, int *perm_r, int *etree, char *equed, \ + FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \ + SuperMatrix *U, void *work, int lwork, \ + SuperMatrix *B, SuperMatrix *X, \ + FLOATTYPE *recip_pivot_growth, \ + FLOATTYPE *rcond, \ + SuperLUStat_t *stats, int *info, KEYTYPE) { \ + mem_usage_t mem_usage; \ + PREFIX##gsisx(options, A, perm_c, perm_r, etree, equed, R, C, L, \ + U, work, lwork, B, X, recip_pivot_growth, rcond, \ + &mem_usage, stats, info); \ + return mem_usage.for_lu; /* bytes used by the factor storage */ \ + } + +DECL_GSISX(s,float,float) +DECL_GSISX(c,float,std::complex) +DECL_GSISX(d,double,double) +DECL_GSISX(z,double,std::complex) + +#endif + +template +struct SluMatrixMapHelper; + +/** \internal + * + * A wrapper class for SuperLU matrices. It supports only compressed sparse matrices + * and dense matrices. Supernodal and other fancy format are not supported by this wrapper. + * + * This wrapper class mainly aims to avoids the need of dynamic allocation of the storage structure. + */ +struct SluMatrix : SuperMatrix +{ + SluMatrix() + { + Store = &storage; + } + + SluMatrix(const SluMatrix& other) + : SuperMatrix(other) + { + Store = &storage; + storage = other.storage; + } + + SluMatrix& operator=(const SluMatrix& other) + { + SuperMatrix::operator=(static_cast(other)); + Store = &storage; + storage = other.storage; + return *this; + } + + struct + { + union {int nnz;int lda;}; + void *values; + int *innerInd; + int *outerInd; + } storage; + + void setStorageType(Stype_t t) + { + Stype = t; + if (t==SLU_NC || t==SLU_NR || t==SLU_DN) + Store = &storage; + else + { + eigen_assert(false && "storage type not supported"); + Store = 0; + } + } + + template + void setScalarType() + { + if (internal::is_same::value) + Dtype = SLU_S; + else if (internal::is_same::value) + Dtype = SLU_D; + else if (internal::is_same >::value) + Dtype = SLU_C; + else if (internal::is_same >::value) + Dtype = SLU_Z; + else + { + eigen_assert(false && "Scalar type not supported by SuperLU"); + } + } + + template + static SluMatrix Map(MatrixBase& _mat) + { + MatrixType& mat(_mat.derived()); + eigen_assert( ((MatrixType::Flags&RowMajorBit)!=RowMajorBit) && "row-major dense matrices are not supported by SuperLU"); + SluMatrix res; + res.setStorageType(SLU_DN); + res.setScalarType(); + res.Mtype = SLU_GE; + + res.nrow = internal::convert_index(mat.rows()); + res.ncol = internal::convert_index(mat.cols()); + + res.storage.lda = internal::convert_index(MatrixType::IsVectorAtCompileTime ? mat.size() : mat.outerStride()); + res.storage.values = (void*)(mat.data()); + return res; + } + + template + static SluMatrix Map(SparseMatrixBase& a_mat) + { + MatrixType &mat(a_mat.derived()); + SluMatrix res; + if ((MatrixType::Flags&RowMajorBit)==RowMajorBit) + { + res.setStorageType(SLU_NR); + res.nrow = internal::convert_index(mat.cols()); + res.ncol = internal::convert_index(mat.rows()); + } + else + { + res.setStorageType(SLU_NC); + res.nrow = internal::convert_index(mat.rows()); + res.ncol = internal::convert_index(mat.cols()); + } + + res.Mtype = SLU_GE; + + res.storage.nnz = internal::convert_index(mat.nonZeros()); + res.storage.values = mat.valuePtr(); + res.storage.innerInd = mat.innerIndexPtr(); + res.storage.outerInd = mat.outerIndexPtr(); + + res.setScalarType(); + + // FIXME the following is not very accurate + if (int(MatrixType::Flags) & int(Upper)) + res.Mtype = SLU_TRU; + if (int(MatrixType::Flags) & int(Lower)) + res.Mtype = SLU_TRL; + + eigen_assert(((int(MatrixType::Flags) & int(SelfAdjoint))==0) && "SelfAdjoint matrix shape not supported by SuperLU"); + + return res; + } +}; + +template +struct SluMatrixMapHelper > +{ + typedef Matrix MatrixType; + static void run(MatrixType& mat, SluMatrix& res) + { + eigen_assert( ((Options&RowMajor)!=RowMajor) && "row-major dense matrices is not supported by SuperLU"); + res.setStorageType(SLU_DN); + res.setScalarType(); + res.Mtype = SLU_GE; + + res.nrow = mat.rows(); + res.ncol = mat.cols(); + + res.storage.lda = mat.outerStride(); + res.storage.values = mat.data(); + } +}; + +template +struct SluMatrixMapHelper > +{ + typedef Derived MatrixType; + static void run(MatrixType& mat, SluMatrix& res) + { + if ((MatrixType::Flags&RowMajorBit)==RowMajorBit) + { + res.setStorageType(SLU_NR); + res.nrow = mat.cols(); + res.ncol = mat.rows(); + } + else + { + res.setStorageType(SLU_NC); + res.nrow = mat.rows(); + res.ncol = mat.cols(); + } + + res.Mtype = SLU_GE; + + res.storage.nnz = mat.nonZeros(); + res.storage.values = mat.valuePtr(); + res.storage.innerInd = mat.innerIndexPtr(); + res.storage.outerInd = mat.outerIndexPtr(); + + res.setScalarType(); + + // FIXME the following is not very accurate + if (MatrixType::Flags & Upper) + res.Mtype = SLU_TRU; + if (MatrixType::Flags & Lower) + res.Mtype = SLU_TRL; + + eigen_assert(((MatrixType::Flags & SelfAdjoint)==0) && "SelfAdjoint matrix shape not supported by SuperLU"); + } +}; + +namespace internal { + +template +SluMatrix asSluMatrix(MatrixType& mat) +{ + return SluMatrix::Map(mat); +} + +/** View a Super LU matrix as an Eigen expression */ +template +MappedSparseMatrix map_superlu(SluMatrix& sluMat) +{ + eigen_assert(((Flags&RowMajor)==RowMajor && sluMat.Stype == SLU_NR) + || ((Flags&ColMajor)==ColMajor && sluMat.Stype == SLU_NC)); + + Index outerSize = (Flags&RowMajor)==RowMajor ? sluMat.ncol : sluMat.nrow; + + return MappedSparseMatrix( + sluMat.nrow, sluMat.ncol, sluMat.storage.outerInd[outerSize], + sluMat.storage.outerInd, sluMat.storage.innerInd, reinterpret_cast(sluMat.storage.values) ); +} + +} // end namespace internal + +/** \ingroup SuperLUSupport_Module + * \class SuperLUBase + * \brief The base class for the direct and incomplete LU factorization of SuperLU + */ +template +class SuperLUBase : public SparseSolverBase +{ + protected: + typedef SparseSolverBase Base; + using Base::derived; + using Base::m_isInitialized; + public: + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef Matrix Vector; + typedef Matrix IntRowVectorType; + typedef Matrix IntColVectorType; + typedef Map > PermutationMap; + typedef SparseMatrix LUMatrixType; + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + SuperLUBase() {} + + ~SuperLUBase() + { + clearFactors(); + } + + inline Index rows() const { return m_matrix.rows(); } + inline Index cols() const { return m_matrix.cols(); } + + /** \returns a reference to the Super LU option object to configure the Super LU algorithms. */ + inline superlu_options_t& options() { return m_sluOptions; } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + /** Computes the sparse Cholesky decomposition of \a matrix */ + void compute(const MatrixType& matrix) + { + derived().analyzePattern(matrix); + derived().factorize(matrix); + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + void analyzePattern(const MatrixType& /*matrix*/) + { + m_isInitialized = true; + m_info = Success; + m_analysisIsOk = true; + m_factorizationIsOk = false; + } + + template + void dumpMemory(Stream& /*s*/) + {} + + protected: + + void initFactorization(const MatrixType& a) + { + set_default_options(&this->m_sluOptions); + + const Index size = a.rows(); + m_matrix = a; + + m_sluA = internal::asSluMatrix(m_matrix); + clearFactors(); + + m_p.resize(size); + m_q.resize(size); + m_sluRscale.resize(size); + m_sluCscale.resize(size); + m_sluEtree.resize(size); + + // set empty B and X + m_sluB.setStorageType(SLU_DN); + m_sluB.setScalarType(); + m_sluB.Mtype = SLU_GE; + m_sluB.storage.values = 0; + m_sluB.nrow = 0; + m_sluB.ncol = 0; + m_sluB.storage.lda = internal::convert_index(size); + m_sluX = m_sluB; + + m_extractedDataAreDirty = true; + } + + void init() + { + m_info = InvalidInput; + m_isInitialized = false; + m_sluL.Store = 0; + m_sluU.Store = 0; + } + + void extractData() const; + + void clearFactors() + { + if(m_sluL.Store) + Destroy_SuperNode_Matrix(&m_sluL); + if(m_sluU.Store) + Destroy_CompCol_Matrix(&m_sluU); + + m_sluL.Store = 0; + m_sluU.Store = 0; + + memset(&m_sluL,0,sizeof m_sluL); + memset(&m_sluU,0,sizeof m_sluU); + } + + // cached data to reduce reallocation, etc. + mutable LUMatrixType m_l; + mutable LUMatrixType m_u; + mutable IntColVectorType m_p; + mutable IntRowVectorType m_q; + + mutable LUMatrixType m_matrix; // copy of the factorized matrix + mutable SluMatrix m_sluA; + mutable SuperMatrix m_sluL, m_sluU; + mutable SluMatrix m_sluB, m_sluX; + mutable SuperLUStat_t m_sluStat; + mutable superlu_options_t m_sluOptions; + mutable std::vector m_sluEtree; + mutable Matrix m_sluRscale, m_sluCscale; + mutable Matrix m_sluFerr, m_sluBerr; + mutable char m_sluEqued; + + mutable ComputationInfo m_info; + int m_factorizationIsOk; + int m_analysisIsOk; + mutable bool m_extractedDataAreDirty; + + private: + SuperLUBase(SuperLUBase& ) { } +}; + + +/** \ingroup SuperLUSupport_Module + * \class SuperLU + * \brief A sparse direct LU factorization and solver based on the SuperLU library + * + * This class allows to solve for A.X = B sparse linear problems via a direct LU factorization + * using the SuperLU library. The sparse matrix A must be squared and invertible. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * + * \warning This class is only for the 4.x versions of SuperLU. The 3.x and 5.x versions are not supported. + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class SparseLU + */ +template +class SuperLU : public SuperLUBase<_MatrixType,SuperLU<_MatrixType> > +{ + public: + typedef SuperLUBase<_MatrixType,SuperLU> Base; + typedef _MatrixType MatrixType; + typedef typename Base::Scalar Scalar; + typedef typename Base::RealScalar RealScalar; + typedef typename Base::StorageIndex StorageIndex; + typedef typename Base::IntRowVectorType IntRowVectorType; + typedef typename Base::IntColVectorType IntColVectorType; + typedef typename Base::PermutationMap PermutationMap; + typedef typename Base::LUMatrixType LUMatrixType; + typedef TriangularView LMatrixType; + typedef TriangularView UMatrixType; + + public: + using Base::_solve_impl; + + SuperLU() : Base() { init(); } + + explicit SuperLU(const MatrixType& matrix) : Base() + { + init(); + Base::compute(matrix); + } + + ~SuperLU() + { + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + void analyzePattern(const MatrixType& matrix) + { + m_info = InvalidInput; + m_isInitialized = false; + Base::analyzePattern(matrix); + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed. + * + * \sa analyzePattern() + */ + void factorize(const MatrixType& matrix); + + /** \internal */ + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const; + + inline const LMatrixType& matrixL() const + { + if (m_extractedDataAreDirty) this->extractData(); + return m_l; + } + + inline const UMatrixType& matrixU() const + { + if (m_extractedDataAreDirty) this->extractData(); + return m_u; + } + + inline const IntColVectorType& permutationP() const + { + if (m_extractedDataAreDirty) this->extractData(); + return m_p; + } + + inline const IntRowVectorType& permutationQ() const + { + if (m_extractedDataAreDirty) this->extractData(); + return m_q; + } + + Scalar determinant() const; + + protected: + + using Base::m_matrix; + using Base::m_sluOptions; + using Base::m_sluA; + using Base::m_sluB; + using Base::m_sluX; + using Base::m_p; + using Base::m_q; + using Base::m_sluEtree; + using Base::m_sluEqued; + using Base::m_sluRscale; + using Base::m_sluCscale; + using Base::m_sluL; + using Base::m_sluU; + using Base::m_sluStat; + using Base::m_sluFerr; + using Base::m_sluBerr; + using Base::m_l; + using Base::m_u; + + using Base::m_analysisIsOk; + using Base::m_factorizationIsOk; + using Base::m_extractedDataAreDirty; + using Base::m_isInitialized; + using Base::m_info; + + void init() + { + Base::init(); + + set_default_options(&this->m_sluOptions); + m_sluOptions.PrintStat = NO; + m_sluOptions.ConditionNumber = NO; + m_sluOptions.Trans = NOTRANS; + m_sluOptions.ColPerm = COLAMD; + } + + + private: + SuperLU(SuperLU& ) { } +}; + +template +void SuperLU::factorize(const MatrixType& a) +{ + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + if(!m_analysisIsOk) + { + m_info = InvalidInput; + return; + } + + this->initFactorization(a); + + m_sluOptions.ColPerm = COLAMD; + int info = 0; + RealScalar recip_pivot_growth, rcond; + RealScalar ferr, berr; + + StatInit(&m_sluStat); + SuperLU_gssvx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0], + &m_sluEqued, &m_sluRscale[0], &m_sluCscale[0], + &m_sluL, &m_sluU, + NULL, 0, + &m_sluB, &m_sluX, + &recip_pivot_growth, &rcond, + &ferr, &berr, + &m_sluStat, &info, Scalar()); + StatFree(&m_sluStat); + + m_extractedDataAreDirty = true; + + // FIXME how to better check for errors ??? + m_info = info == 0 ? Success : NumericalIssue; + m_factorizationIsOk = true; +} + +template +template +void SuperLU::_solve_impl(const MatrixBase &b, MatrixBase& x) const +{ + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or analyzePattern()/factorize()"); + + const Index rhsCols = b.cols(); + eigen_assert(m_matrix.rows()==b.rows()); + + m_sluOptions.Trans = NOTRANS; + m_sluOptions.Fact = FACTORED; + m_sluOptions.IterRefine = NOREFINE; + + + m_sluFerr.resize(rhsCols); + m_sluBerr.resize(rhsCols); + + Ref > b_ref(b); + Ref > x_ref(x); + + m_sluB = SluMatrix::Map(b_ref.const_cast_derived()); + m_sluX = SluMatrix::Map(x_ref.const_cast_derived()); + + typename Rhs::PlainObject b_cpy; + if(m_sluEqued!='N') + { + b_cpy = b; + m_sluB = SluMatrix::Map(b_cpy.const_cast_derived()); + } + + StatInit(&m_sluStat); + int info = 0; + RealScalar recip_pivot_growth, rcond; + SuperLU_gssvx(&m_sluOptions, &m_sluA, + m_q.data(), m_p.data(), + &m_sluEtree[0], &m_sluEqued, + &m_sluRscale[0], &m_sluCscale[0], + &m_sluL, &m_sluU, + NULL, 0, + &m_sluB, &m_sluX, + &recip_pivot_growth, &rcond, + &m_sluFerr[0], &m_sluBerr[0], + &m_sluStat, &info, Scalar()); + StatFree(&m_sluStat); + + if(x.derived().data() != x_ref.data()) + x = x_ref; + + m_info = info==0 ? Success : NumericalIssue; +} + +// the code of this extractData() function has been adapted from the SuperLU's Matlab support code, +// +// Copyright (c) 1994 by Xerox Corporation. All rights reserved. +// +// THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY +// EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. +// +template +void SuperLUBase::extractData() const +{ + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for extracting factors, you must first call either compute() or analyzePattern()/factorize()"); + if (m_extractedDataAreDirty) + { + int upper; + int fsupc, istart, nsupr; + int lastl = 0, lastu = 0; + SCformat *Lstore = static_cast(m_sluL.Store); + NCformat *Ustore = static_cast(m_sluU.Store); + Scalar *SNptr; + + const Index size = m_matrix.rows(); + m_l.resize(size,size); + m_l.resizeNonZeros(Lstore->nnz); + m_u.resize(size,size); + m_u.resizeNonZeros(Ustore->nnz); + + int* Lcol = m_l.outerIndexPtr(); + int* Lrow = m_l.innerIndexPtr(); + Scalar* Lval = m_l.valuePtr(); + + int* Ucol = m_u.outerIndexPtr(); + int* Urow = m_u.innerIndexPtr(); + Scalar* Uval = m_u.valuePtr(); + + Ucol[0] = 0; + Ucol[0] = 0; + + /* for each supernode */ + for (int k = 0; k <= Lstore->nsuper; ++k) + { + fsupc = L_FST_SUPC(k); + istart = L_SUB_START(fsupc); + nsupr = L_SUB_START(fsupc+1) - istart; + upper = 1; + + /* for each column in the supernode */ + for (int j = fsupc; j < L_FST_SUPC(k+1); ++j) + { + SNptr = &((Scalar*)Lstore->nzval)[L_NZ_START(j)]; + + /* Extract U */ + for (int i = U_NZ_START(j); i < U_NZ_START(j+1); ++i) + { + Uval[lastu] = ((Scalar*)Ustore->nzval)[i]; + /* Matlab doesn't like explicit zero. */ + if (Uval[lastu] != 0.0) + Urow[lastu++] = U_SUB(i); + } + for (int i = 0; i < upper; ++i) + { + /* upper triangle in the supernode */ + Uval[lastu] = SNptr[i]; + /* Matlab doesn't like explicit zero. */ + if (Uval[lastu] != 0.0) + Urow[lastu++] = L_SUB(istart+i); + } + Ucol[j+1] = lastu; + + /* Extract L */ + Lval[lastl] = 1.0; /* unit diagonal */ + Lrow[lastl++] = L_SUB(istart + upper - 1); + for (int i = upper; i < nsupr; ++i) + { + Lval[lastl] = SNptr[i]; + /* Matlab doesn't like explicit zero. */ + if (Lval[lastl] != 0.0) + Lrow[lastl++] = L_SUB(istart+i); + } + Lcol[j+1] = lastl; + + ++upper; + } /* for j ... */ + + } /* for k ... */ + + // squeeze the matrices : + m_l.resizeNonZeros(lastl); + m_u.resizeNonZeros(lastu); + + m_extractedDataAreDirty = false; + } +} + +template +typename SuperLU::Scalar SuperLU::determinant() const +{ + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for computing the determinant, you must first call either compute() or analyzePattern()/factorize()"); + + if (m_extractedDataAreDirty) + this->extractData(); + + Scalar det = Scalar(1); + for (int j=0; j 0) + { + int lastId = m_u.outerIndexPtr()[j+1]-1; + eigen_assert(m_u.innerIndexPtr()[lastId]<=j); + if (m_u.innerIndexPtr()[lastId]==j) + det *= m_u.valuePtr()[lastId]; + } + } + if(PermutationMap(m_p.data(),m_p.size()).determinant()*PermutationMap(m_q.data(),m_q.size()).determinant()<0) + det = -det; + if(m_sluEqued!='N') + return det/m_sluRscale.prod()/m_sluCscale.prod(); + else + return det; +} + +#ifdef EIGEN_PARSED_BY_DOXYGEN +#define EIGEN_SUPERLU_HAS_ILU +#endif + +#ifdef EIGEN_SUPERLU_HAS_ILU + +/** \ingroup SuperLUSupport_Module + * \class SuperILU + * \brief A sparse direct \b incomplete LU factorization and solver based on the SuperLU library + * + * This class allows to solve for an approximate solution of A.X = B sparse linear problems via an incomplete LU factorization + * using the SuperLU library. This class is aimed to be used as a preconditioner of the iterative linear solvers. + * + * \warning This class is only for the 4.x versions of SuperLU. The 3.x and 5.x versions are not supported. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class IncompleteLUT, class ConjugateGradient, class BiCGSTAB + */ + +template +class SuperILU : public SuperLUBase<_MatrixType,SuperILU<_MatrixType> > +{ + public: + typedef SuperLUBase<_MatrixType,SuperILU> Base; + typedef _MatrixType MatrixType; + typedef typename Base::Scalar Scalar; + typedef typename Base::RealScalar RealScalar; + + public: + using Base::_solve_impl; + + SuperILU() : Base() { init(); } + + SuperILU(const MatrixType& matrix) : Base() + { + init(); + Base::compute(matrix); + } + + ~SuperILU() + { + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + void analyzePattern(const MatrixType& matrix) + { + Base::analyzePattern(matrix); + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed. + * + * \sa analyzePattern() + */ + void factorize(const MatrixType& matrix); + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal */ + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const; + #endif // EIGEN_PARSED_BY_DOXYGEN + + protected: + + using Base::m_matrix; + using Base::m_sluOptions; + using Base::m_sluA; + using Base::m_sluB; + using Base::m_sluX; + using Base::m_p; + using Base::m_q; + using Base::m_sluEtree; + using Base::m_sluEqued; + using Base::m_sluRscale; + using Base::m_sluCscale; + using Base::m_sluL; + using Base::m_sluU; + using Base::m_sluStat; + using Base::m_sluFerr; + using Base::m_sluBerr; + using Base::m_l; + using Base::m_u; + + using Base::m_analysisIsOk; + using Base::m_factorizationIsOk; + using Base::m_extractedDataAreDirty; + using Base::m_isInitialized; + using Base::m_info; + + void init() + { + Base::init(); + + ilu_set_default_options(&m_sluOptions); + m_sluOptions.PrintStat = NO; + m_sluOptions.ConditionNumber = NO; + m_sluOptions.Trans = NOTRANS; + m_sluOptions.ColPerm = MMD_AT_PLUS_A; + + // no attempt to preserve column sum + m_sluOptions.ILU_MILU = SILU; + // only basic ILU(k) support -- no direct control over memory consumption + // better to use ILU_DropRule = DROP_BASIC | DROP_AREA + // and set ILU_FillFactor to max memory growth + m_sluOptions.ILU_DropRule = DROP_BASIC; + m_sluOptions.ILU_DropTol = NumTraits::dummy_precision()*10; + } + + private: + SuperILU(SuperILU& ) { } +}; + +template +void SuperILU::factorize(const MatrixType& a) +{ + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + if(!m_analysisIsOk) + { + m_info = InvalidInput; + return; + } + + this->initFactorization(a); + + int info = 0; + RealScalar recip_pivot_growth, rcond; + + StatInit(&m_sluStat); + SuperLU_gsisx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0], + &m_sluEqued, &m_sluRscale[0], &m_sluCscale[0], + &m_sluL, &m_sluU, + NULL, 0, + &m_sluB, &m_sluX, + &recip_pivot_growth, &rcond, + &m_sluStat, &info, Scalar()); + StatFree(&m_sluStat); + + // FIXME how to better check for errors ??? + m_info = info == 0 ? Success : NumericalIssue; + m_factorizationIsOk = true; +} + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +template +void SuperILU::_solve_impl(const MatrixBase &b, MatrixBase& x) const +{ + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or analyzePattern()/factorize()"); + + const int rhsCols = b.cols(); + eigen_assert(m_matrix.rows()==b.rows()); + + m_sluOptions.Trans = NOTRANS; + m_sluOptions.Fact = FACTORED; + m_sluOptions.IterRefine = NOREFINE; + + m_sluFerr.resize(rhsCols); + m_sluBerr.resize(rhsCols); + + Ref > b_ref(b); + Ref > x_ref(x); + + m_sluB = SluMatrix::Map(b_ref.const_cast_derived()); + m_sluX = SluMatrix::Map(x_ref.const_cast_derived()); + + typename Rhs::PlainObject b_cpy; + if(m_sluEqued!='N') + { + b_cpy = b; + m_sluB = SluMatrix::Map(b_cpy.const_cast_derived()); + } + + int info = 0; + RealScalar recip_pivot_growth, rcond; + + StatInit(&m_sluStat); + SuperLU_gsisx(&m_sluOptions, &m_sluA, + m_q.data(), m_p.data(), + &m_sluEtree[0], &m_sluEqued, + &m_sluRscale[0], &m_sluCscale[0], + &m_sluL, &m_sluU, + NULL, 0, + &m_sluB, &m_sluX, + &recip_pivot_growth, &rcond, + &m_sluStat, &info, Scalar()); + StatFree(&m_sluStat); + + if(x.derived().data() != x_ref.data()) + x = x_ref; + + m_info = info==0 ? Success : NumericalIssue; +} +#endif + +#endif + +} // end namespace Eigen + +#endif // EIGEN_SUPERLUSUPPORT_H diff --git a/vendor/eigen/include/eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h b/vendor/eigen/include/eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..e3a333f80f0511e861591c7a5e92da95ffa2142c --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/UmfPackSupport/UmfPackSupport.h @@ -0,0 +1,642 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2011 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_UMFPACKSUPPORT_H +#define EIGEN_UMFPACKSUPPORT_H + +// for compatibility with super old version of umfpack, +// not sure this is really needed, but this is harmless. +#ifndef SuiteSparse_long +#ifdef UF_long +#define SuiteSparse_long UF_long +#else +#error neither SuiteSparse_long nor UF_long are defined +#endif +#endif + +namespace Eigen { + +/* TODO extract L, extract U, compute det, etc... */ + +// generic double/complex wrapper functions: + + + // Defaults +inline void umfpack_defaults(double control[UMFPACK_CONTROL], double, int) +{ umfpack_di_defaults(control); } + +inline void umfpack_defaults(double control[UMFPACK_CONTROL], std::complex, int) +{ umfpack_zi_defaults(control); } + +inline void umfpack_defaults(double control[UMFPACK_CONTROL], double, SuiteSparse_long) +{ umfpack_dl_defaults(control); } + +inline void umfpack_defaults(double control[UMFPACK_CONTROL], std::complex, SuiteSparse_long) +{ umfpack_zl_defaults(control); } + +// Report info +inline void umfpack_report_info(double control[UMFPACK_CONTROL], double info[UMFPACK_INFO], double, int) +{ umfpack_di_report_info(control, info);} + +inline void umfpack_report_info(double control[UMFPACK_CONTROL], double info[UMFPACK_INFO], std::complex, int) +{ umfpack_zi_report_info(control, info);} + +inline void umfpack_report_info(double control[UMFPACK_CONTROL], double info[UMFPACK_INFO], double, SuiteSparse_long) +{ umfpack_dl_report_info(control, info);} + +inline void umfpack_report_info(double control[UMFPACK_CONTROL], double info[UMFPACK_INFO], std::complex, SuiteSparse_long) +{ umfpack_zl_report_info(control, info);} + +// Report status +inline void umfpack_report_status(double control[UMFPACK_CONTROL], int status, double, int) +{ umfpack_di_report_status(control, status);} + +inline void umfpack_report_status(double control[UMFPACK_CONTROL], int status, std::complex, int) +{ umfpack_zi_report_status(control, status);} + +inline void umfpack_report_status(double control[UMFPACK_CONTROL], int status, double, SuiteSparse_long) +{ umfpack_dl_report_status(control, status);} + +inline void umfpack_report_status(double control[UMFPACK_CONTROL], int status, std::complex, SuiteSparse_long) +{ umfpack_zl_report_status(control, status);} + +// report control +inline void umfpack_report_control(double control[UMFPACK_CONTROL], double, int) +{ umfpack_di_report_control(control);} + +inline void umfpack_report_control(double control[UMFPACK_CONTROL], std::complex, int) +{ umfpack_zi_report_control(control);} + +inline void umfpack_report_control(double control[UMFPACK_CONTROL], double, SuiteSparse_long) +{ umfpack_dl_report_control(control);} + +inline void umfpack_report_control(double control[UMFPACK_CONTROL], std::complex, SuiteSparse_long) +{ umfpack_zl_report_control(control);} + +// Free numeric +inline void umfpack_free_numeric(void **Numeric, double, int) +{ umfpack_di_free_numeric(Numeric); *Numeric = 0; } + +inline void umfpack_free_numeric(void **Numeric, std::complex, int) +{ umfpack_zi_free_numeric(Numeric); *Numeric = 0; } + +inline void umfpack_free_numeric(void **Numeric, double, SuiteSparse_long) +{ umfpack_dl_free_numeric(Numeric); *Numeric = 0; } + +inline void umfpack_free_numeric(void **Numeric, std::complex, SuiteSparse_long) +{ umfpack_zl_free_numeric(Numeric); *Numeric = 0; } + +// Free symbolic +inline void umfpack_free_symbolic(void **Symbolic, double, int) +{ umfpack_di_free_symbolic(Symbolic); *Symbolic = 0; } + +inline void umfpack_free_symbolic(void **Symbolic, std::complex, int) +{ umfpack_zi_free_symbolic(Symbolic); *Symbolic = 0; } + +inline void umfpack_free_symbolic(void **Symbolic, double, SuiteSparse_long) +{ umfpack_dl_free_symbolic(Symbolic); *Symbolic = 0; } + +inline void umfpack_free_symbolic(void **Symbolic, std::complex, SuiteSparse_long) +{ umfpack_zl_free_symbolic(Symbolic); *Symbolic = 0; } + +// Symbolic +inline int umfpack_symbolic(int n_row,int n_col, + const int Ap[], const int Ai[], const double Ax[], void **Symbolic, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]) +{ + return umfpack_di_symbolic(n_row,n_col,Ap,Ai,Ax,Symbolic,Control,Info); +} + +inline int umfpack_symbolic(int n_row,int n_col, + const int Ap[], const int Ai[], const std::complex Ax[], void **Symbolic, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]) +{ + return umfpack_zi_symbolic(n_row,n_col,Ap,Ai,&numext::real_ref(Ax[0]),0,Symbolic,Control,Info); +} +inline SuiteSparse_long umfpack_symbolic( SuiteSparse_long n_row,SuiteSparse_long n_col, + const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const double Ax[], void **Symbolic, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]) +{ + return umfpack_dl_symbolic(n_row,n_col,Ap,Ai,Ax,Symbolic,Control,Info); +} + +inline SuiteSparse_long umfpack_symbolic( SuiteSparse_long n_row,SuiteSparse_long n_col, + const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const std::complex Ax[], void **Symbolic, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]) +{ + return umfpack_zl_symbolic(n_row,n_col,Ap,Ai,&numext::real_ref(Ax[0]),0,Symbolic,Control,Info); +} + +// Numeric +inline int umfpack_numeric( const int Ap[], const int Ai[], const double Ax[], + void *Symbolic, void **Numeric, + const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO]) +{ + return umfpack_di_numeric(Ap,Ai,Ax,Symbolic,Numeric,Control,Info); +} + +inline int umfpack_numeric( const int Ap[], const int Ai[], const std::complex Ax[], + void *Symbolic, void **Numeric, + const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO]) +{ + return umfpack_zi_numeric(Ap,Ai,&numext::real_ref(Ax[0]),0,Symbolic,Numeric,Control,Info); +} +inline SuiteSparse_long umfpack_numeric(const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const double Ax[], + void *Symbolic, void **Numeric, + const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO]) +{ + return umfpack_dl_numeric(Ap,Ai,Ax,Symbolic,Numeric,Control,Info); +} + +inline SuiteSparse_long umfpack_numeric(const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const std::complex Ax[], + void *Symbolic, void **Numeric, + const double Control[UMFPACK_CONTROL],double Info [UMFPACK_INFO]) +{ + return umfpack_zl_numeric(Ap,Ai,&numext::real_ref(Ax[0]),0,Symbolic,Numeric,Control,Info); +} + +// solve +inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const double Ax[], + double X[], const double B[], void *Numeric, + const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO]) +{ + return umfpack_di_solve(sys,Ap,Ai,Ax,X,B,Numeric,Control,Info); +} + +inline int umfpack_solve( int sys, const int Ap[], const int Ai[], const std::complex Ax[], + std::complex X[], const std::complex B[], void *Numeric, + const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO]) +{ + return umfpack_zi_solve(sys,Ap,Ai,&numext::real_ref(Ax[0]),0,&numext::real_ref(X[0]),0,&numext::real_ref(B[0]),0,Numeric,Control,Info); +} + +inline SuiteSparse_long umfpack_solve(int sys, const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const double Ax[], + double X[], const double B[], void *Numeric, + const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO]) +{ + return umfpack_dl_solve(sys,Ap,Ai,Ax,X,B,Numeric,Control,Info); +} + +inline SuiteSparse_long umfpack_solve(int sys, const SuiteSparse_long Ap[], const SuiteSparse_long Ai[], const std::complex Ax[], + std::complex X[], const std::complex B[], void *Numeric, + const double Control[UMFPACK_CONTROL], double Info[UMFPACK_INFO]) +{ + return umfpack_zl_solve(sys,Ap,Ai,&numext::real_ref(Ax[0]),0,&numext::real_ref(X[0]),0,&numext::real_ref(B[0]),0,Numeric,Control,Info); +} + +// Get Lunz +inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, double) +{ + return umfpack_di_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric); +} + +inline int umfpack_get_lunz(int *lnz, int *unz, int *n_row, int *n_col, int *nz_udiag, void *Numeric, std::complex) +{ + return umfpack_zi_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric); +} + +inline SuiteSparse_long umfpack_get_lunz( SuiteSparse_long *lnz, SuiteSparse_long *unz, SuiteSparse_long *n_row, SuiteSparse_long *n_col, + SuiteSparse_long *nz_udiag, void *Numeric, double) +{ + return umfpack_dl_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric); +} + +inline SuiteSparse_long umfpack_get_lunz( SuiteSparse_long *lnz, SuiteSparse_long *unz, SuiteSparse_long *n_row, SuiteSparse_long *n_col, + SuiteSparse_long *nz_udiag, void *Numeric, std::complex) +{ + return umfpack_zl_get_lunz(lnz,unz,n_row,n_col,nz_udiag,Numeric); +} + +// Get Numeric +inline int umfpack_get_numeric(int Lp[], int Lj[], double Lx[], int Up[], int Ui[], double Ux[], + int P[], int Q[], double Dx[], int *do_recip, double Rs[], void *Numeric) +{ + return umfpack_di_get_numeric(Lp,Lj,Lx,Up,Ui,Ux,P,Q,Dx,do_recip,Rs,Numeric); +} + +inline int umfpack_get_numeric(int Lp[], int Lj[], std::complex Lx[], int Up[], int Ui[], std::complex Ux[], + int P[], int Q[], std::complex Dx[], int *do_recip, double Rs[], void *Numeric) +{ + double& lx0_real = numext::real_ref(Lx[0]); + double& ux0_real = numext::real_ref(Ux[0]); + double& dx0_real = numext::real_ref(Dx[0]); + return umfpack_zi_get_numeric(Lp,Lj,Lx?&lx0_real:0,0,Up,Ui,Ux?&ux0_real:0,0,P,Q, + Dx?&dx0_real:0,0,do_recip,Rs,Numeric); +} +inline SuiteSparse_long umfpack_get_numeric(SuiteSparse_long Lp[], SuiteSparse_long Lj[], double Lx[], SuiteSparse_long Up[], SuiteSparse_long Ui[], double Ux[], + SuiteSparse_long P[], SuiteSparse_long Q[], double Dx[], SuiteSparse_long *do_recip, double Rs[], void *Numeric) +{ + return umfpack_dl_get_numeric(Lp,Lj,Lx,Up,Ui,Ux,P,Q,Dx,do_recip,Rs,Numeric); +} + +inline SuiteSparse_long umfpack_get_numeric(SuiteSparse_long Lp[], SuiteSparse_long Lj[], std::complex Lx[], SuiteSparse_long Up[], SuiteSparse_long Ui[], std::complex Ux[], + SuiteSparse_long P[], SuiteSparse_long Q[], std::complex Dx[], SuiteSparse_long *do_recip, double Rs[], void *Numeric) +{ + double& lx0_real = numext::real_ref(Lx[0]); + double& ux0_real = numext::real_ref(Ux[0]); + double& dx0_real = numext::real_ref(Dx[0]); + return umfpack_zl_get_numeric(Lp,Lj,Lx?&lx0_real:0,0,Up,Ui,Ux?&ux0_real:0,0,P,Q, + Dx?&dx0_real:0,0,do_recip,Rs,Numeric); +} + +// Get Determinant +inline int umfpack_get_determinant(double *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO], int) +{ + return umfpack_di_get_determinant(Mx,Ex,NumericHandle,User_Info); +} + +inline int umfpack_get_determinant(std::complex *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO], int) +{ + double& mx_real = numext::real_ref(*Mx); + return umfpack_zi_get_determinant(&mx_real,0,Ex,NumericHandle,User_Info); +} + +inline SuiteSparse_long umfpack_get_determinant(double *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO], SuiteSparse_long) +{ + return umfpack_dl_get_determinant(Mx,Ex,NumericHandle,User_Info); +} + +inline SuiteSparse_long umfpack_get_determinant(std::complex *Mx, double *Ex, void *NumericHandle, double User_Info [UMFPACK_INFO], SuiteSparse_long) +{ + double& mx_real = numext::real_ref(*Mx); + return umfpack_zl_get_determinant(&mx_real,0,Ex,NumericHandle,User_Info); +} + + +/** \ingroup UmfPackSupport_Module + * \brief A sparse LU factorization and solver based on UmfPack + * + * This class allows to solve for A.X = B sparse linear problems via a LU factorization + * using the UmfPack library. The sparse matrix A must be squared and full rank. + * The vectors or matrices X and B can be either dense or sparse. + * + * \warning The input matrix A should be in a \b compressed and \b column-major form. + * Otherwise an expensive copy will be made. You can call the inexpensive makeCompressed() to get a compressed matrix. + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * + * \implsparsesolverconcept + * + * \sa \ref TutorialSparseSolverConcept, class SparseLU + */ +template +class UmfPackLU : public SparseSolverBase > +{ + protected: + typedef SparseSolverBase > Base; + using Base::m_isInitialized; + public: + using Base::_solve_impl; + typedef _MatrixType MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef Matrix Vector; + typedef Matrix IntRowVectorType; + typedef Matrix IntColVectorType; + typedef SparseMatrix LUMatrixType; + typedef SparseMatrix UmfpackMatrixType; + typedef Ref UmfpackMatrixRef; + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + typedef Array UmfpackControl; + typedef Array UmfpackInfo; + + UmfPackLU() + : m_dummy(0,0), mp_matrix(m_dummy) + { + init(); + } + + template + explicit UmfPackLU(const InputMatrixType& matrix) + : mp_matrix(matrix) + { + init(); + compute(matrix); + } + + ~UmfPackLU() + { + if(m_symbolic) umfpack_free_symbolic(&m_symbolic,Scalar(), StorageIndex()); + if(m_numeric) umfpack_free_numeric(&m_numeric,Scalar(), StorageIndex()); + } + + inline Index rows() const { return mp_matrix.rows(); } + inline Index cols() const { return mp_matrix.cols(); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + inline const LUMatrixType& matrixL() const + { + if (m_extractedDataAreDirty) extractData(); + return m_l; + } + + inline const LUMatrixType& matrixU() const + { + if (m_extractedDataAreDirty) extractData(); + return m_u; + } + + inline const IntColVectorType& permutationP() const + { + if (m_extractedDataAreDirty) extractData(); + return m_p; + } + + inline const IntRowVectorType& permutationQ() const + { + if (m_extractedDataAreDirty) extractData(); + return m_q; + } + + /** Computes the sparse Cholesky decomposition of \a matrix + * Note that the matrix should be column-major, and in compressed format for best performance. + * \sa SparseMatrix::makeCompressed(). + */ + template + void compute(const InputMatrixType& matrix) + { + if(m_symbolic) umfpack_free_symbolic(&m_symbolic,Scalar(),StorageIndex()); + if(m_numeric) umfpack_free_numeric(&m_numeric,Scalar(),StorageIndex()); + grab(matrix.derived()); + analyzePattern_impl(); + factorize_impl(); + } + + /** Performs a symbolic decomposition on the sparcity of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize(), compute() + */ + template + void analyzePattern(const InputMatrixType& matrix) + { + if(m_symbolic) umfpack_free_symbolic(&m_symbolic,Scalar(),StorageIndex()); + if(m_numeric) umfpack_free_numeric(&m_numeric,Scalar(),StorageIndex()); + + grab(matrix.derived()); + + analyzePattern_impl(); + } + + /** Provides the return status code returned by UmfPack during the numeric + * factorization. + * + * \sa factorize(), compute() + */ + inline int umfpackFactorizeReturncode() const + { + eigen_assert(m_numeric && "UmfPackLU: you must first call factorize()"); + return m_fact_errorCode; + } + + /** Provides access to the control settings array used by UmfPack. + * + * If this array contains NaN's, the default values are used. + * + * See UMFPACK documentation for details. + */ + inline const UmfpackControl& umfpackControl() const + { + return m_control; + } + + /** Provides access to the control settings array used by UmfPack. + * + * If this array contains NaN's, the default values are used. + * + * See UMFPACK documentation for details. + */ + inline UmfpackControl& umfpackControl() + { + return m_control; + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must has the same sparcity than the matrix on which the pattern anylysis has been performed. + * + * \sa analyzePattern(), compute() + */ + template + void factorize(const InputMatrixType& matrix) + { + eigen_assert(m_analysisIsOk && "UmfPackLU: you must first call analyzePattern()"); + if(m_numeric) + umfpack_free_numeric(&m_numeric,Scalar(),StorageIndex()); + + grab(matrix.derived()); + + factorize_impl(); + } + + /** Prints the current UmfPack control settings. + * + * \sa umfpackControl() + */ + void printUmfpackControl() + { + umfpack_report_control(m_control.data(), Scalar(),StorageIndex()); + } + + /** Prints statistics collected by UmfPack. + * + * \sa analyzePattern(), compute() + */ + void printUmfpackInfo() + { + eigen_assert(m_analysisIsOk && "UmfPackLU: you must first call analyzePattern()"); + umfpack_report_info(m_control.data(), m_umfpackInfo.data(), Scalar(),StorageIndex()); + } + + /** Prints the status of the previous factorization operation performed by UmfPack (symbolic or numerical factorization). + * + * \sa analyzePattern(), compute() + */ + void printUmfpackStatus() { + eigen_assert(m_analysisIsOk && "UmfPackLU: you must first call analyzePattern()"); + umfpack_report_status(m_control.data(), m_fact_errorCode, Scalar(),StorageIndex()); + } + + /** \internal */ + template + bool _solve_impl(const MatrixBase &b, MatrixBase &x) const; + + Scalar determinant() const; + + void extractData() const; + + protected: + + void init() + { + m_info = InvalidInput; + m_isInitialized = false; + m_numeric = 0; + m_symbolic = 0; + m_extractedDataAreDirty = true; + + umfpack_defaults(m_control.data(), Scalar(),StorageIndex()); + } + + void analyzePattern_impl() + { + m_fact_errorCode = umfpack_symbolic(internal::convert_index(mp_matrix.rows()), + internal::convert_index(mp_matrix.cols()), + mp_matrix.outerIndexPtr(), mp_matrix.innerIndexPtr(), mp_matrix.valuePtr(), + &m_symbolic, m_control.data(), m_umfpackInfo.data()); + + m_isInitialized = true; + m_info = m_fact_errorCode ? InvalidInput : Success; + m_analysisIsOk = true; + m_factorizationIsOk = false; + m_extractedDataAreDirty = true; + } + + void factorize_impl() + { + + m_fact_errorCode = umfpack_numeric(mp_matrix.outerIndexPtr(), mp_matrix.innerIndexPtr(), mp_matrix.valuePtr(), + m_symbolic, &m_numeric, m_control.data(), m_umfpackInfo.data()); + + m_info = m_fact_errorCode == UMFPACK_OK ? Success : NumericalIssue; + m_factorizationIsOk = true; + m_extractedDataAreDirty = true; + } + + template + void grab(const EigenBase &A) + { + mp_matrix.~UmfpackMatrixRef(); + ::new (&mp_matrix) UmfpackMatrixRef(A.derived()); + } + + void grab(const UmfpackMatrixRef &A) + { + if(&(A.derived()) != &mp_matrix) + { + mp_matrix.~UmfpackMatrixRef(); + ::new (&mp_matrix) UmfpackMatrixRef(A); + } + } + + // cached data to reduce reallocation, etc. + mutable LUMatrixType m_l; + StorageIndex m_fact_errorCode; + UmfpackControl m_control; + mutable UmfpackInfo m_umfpackInfo; + + mutable LUMatrixType m_u; + mutable IntColVectorType m_p; + mutable IntRowVectorType m_q; + + UmfpackMatrixType m_dummy; + UmfpackMatrixRef mp_matrix; + + void* m_numeric; + void* m_symbolic; + + mutable ComputationInfo m_info; + int m_factorizationIsOk; + int m_analysisIsOk; + mutable bool m_extractedDataAreDirty; + + private: + UmfPackLU(const UmfPackLU& ) { } +}; + + +template +void UmfPackLU::extractData() const +{ + if (m_extractedDataAreDirty) + { + // get size of the data + StorageIndex lnz, unz, rows, cols, nz_udiag; + umfpack_get_lunz(&lnz, &unz, &rows, &cols, &nz_udiag, m_numeric, Scalar()); + + // allocate data + m_l.resize(rows,(std::min)(rows,cols)); + m_l.resizeNonZeros(lnz); + + m_u.resize((std::min)(rows,cols),cols); + m_u.resizeNonZeros(unz); + + m_p.resize(rows); + m_q.resize(cols); + + // extract + umfpack_get_numeric(m_l.outerIndexPtr(), m_l.innerIndexPtr(), m_l.valuePtr(), + m_u.outerIndexPtr(), m_u.innerIndexPtr(), m_u.valuePtr(), + m_p.data(), m_q.data(), 0, 0, 0, m_numeric); + + m_extractedDataAreDirty = false; + } +} + +template +typename UmfPackLU::Scalar UmfPackLU::determinant() const +{ + Scalar det; + umfpack_get_determinant(&det, 0, m_numeric, 0, StorageIndex()); + return det; +} + +template +template +bool UmfPackLU::_solve_impl(const MatrixBase &b, MatrixBase &x) const +{ + Index rhsCols = b.cols(); + eigen_assert((BDerived::Flags&RowMajorBit)==0 && "UmfPackLU backend does not support non col-major rhs yet"); + eigen_assert((XDerived::Flags&RowMajorBit)==0 && "UmfPackLU backend does not support non col-major result yet"); + eigen_assert(b.derived().data() != x.derived().data() && " Umfpack does not support inplace solve"); + + Scalar* x_ptr = 0; + Matrix x_tmp; + if(x.innerStride()!=1) + { + x_tmp.resize(x.rows()); + x_ptr = x_tmp.data(); + } + for (int j=0; j +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const EIGEN_CWISE_BINARY_RETURN_TYPE(Derived,OtherDerived,product) +operator*(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return EIGEN_CWISE_BINARY_RETURN_TYPE(Derived,OtherDerived,product)(derived(), other.derived()); +} + +/** \returns an expression of the coefficient wise quotient of \c *this and \a other + * + * \sa MatrixBase::cwiseQuotient + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const OtherDerived> +operator/(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise min of \c *this and \a other + * + * Example: \include Cwise_min.cpp + * Output: \verbinclude Cwise_min.out + * + * \sa max() + */ +EIGEN_MAKE_CWISE_BINARY_OP(min,min) + +/** \returns an expression of the coefficient-wise min of \c *this and scalar \a other + * + * \sa max() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, + const CwiseNullaryOp, PlainObject> > +#ifdef EIGEN_PARSED_BY_DOXYGEN +min +#else +(min) +#endif +(const Scalar &other) const +{ + return (min)(Derived::PlainObject::Constant(rows(), cols(), other)); +} + +/** \returns an expression of the coefficient-wise max of \c *this and \a other + * + * Example: \include Cwise_max.cpp + * Output: \verbinclude Cwise_max.out + * + * \sa min() + */ +EIGEN_MAKE_CWISE_BINARY_OP(max,max) + +/** \returns an expression of the coefficient-wise max of \c *this and scalar \a other + * + * \sa min() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, + const CwiseNullaryOp, PlainObject> > +#ifdef EIGEN_PARSED_BY_DOXYGEN +max +#else +(max) +#endif +(const Scalar &other) const +{ + return (max)(Derived::PlainObject::Constant(rows(), cols(), other)); +} + +/** \returns an expression of the coefficient-wise absdiff of \c *this and \a other + * + * Example: \include Cwise_absolute_difference.cpp + * Output: \verbinclude Cwise_absolute_difference.out + * + * \sa absolute_difference() + */ +EIGEN_MAKE_CWISE_BINARY_OP(absolute_difference,absolute_difference) + +/** \returns an expression of the coefficient-wise absolute_difference of \c *this and scalar \a other + * + * \sa absolute_difference() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, + const CwiseNullaryOp, PlainObject> > +#ifdef EIGEN_PARSED_BY_DOXYGEN +absolute_difference +#else +(absolute_difference) +#endif +(const Scalar &other) const +{ + return (absolute_difference)(Derived::PlainObject::Constant(rows(), cols(), other)); +} + +/** \returns an expression of the coefficient-wise power of \c *this to the given array of \a exponents. + * + * This function computes the coefficient-wise power. + * + * Example: \include Cwise_array_power_array.cpp + * Output: \verbinclude Cwise_array_power_array.out + */ +EIGEN_MAKE_CWISE_BINARY_OP(pow,pow) + +#ifndef EIGEN_PARSED_BY_DOXYGEN +EIGEN_MAKE_SCALAR_BINARY_OP_ONTHERIGHT(pow,pow) +#else +/** \returns an expression of the coefficients of \c *this rasied to the constant power \a exponent + * + * \tparam T is the scalar type of \a exponent. It must be compatible with the scalar type of the given expression. + * + * This function computes the coefficient-wise power. The function MatrixBase::pow() in the + * unsupported module MatrixFunctions computes the matrix power. + * + * Example: \include Cwise_pow.cpp + * Output: \verbinclude Cwise_pow.out + * + * \sa ArrayBase::pow(ArrayBase), square(), cube(), exp(), log() + */ +template +const CwiseBinaryOp,Derived,Constant > pow(const T& exponent) const; +#endif + + +// TODO code generating macros could be moved to Macros.h and could include generation of documentation +#define EIGEN_MAKE_CWISE_COMP_OP(OP, COMPARATOR) \ +template \ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const OtherDerived> \ +OP(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const \ +{ \ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); \ +}\ +typedef CwiseBinaryOp, const Derived, const CwiseNullaryOp, PlainObject> > Cmp ## COMPARATOR ## ReturnType; \ +typedef CwiseBinaryOp, const CwiseNullaryOp, PlainObject>, const Derived > RCmp ## COMPARATOR ## ReturnType; \ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Cmp ## COMPARATOR ## ReturnType \ +OP(const Scalar& s) const { \ + return this->OP(Derived::PlainObject::Constant(rows(), cols(), s)); \ +} \ +EIGEN_DEVICE_FUNC friend EIGEN_STRONG_INLINE const RCmp ## COMPARATOR ## ReturnType \ +OP(const Scalar& s, const EIGEN_CURRENT_STORAGE_BASE_CLASS& d) { \ + return Derived::PlainObject::Constant(d.rows(), d.cols(), s).OP(d); \ +} + +#define EIGEN_MAKE_CWISE_COMP_R_OP(OP, R_OP, RCOMPARATOR) \ +template \ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CwiseBinaryOp, const OtherDerived, const Derived> \ +OP(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const \ +{ \ + return CwiseBinaryOp, const OtherDerived, const Derived>(other.derived(), derived()); \ +} \ +EIGEN_DEVICE_FUNC \ +inline const RCmp ## RCOMPARATOR ## ReturnType \ +OP(const Scalar& s) const { \ + return Derived::PlainObject::Constant(rows(), cols(), s).R_OP(*this); \ +} \ +friend inline const Cmp ## RCOMPARATOR ## ReturnType \ +OP(const Scalar& s, const Derived& d) { \ + return d.R_OP(Derived::PlainObject::Constant(d.rows(), d.cols(), s)); \ +} + + + +/** \returns an expression of the coefficient-wise \< operator of *this and \a other + * + * Example: \include Cwise_less.cpp + * Output: \verbinclude Cwise_less.out + * + * \sa all(), any(), operator>(), operator<=() + */ +EIGEN_MAKE_CWISE_COMP_OP(operator<, LT) + +/** \returns an expression of the coefficient-wise \<= operator of *this and \a other + * + * Example: \include Cwise_less_equal.cpp + * Output: \verbinclude Cwise_less_equal.out + * + * \sa all(), any(), operator>=(), operator<() + */ +EIGEN_MAKE_CWISE_COMP_OP(operator<=, LE) + +/** \returns an expression of the coefficient-wise \> operator of *this and \a other + * + * Example: \include Cwise_greater.cpp + * Output: \verbinclude Cwise_greater.out + * + * \sa all(), any(), operator>=(), operator<() + */ +EIGEN_MAKE_CWISE_COMP_R_OP(operator>, operator<, LT) + +/** \returns an expression of the coefficient-wise \>= operator of *this and \a other + * + * Example: \include Cwise_greater_equal.cpp + * Output: \verbinclude Cwise_greater_equal.out + * + * \sa all(), any(), operator>(), operator<=() + */ +EIGEN_MAKE_CWISE_COMP_R_OP(operator>=, operator<=, LE) + +/** \returns an expression of the coefficient-wise == operator of *this and \a other + * + * \warning this performs an exact comparison, which is generally a bad idea with floating-point types. + * In order to check for equality between two vectors or matrices with floating-point coefficients, it is + * generally a far better idea to use a fuzzy comparison as provided by isApprox() and + * isMuchSmallerThan(). + * + * Example: \include Cwise_equal_equal.cpp + * Output: \verbinclude Cwise_equal_equal.out + * + * \sa all(), any(), isApprox(), isMuchSmallerThan() + */ +EIGEN_MAKE_CWISE_COMP_OP(operator==, EQ) + +/** \returns an expression of the coefficient-wise != operator of *this and \a other + * + * \warning this performs an exact comparison, which is generally a bad idea with floating-point types. + * In order to check for equality between two vectors or matrices with floating-point coefficients, it is + * generally a far better idea to use a fuzzy comparison as provided by isApprox() and + * isMuchSmallerThan(). + * + * Example: \include Cwise_not_equal.cpp + * Output: \verbinclude Cwise_not_equal.out + * + * \sa all(), any(), isApprox(), isMuchSmallerThan() + */ +EIGEN_MAKE_CWISE_COMP_OP(operator!=, NEQ) + + +#undef EIGEN_MAKE_CWISE_COMP_OP +#undef EIGEN_MAKE_CWISE_COMP_R_OP + +// scalar addition +#ifndef EIGEN_PARSED_BY_DOXYGEN +EIGEN_MAKE_SCALAR_BINARY_OP(operator+,sum) +#else +/** \returns an expression of \c *this with each coeff incremented by the constant \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + * + * Example: \include Cwise_plus.cpp + * Output: \verbinclude Cwise_plus.out + * + * \sa operator+=(), operator-() + */ +template +const CwiseBinaryOp,Derived,Constant > operator+(const T& scalar) const; +/** \returns an expression of \a expr with each coeff incremented by the constant \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + */ +template friend +const CwiseBinaryOp,Constant,Derived> operator+(const T& scalar, const StorageBaseType& expr); +#endif + +#ifndef EIGEN_PARSED_BY_DOXYGEN +EIGEN_MAKE_SCALAR_BINARY_OP(operator-,difference) +#else +/** \returns an expression of \c *this with each coeff decremented by the constant \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + * + * Example: \include Cwise_minus.cpp + * Output: \verbinclude Cwise_minus.out + * + * \sa operator+=(), operator-() + */ +template +const CwiseBinaryOp,Derived,Constant > operator-(const T& scalar) const; +/** \returns an expression of the constant matrix of value \a scalar decremented by the coefficients of \a expr + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + */ +template friend +const CwiseBinaryOp,Constant,Derived> operator-(const T& scalar, const StorageBaseType& expr); +#endif + + +#ifndef EIGEN_PARSED_BY_DOXYGEN + EIGEN_MAKE_SCALAR_BINARY_OP_ONTHELEFT(operator/,quotient) +#else + /** + * \brief Component-wise division of the scalar \a s by array elements of \a a. + * + * \tparam Scalar is the scalar type of \a x. It must be compatible with the scalar type of the given array expression (\c Derived::Scalar). + */ + template friend + inline const CwiseBinaryOp,Constant,Derived> + operator/(const T& s,const StorageBaseType& a); +#endif + +/** \returns an expression of the coefficient-wise ^ operator of *this and \a other + * + * \warning this operator is for expression of bool only. + * + * Example: \include Cwise_boolean_xor.cpp + * Output: \verbinclude Cwise_boolean_xor.out + * + * \sa operator&&(), select() + */ +template +EIGEN_DEVICE_FUNC +inline const CwiseBinaryOp +operator^(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + EIGEN_STATIC_ASSERT((internal::is_same::value && internal::is_same::value), + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL); + return CwiseBinaryOp(derived(),other.derived()); +} + +// NOTE disabled until we agree on argument order +#if 0 +/** \cpp11 \returns an expression of the coefficient-wise polygamma function. + * + * \specialfunctions_module + * + * It returns the \a n -th derivative of the digamma(psi) evaluated at \c *this. + * + * \warning Be careful with the order of the parameters: x.polygamma(n) is equivalent to polygamma(n,x) + * + * \sa Eigen::polygamma() + */ +template +inline const CwiseBinaryOp, const DerivedN, const Derived> +polygamma(const EIGEN_CURRENT_STORAGE_BASE_CLASS &n) const +{ + return CwiseBinaryOp, const DerivedN, const Derived>(n.derived(), this->derived()); +} +#endif + +/** \returns an expression of the coefficient-wise zeta function. + * + * \specialfunctions_module + * + * It returns the Riemann zeta function of two arguments \c *this and \a q: + * + * \param q is the shift, it must be > 0 + * + * \note *this is the exponent, it must be > 1. + * \note This function supports only float and double scalar types. To support other scalar types, the user has + * to provide implementations of zeta(T,T) for any scalar type T to be supported. + * + * This method is an alias for zeta(*this,q); + * + * \sa Eigen::zeta() + */ +template +inline const CwiseBinaryOp, const Derived, const DerivedQ> +zeta(const EIGEN_CURRENT_STORAGE_BASE_CLASS &q) const +{ + return CwiseBinaryOp, const Derived, const DerivedQ>(this->derived(), q.derived()); +} diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..13c55f4b115880c0becb6246bdc1fb86c9f404fa --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h @@ -0,0 +1,696 @@ + + +typedef CwiseUnaryOp, const Derived> AbsReturnType; +typedef CwiseUnaryOp, const Derived> ArgReturnType; +typedef CwiseUnaryOp, const Derived> Abs2ReturnType; +typedef CwiseUnaryOp, const Derived> SqrtReturnType; +typedef CwiseUnaryOp, const Derived> RsqrtReturnType; +typedef CwiseUnaryOp, const Derived> SignReturnType; +typedef CwiseUnaryOp, const Derived> InverseReturnType; +typedef CwiseUnaryOp, const Derived> BooleanNotReturnType; + +typedef CwiseUnaryOp, const Derived> ExpReturnType; +typedef CwiseUnaryOp, const Derived> Expm1ReturnType; +typedef CwiseUnaryOp, const Derived> LogReturnType; +typedef CwiseUnaryOp, const Derived> Log1pReturnType; +typedef CwiseUnaryOp, const Derived> Log10ReturnType; +typedef CwiseUnaryOp, const Derived> Log2ReturnType; +typedef CwiseUnaryOp, const Derived> CosReturnType; +typedef CwiseUnaryOp, const Derived> SinReturnType; +typedef CwiseUnaryOp, const Derived> TanReturnType; +typedef CwiseUnaryOp, const Derived> AcosReturnType; +typedef CwiseUnaryOp, const Derived> AsinReturnType; +typedef CwiseUnaryOp, const Derived> AtanReturnType; +typedef CwiseUnaryOp, const Derived> TanhReturnType; +typedef CwiseUnaryOp, const Derived> LogisticReturnType; +typedef CwiseUnaryOp, const Derived> SinhReturnType; +#if EIGEN_HAS_CXX11_MATH +typedef CwiseUnaryOp, const Derived> AtanhReturnType; +typedef CwiseUnaryOp, const Derived> AsinhReturnType; +typedef CwiseUnaryOp, const Derived> AcoshReturnType; +#endif +typedef CwiseUnaryOp, const Derived> CoshReturnType; +typedef CwiseUnaryOp, const Derived> SquareReturnType; +typedef CwiseUnaryOp, const Derived> CubeReturnType; +typedef CwiseUnaryOp, const Derived> RoundReturnType; +typedef CwiseUnaryOp, const Derived> RintReturnType; +typedef CwiseUnaryOp, const Derived> FloorReturnType; +typedef CwiseUnaryOp, const Derived> CeilReturnType; +typedef CwiseUnaryOp, const Derived> IsNaNReturnType; +typedef CwiseUnaryOp, const Derived> IsInfReturnType; +typedef CwiseUnaryOp, const Derived> IsFiniteReturnType; + +/** \returns an expression of the coefficient-wise absolute value of \c *this + * + * Example: \include Cwise_abs.cpp + * Output: \verbinclude Cwise_abs.out + * + * \sa Math functions, abs2() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const AbsReturnType +abs() const +{ + return AbsReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise phase angle of \c *this + * + * Example: \include Cwise_arg.cpp + * Output: \verbinclude Cwise_arg.out + * + * \sa abs() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const ArgReturnType +arg() const +{ + return ArgReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise squared absolute value of \c *this + * + * Example: \include Cwise_abs2.cpp + * Output: \verbinclude Cwise_abs2.out + * + * \sa Math functions, abs(), square() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const Abs2ReturnType +abs2() const +{ + return Abs2ReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise exponential of *this. + * + * This function computes the coefficient-wise exponential. The function MatrixBase::exp() in the + * unsupported module MatrixFunctions computes the matrix exponential. + * + * Example: \include Cwise_exp.cpp + * Output: \verbinclude Cwise_exp.out + * + * \sa Math functions, pow(), log(), sin(), cos() + */ +EIGEN_DEVICE_FUNC +inline const ExpReturnType +exp() const +{ + return ExpReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise exponential of *this minus 1. + * + * In exact arithmetic, \c x.expm1() is equivalent to \c x.exp() - 1, + * however, with finite precision, this function is much more accurate when \c x is close to zero. + * + * \sa Math functions, exp() + */ +EIGEN_DEVICE_FUNC +inline const Expm1ReturnType +expm1() const +{ + return Expm1ReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise logarithm of *this. + * + * This function computes the coefficient-wise logarithm. The function MatrixBase::log() in the + * unsupported module MatrixFunctions computes the matrix logarithm. + * + * Example: \include Cwise_log.cpp + * Output: \verbinclude Cwise_log.out + * + * \sa Math functions, log() + */ +EIGEN_DEVICE_FUNC +inline const LogReturnType +log() const +{ + return LogReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise logarithm of 1 plus \c *this. + * + * In exact arithmetic, \c x.log() is equivalent to \c (x+1).log(), + * however, with finite precision, this function is much more accurate when \c x is close to zero. + * + * \sa Math functions, log() + */ +EIGEN_DEVICE_FUNC +inline const Log1pReturnType +log1p() const +{ + return Log1pReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise base-10 logarithm of *this. + * + * This function computes the coefficient-wise base-10 logarithm. + * + * Example: \include Cwise_log10.cpp + * Output: \verbinclude Cwise_log10.out + * + * \sa Math functions, log() + */ +EIGEN_DEVICE_FUNC +inline const Log10ReturnType +log10() const +{ + return Log10ReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise base-2 logarithm of *this. + * + * This function computes the coefficient-wise base-2 logarithm. + * + */ +EIGEN_DEVICE_FUNC +inline const Log2ReturnType +log2() const +{ + return Log2ReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise square root of *this. + * + * This function computes the coefficient-wise square root. The function MatrixBase::sqrt() in the + * unsupported module MatrixFunctions computes the matrix square root. + * + * Example: \include Cwise_sqrt.cpp + * Output: \verbinclude Cwise_sqrt.out + * + * \sa Math functions, pow(), square() + */ +EIGEN_DEVICE_FUNC +inline const SqrtReturnType +sqrt() const +{ + return SqrtReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise inverse square root of *this. + * + * This function computes the coefficient-wise inverse square root. + * + * Example: \include Cwise_sqrt.cpp + * Output: \verbinclude Cwise_sqrt.out + * + * \sa pow(), square() + */ +EIGEN_DEVICE_FUNC +inline const RsqrtReturnType +rsqrt() const +{ + return RsqrtReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise signum of *this. + * + * This function computes the coefficient-wise signum. + * + * Example: \include Cwise_sign.cpp + * Output: \verbinclude Cwise_sign.out + * + * \sa pow(), square() + */ +EIGEN_DEVICE_FUNC +inline const SignReturnType +sign() const +{ + return SignReturnType(derived()); +} + + +/** \returns an expression of the coefficient-wise cosine of *this. + * + * This function computes the coefficient-wise cosine. The function MatrixBase::cos() in the + * unsupported module MatrixFunctions computes the matrix cosine. + * + * Example: \include Cwise_cos.cpp + * Output: \verbinclude Cwise_cos.out + * + * \sa Math functions, sin(), acos() + */ +EIGEN_DEVICE_FUNC +inline const CosReturnType +cos() const +{ + return CosReturnType(derived()); +} + + +/** \returns an expression of the coefficient-wise sine of *this. + * + * This function computes the coefficient-wise sine. The function MatrixBase::sin() in the + * unsupported module MatrixFunctions computes the matrix sine. + * + * Example: \include Cwise_sin.cpp + * Output: \verbinclude Cwise_sin.out + * + * \sa Math functions, cos(), asin() + */ +EIGEN_DEVICE_FUNC +inline const SinReturnType +sin() const +{ + return SinReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise tan of *this. + * + * Example: \include Cwise_tan.cpp + * Output: \verbinclude Cwise_tan.out + * + * \sa Math functions, cos(), sin() + */ +EIGEN_DEVICE_FUNC +inline const TanReturnType +tan() const +{ + return TanReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise arc tan of *this. + * + * Example: \include Cwise_atan.cpp + * Output: \verbinclude Cwise_atan.out + * + * \sa Math functions, tan(), asin(), acos() + */ +EIGEN_DEVICE_FUNC +inline const AtanReturnType +atan() const +{ + return AtanReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise arc cosine of *this. + * + * Example: \include Cwise_acos.cpp + * Output: \verbinclude Cwise_acos.out + * + * \sa Math functions, cos(), asin() + */ +EIGEN_DEVICE_FUNC +inline const AcosReturnType +acos() const +{ + return AcosReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise arc sine of *this. + * + * Example: \include Cwise_asin.cpp + * Output: \verbinclude Cwise_asin.out + * + * \sa Math functions, sin(), acos() + */ +EIGEN_DEVICE_FUNC +inline const AsinReturnType +asin() const +{ + return AsinReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise hyperbolic tan of *this. + * + * Example: \include Cwise_tanh.cpp + * Output: \verbinclude Cwise_tanh.out + * + * \sa Math functions, tan(), sinh(), cosh() + */ +EIGEN_DEVICE_FUNC +inline const TanhReturnType +tanh() const +{ + return TanhReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise hyperbolic sin of *this. + * + * Example: \include Cwise_sinh.cpp + * Output: \verbinclude Cwise_sinh.out + * + * \sa Math functions, sin(), tanh(), cosh() + */ +EIGEN_DEVICE_FUNC +inline const SinhReturnType +sinh() const +{ + return SinhReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise hyperbolic cos of *this. + * + * Example: \include Cwise_cosh.cpp + * Output: \verbinclude Cwise_cosh.out + * + * \sa Math functions, tanh(), sinh(), cosh() + */ +EIGEN_DEVICE_FUNC +inline const CoshReturnType +cosh() const +{ + return CoshReturnType(derived()); +} + +#if EIGEN_HAS_CXX11_MATH +/** \returns an expression of the coefficient-wise inverse hyperbolic tan of *this. + * + * \sa Math functions, atanh(), asinh(), acosh() + */ +EIGEN_DEVICE_FUNC +inline const AtanhReturnType +atanh() const +{ + return AtanhReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise inverse hyperbolic sin of *this. + * + * \sa Math functions, atanh(), asinh(), acosh() + */ +EIGEN_DEVICE_FUNC +inline const AsinhReturnType +asinh() const +{ + return AsinhReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise inverse hyperbolic cos of *this. + * + * \sa Math functions, atanh(), asinh(), acosh() + */ +EIGEN_DEVICE_FUNC +inline const AcoshReturnType +acosh() const +{ + return AcoshReturnType(derived()); +} +#endif + +/** \returns an expression of the coefficient-wise logistic of *this. + */ +EIGEN_DEVICE_FUNC +inline const LogisticReturnType +logistic() const +{ + return LogisticReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise inverse of *this. + * + * Example: \include Cwise_inverse.cpp + * Output: \verbinclude Cwise_inverse.out + * + * \sa operator/(), operator*() + */ +EIGEN_DEVICE_FUNC +inline const InverseReturnType +inverse() const +{ + return InverseReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise square of *this. + * + * Example: \include Cwise_square.cpp + * Output: \verbinclude Cwise_square.out + * + * \sa Math functions, abs2(), cube(), pow() + */ +EIGEN_DEVICE_FUNC +inline const SquareReturnType +square() const +{ + return SquareReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise cube of *this. + * + * Example: \include Cwise_cube.cpp + * Output: \verbinclude Cwise_cube.out + * + * \sa Math functions, square(), pow() + */ +EIGEN_DEVICE_FUNC +inline const CubeReturnType +cube() const +{ + return CubeReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise rint of *this. + * + * Example: \include Cwise_rint.cpp + * Output: \verbinclude Cwise_rint.out + * + * \sa Math functions, ceil(), floor() + */ +EIGEN_DEVICE_FUNC +inline const RintReturnType +rint() const +{ + return RintReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise round of *this. + * + * Example: \include Cwise_round.cpp + * Output: \verbinclude Cwise_round.out + * + * \sa Math functions, ceil(), floor() + */ +EIGEN_DEVICE_FUNC +inline const RoundReturnType +round() const +{ + return RoundReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise floor of *this. + * + * Example: \include Cwise_floor.cpp + * Output: \verbinclude Cwise_floor.out + * + * \sa Math functions, ceil(), round() + */ +EIGEN_DEVICE_FUNC +inline const FloorReturnType +floor() const +{ + return FloorReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise ceil of *this. + * + * Example: \include Cwise_ceil.cpp + * Output: \verbinclude Cwise_ceil.out + * + * \sa Math functions, floor(), round() + */ +EIGEN_DEVICE_FUNC +inline const CeilReturnType +ceil() const +{ + return CeilReturnType(derived()); +} + +template struct ShiftRightXpr { + typedef CwiseUnaryOp, const Derived> Type; +}; + +/** \returns an expression of \c *this with the \a Scalar type arithmetically + * shifted right by \a N bit positions. + * + * The template parameter \a N specifies the number of bit positions to shift. + * + * \sa shiftLeft() + */ +template +EIGEN_DEVICE_FUNC +typename ShiftRightXpr::Type +shiftRight() const +{ + return typename ShiftRightXpr::Type(derived()); +} + + +template struct ShiftLeftXpr { + typedef CwiseUnaryOp, const Derived> Type; +}; + +/** \returns an expression of \c *this with the \a Scalar type logically + * shifted left by \a N bit positions. + * + * The template parameter \a N specifies the number of bit positions to shift. + * + * \sa shiftRight() + */ +template +EIGEN_DEVICE_FUNC +typename ShiftLeftXpr::Type +shiftLeft() const +{ + return typename ShiftLeftXpr::Type(derived()); +} + +/** \returns an expression of the coefficient-wise isnan of *this. + * + * Example: \include Cwise_isNaN.cpp + * Output: \verbinclude Cwise_isNaN.out + * + * \sa isfinite(), isinf() + */ +EIGEN_DEVICE_FUNC +inline const IsNaNReturnType +isNaN() const +{ + return IsNaNReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise isinf of *this. + * + * Example: \include Cwise_isInf.cpp + * Output: \verbinclude Cwise_isInf.out + * + * \sa isnan(), isfinite() + */ +EIGEN_DEVICE_FUNC +inline const IsInfReturnType +isInf() const +{ + return IsInfReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise isfinite of *this. + * + * Example: \include Cwise_isFinite.cpp + * Output: \verbinclude Cwise_isFinite.out + * + * \sa isnan(), isinf() + */ +EIGEN_DEVICE_FUNC +inline const IsFiniteReturnType +isFinite() const +{ + return IsFiniteReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise ! operator of *this + * + * \warning this operator is for expression of bool only. + * + * Example: \include Cwise_boolean_not.cpp + * Output: \verbinclude Cwise_boolean_not.out + * + * \sa operator!=() + */ +EIGEN_DEVICE_FUNC +inline const BooleanNotReturnType +operator!() const +{ + EIGEN_STATIC_ASSERT((internal::is_same::value), + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL); + return BooleanNotReturnType(derived()); +} + + +// --- SpecialFunctions module --- + +typedef CwiseUnaryOp, const Derived> LgammaReturnType; +typedef CwiseUnaryOp, const Derived> DigammaReturnType; +typedef CwiseUnaryOp, const Derived> ErfReturnType; +typedef CwiseUnaryOp, const Derived> ErfcReturnType; +typedef CwiseUnaryOp, const Derived> NdtriReturnType; + +/** \cpp11 \returns an expression of the coefficient-wise ln(|gamma(*this)|). + * + * \specialfunctions_module + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of lgamma(T) for any scalar + * type T to be supported. + * + * \sa Math functions, digamma() + */ +EIGEN_DEVICE_FUNC +inline const LgammaReturnType +lgamma() const +{ + return LgammaReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise digamma (psi, derivative of lgamma). + * + * \specialfunctions_module + * + * \note This function supports only float and double scalar types. To support other scalar types, + * the user has to provide implementations of digamma(T) for any scalar + * type T to be supported. + * + * \sa Math functions, Eigen::digamma(), Eigen::polygamma(), lgamma() + */ +EIGEN_DEVICE_FUNC +inline const DigammaReturnType +digamma() const +{ + return DigammaReturnType(derived()); +} + +/** \cpp11 \returns an expression of the coefficient-wise Gauss error + * function of *this. + * + * \specialfunctions_module + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of erf(T) for any scalar + * type T to be supported. + * + * \sa Math functions, erfc() + */ +EIGEN_DEVICE_FUNC +inline const ErfReturnType +erf() const +{ + return ErfReturnType(derived()); +} + +/** \cpp11 \returns an expression of the coefficient-wise Complementary error + * function of *this. + * + * \specialfunctions_module + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of erfc(T) for any scalar + * type T to be supported. + * + * \sa Math functions, erf() + */ +EIGEN_DEVICE_FUNC +inline const ErfcReturnType +erfc() const +{ + return ErfcReturnType(derived()); +} + +/** \returns an expression of the coefficient-wise inverse of the CDF of the Normal distribution function + * function of *this. + * + * \specialfunctions_module + * + * In other words, considering `x = ndtri(y)`, it returns the argument, x, for which the area under the + * Gaussian probability density function (integrated from minus infinity to x) is equal to y. + * + * \note This function supports only float and double scalar types. To support other scalar types, + * the user has to provide implementations of ndtri(T) for any scalar type T to be supported. + * + * \sa Math functions + */ +EIGEN_DEVICE_FUNC +inline const NdtriReturnType +ndtri() const +{ + return NdtriReturnType(derived()); +} diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/BlockMethods.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/BlockMethods.h new file mode 100644 index 0000000000000000000000000000000000000000..63a52a6ffaa9bcadef7961d05fabe353f52aadc2 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/BlockMethods.h @@ -0,0 +1,1442 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2010 Gael Guennebaud +// Copyright (C) 2006-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PARSED_BY_DOXYGEN + +/// \internal expression type of a column */ +typedef Block::RowsAtCompileTime, 1, !IsRowMajor> ColXpr; +typedef const Block::RowsAtCompileTime, 1, !IsRowMajor> ConstColXpr; +/// \internal expression type of a row */ +typedef Block::ColsAtCompileTime, IsRowMajor> RowXpr; +typedef const Block::ColsAtCompileTime, IsRowMajor> ConstRowXpr; +/// \internal expression type of a block of whole columns */ +typedef Block::RowsAtCompileTime, Dynamic, !IsRowMajor> ColsBlockXpr; +typedef const Block::RowsAtCompileTime, Dynamic, !IsRowMajor> ConstColsBlockXpr; +/// \internal expression type of a block of whole rows */ +typedef Block::ColsAtCompileTime, IsRowMajor> RowsBlockXpr; +typedef const Block::ColsAtCompileTime, IsRowMajor> ConstRowsBlockXpr; +/// \internal expression type of a block of whole columns */ +template struct NColsBlockXpr { typedef Block::RowsAtCompileTime, N, !IsRowMajor> Type; }; +template struct ConstNColsBlockXpr { typedef const Block::RowsAtCompileTime, N, !IsRowMajor> Type; }; +/// \internal expression type of a block of whole rows */ +template struct NRowsBlockXpr { typedef Block::ColsAtCompileTime, IsRowMajor> Type; }; +template struct ConstNRowsBlockXpr { typedef const Block::ColsAtCompileTime, IsRowMajor> Type; }; +/// \internal expression of a block */ +typedef Block BlockXpr; +typedef const Block ConstBlockXpr; +/// \internal expression of a block of fixed sizes */ +template struct FixedBlockXpr { typedef Block Type; }; +template struct ConstFixedBlockXpr { typedef Block Type; }; + +typedef VectorBlock SegmentReturnType; +typedef const VectorBlock ConstSegmentReturnType; +template struct FixedSegmentReturnType { typedef VectorBlock Type; }; +template struct ConstFixedSegmentReturnType { typedef const VectorBlock Type; }; + +/// \internal inner-vector +typedef Block InnerVectorReturnType; +typedef Block ConstInnerVectorReturnType; + +/// \internal set of inner-vectors +typedef Block InnerVectorsReturnType; +typedef Block ConstInnerVectorsReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN + +/// \returns an expression of a block in \c *this with either dynamic or fixed sizes. +/// +/// \param startRow the first row in the block +/// \param startCol the first column in the block +/// \param blockRows number of rows in the block, specified at either run-time or compile-time +/// \param blockCols number of columns in the block, specified at either run-time or compile-time +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example using runtime (aka dynamic) sizes: \include MatrixBase_block_int_int_int_int.cpp +/// Output: \verbinclude MatrixBase_block_int_int_int_int.out +/// +/// \newin{3.4}: +/// +/// The number of rows \a blockRows and columns \a blockCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. In the later case, \c n plays the role of a runtime fallback value in case \c N equals Eigen::Dynamic. +/// Here is an example with a fixed number of rows \c NRows and dynamic number of columns \c cols: +/// \code +/// mat.block(i,j,fix,cols) +/// \endcode +/// +/// This function thus fully covers the features offered by the following overloads block(Index, Index), +/// and block(Index, Index, Index, Index) that are thus obsolete. Indeed, this generic version avoids +/// redundancy, it preserves the argument order, and prevents the need to rely on the template keyword in templated code. +/// +/// but with less redundancy and more consistency as it does not modify the argument order +/// and seamlessly enable hybrid fixed/dynamic sizes. +/// +/// \note Even in the case that the returned expression has dynamic size, in the case +/// when it is applied to a fixed-size matrix, it inherits a fixed maximal size, +/// which means that evaluating it does not cause a dynamic memory allocation. +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block, fix, fix(int) +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename FixedBlockXpr<...,...>::Type +#endif +block(Index startRow, Index startCol, NRowsType blockRows, NColsType blockCols) +{ + return typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type( + derived(), startRow, startCol, internal::get_runtime_value(blockRows), internal::get_runtime_value(blockCols)); +} + +/// This is the const version of block(Index,Index,NRowsType,NColsType) +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +const typename ConstFixedBlockXpr<...,...>::Type +#endif +block(Index startRow, Index startCol, NRowsType blockRows, NColsType blockCols) const +{ + return typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type( + derived(), startRow, startCol, internal::get_runtime_value(blockRows), internal::get_runtime_value(blockCols)); +} + + + +/// \returns a expression of a top-right corner of \c *this with either dynamic or fixed sizes. +/// +/// \param cRows the number of rows in the corner +/// \param cCols the number of columns in the corner +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example with dynamic sizes: \include MatrixBase_topRightCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_topRightCorner_int_int.out +/// +/// The number of rows \a blockRows and columns \a blockCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename FixedBlockXpr<...,...>::Type +#endif +topRightCorner(NRowsType cRows, NColsType cCols) +{ + return typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), 0, cols() - internal::get_runtime_value(cCols), internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// This is the const version of topRightCorner(NRowsType, NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +const typename ConstFixedBlockXpr<...,...>::Type +#endif +topRightCorner(NRowsType cRows, NColsType cCols) const +{ + return typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), 0, cols() - internal::get_runtime_value(cCols), internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// \returns an expression of a fixed-size top-right corner of \c *this. +/// +/// \tparam CRows the number of rows in the corner +/// \tparam CCols the number of columns in the corner +/// +/// Example: \include MatrixBase_template_int_int_topRightCorner.cpp +/// Output: \verbinclude MatrixBase_template_int_int_topRightCorner.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block, block(Index,Index) +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type topRightCorner() +{ + return typename FixedBlockXpr::Type(derived(), 0, cols() - CCols); +} + +/// This is the const version of topRightCorner(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type topRightCorner() const +{ + return typename ConstFixedBlockXpr::Type(derived(), 0, cols() - CCols); +} + +/// \returns an expression of a top-right corner of \c *this. +/// +/// \tparam CRows number of rows in corner as specified at compile-time +/// \tparam CCols number of columns in corner as specified at compile-time +/// \param cRows number of rows in corner as specified at run-time +/// \param cCols number of columns in corner as specified at run-time +/// +/// This function is mainly useful for corners where the number of rows is specified at compile-time +/// and the number of columns is specified at run-time, or vice versa. The compile-time and run-time +/// information should not contradict. In other words, \a cRows should equal \a CRows unless +/// \a CRows is \a Dynamic, and the same for the number of columns. +/// +/// Example: \include MatrixBase_template_int_int_topRightCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_template_int_int_topRightCorner_int_int.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type topRightCorner(Index cRows, Index cCols) +{ + return typename FixedBlockXpr::Type(derived(), 0, cols() - cCols, cRows, cCols); +} + +/// This is the const version of topRightCorner(Index, Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type topRightCorner(Index cRows, Index cCols) const +{ + return typename ConstFixedBlockXpr::Type(derived(), 0, cols() - cCols, cRows, cCols); +} + + + +/// \returns an expression of a top-left corner of \c *this with either dynamic or fixed sizes. +/// +/// \param cRows the number of rows in the corner +/// \param cCols the number of columns in the corner +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include MatrixBase_topLeftCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_topLeftCorner_int_int.out +/// +/// The number of rows \a blockRows and columns \a blockCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename FixedBlockXpr<...,...>::Type +#endif +topLeftCorner(NRowsType cRows, NColsType cCols) +{ + return typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), 0, 0, internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// This is the const version of topLeftCorner(Index, Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +const typename ConstFixedBlockXpr<...,...>::Type +#endif +topLeftCorner(NRowsType cRows, NColsType cCols) const +{ + return typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), 0, 0, internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// \returns an expression of a fixed-size top-left corner of \c *this. +/// +/// The template parameters CRows and CCols are the number of rows and columns in the corner. +/// +/// Example: \include MatrixBase_template_int_int_topLeftCorner.cpp +/// Output: \verbinclude MatrixBase_template_int_int_topLeftCorner.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type topLeftCorner() +{ + return typename FixedBlockXpr::Type(derived(), 0, 0); +} + +/// This is the const version of topLeftCorner(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type topLeftCorner() const +{ + return typename ConstFixedBlockXpr::Type(derived(), 0, 0); +} + +/// \returns an expression of a top-left corner of \c *this. +/// +/// \tparam CRows number of rows in corner as specified at compile-time +/// \tparam CCols number of columns in corner as specified at compile-time +/// \param cRows number of rows in corner as specified at run-time +/// \param cCols number of columns in corner as specified at run-time +/// +/// This function is mainly useful for corners where the number of rows is specified at compile-time +/// and the number of columns is specified at run-time, or vice versa. The compile-time and run-time +/// information should not contradict. In other words, \a cRows should equal \a CRows unless +/// \a CRows is \a Dynamic, and the same for the number of columns. +/// +/// Example: \include MatrixBase_template_int_int_topLeftCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_template_int_int_topLeftCorner_int_int.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type topLeftCorner(Index cRows, Index cCols) +{ + return typename FixedBlockXpr::Type(derived(), 0, 0, cRows, cCols); +} + +/// This is the const version of topLeftCorner(Index, Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type topLeftCorner(Index cRows, Index cCols) const +{ + return typename ConstFixedBlockXpr::Type(derived(), 0, 0, cRows, cCols); +} + + + +/// \returns an expression of a bottom-right corner of \c *this with either dynamic or fixed sizes. +/// +/// \param cRows the number of rows in the corner +/// \param cCols the number of columns in the corner +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include MatrixBase_bottomRightCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_bottomRightCorner_int_int.out +/// +/// The number of rows \a blockRows and columns \a blockCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename FixedBlockXpr<...,...>::Type +#endif +bottomRightCorner(NRowsType cRows, NColsType cCols) +{ + return typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), rows() - internal::get_runtime_value(cRows), cols() - internal::get_runtime_value(cCols), + internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// This is the const version of bottomRightCorner(NRowsType, NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +const typename ConstFixedBlockXpr<...,...>::Type +#endif +bottomRightCorner(NRowsType cRows, NColsType cCols) const +{ + return typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), rows() - internal::get_runtime_value(cRows), cols() - internal::get_runtime_value(cCols), + internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// \returns an expression of a fixed-size bottom-right corner of \c *this. +/// +/// The template parameters CRows and CCols are the number of rows and columns in the corner. +/// +/// Example: \include MatrixBase_template_int_int_bottomRightCorner.cpp +/// Output: \verbinclude MatrixBase_template_int_int_bottomRightCorner.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type bottomRightCorner() +{ + return typename FixedBlockXpr::Type(derived(), rows() - CRows, cols() - CCols); +} + +/// This is the const version of bottomRightCorner(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type bottomRightCorner() const +{ + return typename ConstFixedBlockXpr::Type(derived(), rows() - CRows, cols() - CCols); +} + +/// \returns an expression of a bottom-right corner of \c *this. +/// +/// \tparam CRows number of rows in corner as specified at compile-time +/// \tparam CCols number of columns in corner as specified at compile-time +/// \param cRows number of rows in corner as specified at run-time +/// \param cCols number of columns in corner as specified at run-time +/// +/// This function is mainly useful for corners where the number of rows is specified at compile-time +/// and the number of columns is specified at run-time, or vice versa. The compile-time and run-time +/// information should not contradict. In other words, \a cRows should equal \a CRows unless +/// \a CRows is \a Dynamic, and the same for the number of columns. +/// +/// Example: \include MatrixBase_template_int_int_bottomRightCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_template_int_int_bottomRightCorner_int_int.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type bottomRightCorner(Index cRows, Index cCols) +{ + return typename FixedBlockXpr::Type(derived(), rows() - cRows, cols() - cCols, cRows, cCols); +} + +/// This is the const version of bottomRightCorner(Index, Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type bottomRightCorner(Index cRows, Index cCols) const +{ + return typename ConstFixedBlockXpr::Type(derived(), rows() - cRows, cols() - cCols, cRows, cCols); +} + + + +/// \returns an expression of a bottom-left corner of \c *this with either dynamic or fixed sizes. +/// +/// \param cRows the number of rows in the corner +/// \param cCols the number of columns in the corner +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include MatrixBase_bottomLeftCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_bottomLeftCorner_int_int.out +/// +/// The number of rows \a blockRows and columns \a blockCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename FixedBlockXpr<...,...>::Type +#endif +bottomLeftCorner(NRowsType cRows, NColsType cCols) +{ + return typename FixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), rows() - internal::get_runtime_value(cRows), 0, + internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// This is the const version of bottomLeftCorner(NRowsType, NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type +#else +typename ConstFixedBlockXpr<...,...>::Type +#endif +bottomLeftCorner(NRowsType cRows, NColsType cCols) const +{ + return typename ConstFixedBlockXpr::value,internal::get_fixed_value::value>::Type + (derived(), rows() - internal::get_runtime_value(cRows), 0, + internal::get_runtime_value(cRows), internal::get_runtime_value(cCols)); +} + +/// \returns an expression of a fixed-size bottom-left corner of \c *this. +/// +/// The template parameters CRows and CCols are the number of rows and columns in the corner. +/// +/// Example: \include MatrixBase_template_int_int_bottomLeftCorner.cpp +/// Output: \verbinclude MatrixBase_template_int_int_bottomLeftCorner.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type bottomLeftCorner() +{ + return typename FixedBlockXpr::Type(derived(), rows() - CRows, 0); +} + +/// This is the const version of bottomLeftCorner(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type bottomLeftCorner() const +{ + return typename ConstFixedBlockXpr::Type(derived(), rows() - CRows, 0); +} + +/// \returns an expression of a bottom-left corner of \c *this. +/// +/// \tparam CRows number of rows in corner as specified at compile-time +/// \tparam CCols number of columns in corner as specified at compile-time +/// \param cRows number of rows in corner as specified at run-time +/// \param cCols number of columns in corner as specified at run-time +/// +/// This function is mainly useful for corners where the number of rows is specified at compile-time +/// and the number of columns is specified at run-time, or vice versa. The compile-time and run-time +/// information should not contradict. In other words, \a cRows should equal \a CRows unless +/// \a CRows is \a Dynamic, and the same for the number of columns. +/// +/// Example: \include MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp +/// Output: \verbinclude MatrixBase_template_int_int_bottomLeftCorner_int_int.out +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa class Block +/// +template +EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type bottomLeftCorner(Index cRows, Index cCols) +{ + return typename FixedBlockXpr::Type(derived(), rows() - cRows, 0, cRows, cCols); +} + +/// This is the const version of bottomLeftCorner(Index, Index). +template +EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type bottomLeftCorner(Index cRows, Index cCols) const +{ + return typename ConstFixedBlockXpr::Type(derived(), rows() - cRows, 0, cRows, cCols); +} + + + +/// \returns a block consisting of the top rows of \c *this. +/// +/// \param n the number of rows in the block +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// +/// Example: \include MatrixBase_topRows_int.cpp +/// Output: \verbinclude MatrixBase_topRows_int.out +/// +/// The number of rows \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NRowsBlockXpr::value>::Type +#else +typename NRowsBlockXpr<...>::Type +#endif +topRows(NRowsType n) +{ + return typename NRowsBlockXpr::value>::Type + (derived(), 0, 0, internal::get_runtime_value(n), cols()); +} + +/// This is the const version of topRows(NRowsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNRowsBlockXpr::value>::Type +#else +const typename ConstNRowsBlockXpr<...>::Type +#endif +topRows(NRowsType n) const +{ + return typename ConstNRowsBlockXpr::value>::Type + (derived(), 0, 0, internal::get_runtime_value(n), cols()); +} + +/// \returns a block consisting of the top rows of \c *this. +/// +/// \tparam N the number of rows in the block as specified at compile-time +/// \param n the number of rows in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_topRows.cpp +/// Output: \verbinclude MatrixBase_template_int_topRows.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NRowsBlockXpr::Type topRows(Index n = N) +{ + return typename NRowsBlockXpr::Type(derived(), 0, 0, n, cols()); +} + +/// This is the const version of topRows(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNRowsBlockXpr::Type topRows(Index n = N) const +{ + return typename ConstNRowsBlockXpr::Type(derived(), 0, 0, n, cols()); +} + + + +/// \returns a block consisting of the bottom rows of \c *this. +/// +/// \param n the number of rows in the block +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// +/// Example: \include MatrixBase_bottomRows_int.cpp +/// Output: \verbinclude MatrixBase_bottomRows_int.out +/// +/// The number of rows \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NRowsBlockXpr::value>::Type +#else +typename NRowsBlockXpr<...>::Type +#endif +bottomRows(NRowsType n) +{ + return typename NRowsBlockXpr::value>::Type + (derived(), rows() - internal::get_runtime_value(n), 0, internal::get_runtime_value(n), cols()); +} + +/// This is the const version of bottomRows(NRowsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNRowsBlockXpr::value>::Type +#else +const typename ConstNRowsBlockXpr<...>::Type +#endif +bottomRows(NRowsType n) const +{ + return typename ConstNRowsBlockXpr::value>::Type + (derived(), rows() - internal::get_runtime_value(n), 0, internal::get_runtime_value(n), cols()); +} + +/// \returns a block consisting of the bottom rows of \c *this. +/// +/// \tparam N the number of rows in the block as specified at compile-time +/// \param n the number of rows in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_bottomRows.cpp +/// Output: \verbinclude MatrixBase_template_int_bottomRows.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NRowsBlockXpr::Type bottomRows(Index n = N) +{ + return typename NRowsBlockXpr::Type(derived(), rows() - n, 0, n, cols()); +} + +/// This is the const version of bottomRows(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNRowsBlockXpr::Type bottomRows(Index n = N) const +{ + return typename ConstNRowsBlockXpr::Type(derived(), rows() - n, 0, n, cols()); +} + + + +/// \returns a block consisting of a range of rows of \c *this. +/// +/// \param startRow the index of the first row in the block +/// \param n the number of rows in the block +/// \tparam NRowsType the type of the value handling the number of rows in the block, typically Index. +/// +/// Example: \include DenseBase_middleRows_int.cpp +/// Output: \verbinclude DenseBase_middleRows_int.out +/// +/// The number of rows \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NRowsBlockXpr::value>::Type +#else +typename NRowsBlockXpr<...>::Type +#endif +middleRows(Index startRow, NRowsType n) +{ + return typename NRowsBlockXpr::value>::Type + (derived(), startRow, 0, internal::get_runtime_value(n), cols()); +} + +/// This is the const version of middleRows(Index,NRowsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNRowsBlockXpr::value>::Type +#else +const typename ConstNRowsBlockXpr<...>::Type +#endif +middleRows(Index startRow, NRowsType n) const +{ + return typename ConstNRowsBlockXpr::value>::Type + (derived(), startRow, 0, internal::get_runtime_value(n), cols()); +} + +/// \returns a block consisting of a range of rows of \c *this. +/// +/// \tparam N the number of rows in the block as specified at compile-time +/// \param startRow the index of the first row in the block +/// \param n the number of rows in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include DenseBase_template_int_middleRows.cpp +/// Output: \verbinclude DenseBase_template_int_middleRows.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NRowsBlockXpr::Type middleRows(Index startRow, Index n = N) +{ + return typename NRowsBlockXpr::Type(derived(), startRow, 0, n, cols()); +} + +/// This is the const version of middleRows(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNRowsBlockXpr::Type middleRows(Index startRow, Index n = N) const +{ + return typename ConstNRowsBlockXpr::Type(derived(), startRow, 0, n, cols()); +} + + + +/// \returns a block consisting of the left columns of \c *this. +/// +/// \param n the number of columns in the block +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include MatrixBase_leftCols_int.cpp +/// Output: \verbinclude MatrixBase_leftCols_int.out +/// +/// The number of columns \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NColsBlockXpr::value>::Type +#else +typename NColsBlockXpr<...>::Type +#endif +leftCols(NColsType n) +{ + return typename NColsBlockXpr::value>::Type + (derived(), 0, 0, rows(), internal::get_runtime_value(n)); +} + +/// This is the const version of leftCols(NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNColsBlockXpr::value>::Type +#else +const typename ConstNColsBlockXpr<...>::Type +#endif +leftCols(NColsType n) const +{ + return typename ConstNColsBlockXpr::value>::Type + (derived(), 0, 0, rows(), internal::get_runtime_value(n)); +} + +/// \returns a block consisting of the left columns of \c *this. +/// +/// \tparam N the number of columns in the block as specified at compile-time +/// \param n the number of columns in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_leftCols.cpp +/// Output: \verbinclude MatrixBase_template_int_leftCols.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NColsBlockXpr::Type leftCols(Index n = N) +{ + return typename NColsBlockXpr::Type(derived(), 0, 0, rows(), n); +} + +/// This is the const version of leftCols(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNColsBlockXpr::Type leftCols(Index n = N) const +{ + return typename ConstNColsBlockXpr::Type(derived(), 0, 0, rows(), n); +} + + + +/// \returns a block consisting of the right columns of \c *this. +/// +/// \param n the number of columns in the block +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include MatrixBase_rightCols_int.cpp +/// Output: \verbinclude MatrixBase_rightCols_int.out +/// +/// The number of columns \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NColsBlockXpr::value>::Type +#else +typename NColsBlockXpr<...>::Type +#endif +rightCols(NColsType n) +{ + return typename NColsBlockXpr::value>::Type + (derived(), 0, cols() - internal::get_runtime_value(n), rows(), internal::get_runtime_value(n)); +} + +/// This is the const version of rightCols(NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNColsBlockXpr::value>::Type +#else +const typename ConstNColsBlockXpr<...>::Type +#endif +rightCols(NColsType n) const +{ + return typename ConstNColsBlockXpr::value>::Type + (derived(), 0, cols() - internal::get_runtime_value(n), rows(), internal::get_runtime_value(n)); +} + +/// \returns a block consisting of the right columns of \c *this. +/// +/// \tparam N the number of columns in the block as specified at compile-time +/// \param n the number of columns in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_rightCols.cpp +/// Output: \verbinclude MatrixBase_template_int_rightCols.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NColsBlockXpr::Type rightCols(Index n = N) +{ + return typename NColsBlockXpr::Type(derived(), 0, cols() - n, rows(), n); +} + +/// This is the const version of rightCols(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNColsBlockXpr::Type rightCols(Index n = N) const +{ + return typename ConstNColsBlockXpr::Type(derived(), 0, cols() - n, rows(), n); +} + + + +/// \returns a block consisting of a range of columns of \c *this. +/// +/// \param startCol the index of the first column in the block +/// \param numCols the number of columns in the block +/// \tparam NColsType the type of the value handling the number of columns in the block, typically Index. +/// +/// Example: \include DenseBase_middleCols_int.cpp +/// Output: \verbinclude DenseBase_middleCols_int.out +/// +/// The number of columns \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename NColsBlockXpr::value>::Type +#else +typename NColsBlockXpr<...>::Type +#endif +middleCols(Index startCol, NColsType numCols) +{ + return typename NColsBlockXpr::value>::Type + (derived(), 0, startCol, rows(), internal::get_runtime_value(numCols)); +} + +/// This is the const version of middleCols(Index,NColsType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstNColsBlockXpr::value>::Type +#else +const typename ConstNColsBlockXpr<...>::Type +#endif +middleCols(Index startCol, NColsType numCols) const +{ + return typename ConstNColsBlockXpr::value>::Type + (derived(), 0, startCol, rows(), internal::get_runtime_value(numCols)); +} + +/// \returns a block consisting of a range of columns of \c *this. +/// +/// \tparam N the number of columns in the block as specified at compile-time +/// \param startCol the index of the first column in the block +/// \param n the number of columns in the block as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include DenseBase_template_int_middleCols.cpp +/// Output: \verbinclude DenseBase_template_int_middleCols.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename NColsBlockXpr::Type middleCols(Index startCol, Index n = N) +{ + return typename NColsBlockXpr::Type(derived(), 0, startCol, rows(), n); +} + +/// This is the const version of middleCols(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstNColsBlockXpr::Type middleCols(Index startCol, Index n = N) const +{ + return typename ConstNColsBlockXpr::Type(derived(), 0, startCol, rows(), n); +} + + + +/// \returns a fixed-size expression of a block of \c *this. +/// +/// The template parameters \a NRows and \a NCols are the number of +/// rows and columns in the block. +/// +/// \param startRow the first row in the block +/// \param startCol the first column in the block +/// +/// Example: \include MatrixBase_block_int_int.cpp +/// Output: \verbinclude MatrixBase_block_int_int.out +/// +/// \note The usage of of this overload is discouraged from %Eigen 3.4, better used the generic +/// block(Index,Index,NRowsType,NColsType), here is the one-to-one equivalence: +/// \code +/// mat.template block(i,j) <--> mat.block(i,j,fix,fix) +/// \endcode +/// +/// \note since block is a templated member, the keyword template has to be used +/// if the matrix type is also a template parameter: \code m.template block<3,3>(1,1); \endcode +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type block(Index startRow, Index startCol) +{ + return typename FixedBlockXpr::Type(derived(), startRow, startCol); +} + +/// This is the const version of block<>(Index, Index). */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type block(Index startRow, Index startCol) const +{ + return typename ConstFixedBlockXpr::Type(derived(), startRow, startCol); +} + +/// \returns an expression of a block of \c *this. +/// +/// \tparam NRows number of rows in block as specified at compile-time +/// \tparam NCols number of columns in block as specified at compile-time +/// \param startRow the first row in the block +/// \param startCol the first column in the block +/// \param blockRows number of rows in block as specified at run-time +/// \param blockCols number of columns in block as specified at run-time +/// +/// This function is mainly useful for blocks where the number of rows is specified at compile-time +/// and the number of columns is specified at run-time, or vice versa. The compile-time and run-time +/// information should not contradict. In other words, \a blockRows should equal \a NRows unless +/// \a NRows is \a Dynamic, and the same for the number of columns. +/// +/// Example: \include MatrixBase_template_int_int_block_int_int_int_int.cpp +/// Output: \verbinclude MatrixBase_template_int_int_block_int_int_int_int.out +/// +/// \note The usage of of this overload is discouraged from %Eigen 3.4, better used the generic +/// block(Index,Index,NRowsType,NColsType), here is the one-to-one complete equivalence: +/// \code +/// mat.template block(i,j,rows,cols) <--> mat.block(i,j,fix(rows),fix(cols)) +/// \endcode +/// If we known that, e.g., NRows==Dynamic and NCols!=Dynamic, then the equivalence becomes: +/// \code +/// mat.template block(i,j,rows,NCols) <--> mat.block(i,j,rows,fix) +/// \endcode +/// +EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +/// +/// \sa block(Index,Index,NRowsType,NColsType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedBlockXpr::Type block(Index startRow, Index startCol, + Index blockRows, Index blockCols) +{ + return typename FixedBlockXpr::Type(derived(), startRow, startCol, blockRows, blockCols); +} + +/// This is the const version of block<>(Index, Index, Index, Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const typename ConstFixedBlockXpr::Type block(Index startRow, Index startCol, + Index blockRows, Index blockCols) const +{ + return typename ConstFixedBlockXpr::Type(derived(), startRow, startCol, blockRows, blockCols); +} + +/// \returns an expression of the \a i-th column of \c *this. Note that the numbering starts at 0. +/// +/// Example: \include MatrixBase_col.cpp +/// Output: \verbinclude MatrixBase_col.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(column-major) +/** + * \sa row(), class Block */ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +ColXpr col(Index i) +{ + return ColXpr(derived(), i); +} + +/// This is the const version of col(). +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +ConstColXpr col(Index i) const +{ + return ConstColXpr(derived(), i); +} + +/// \returns an expression of the \a i-th row of \c *this. Note that the numbering starts at 0. +/// +/// Example: \include MatrixBase_row.cpp +/// Output: \verbinclude MatrixBase_row.out +/// +EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(row-major) +/** + * \sa col(), class Block */ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +RowXpr row(Index i) +{ + return RowXpr(derived(), i); +} + +/// This is the const version of row(). */ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +ConstRowXpr row(Index i) const +{ + return ConstRowXpr(derived(), i); +} + +/// \returns an expression of a segment (i.e. a vector block) in \c *this with either dynamic or fixed sizes. +/// +/// \only_for_vectors +/// +/// \param start the first coefficient in the segment +/// \param n the number of coefficients in the segment +/// \tparam NType the type of the value handling the number of coefficients in the segment, typically Index. +/// +/// Example: \include MatrixBase_segment_int_int.cpp +/// Output: \verbinclude MatrixBase_segment_int_int.out +/// +/// The number of coefficients \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +/// \note Even in the case that the returned expression has dynamic size, in the case +/// when it is applied to a fixed-size vector, it inherits a fixed maximal size, +/// which means that evaluating it does not cause a dynamic memory allocation. +/// +/// \sa block(Index,Index,NRowsType,NColsType), fix, fix(int), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedSegmentReturnType::value>::Type +#else +typename FixedSegmentReturnType<...>::Type +#endif +segment(Index start, NType n) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::value>::Type + (derived(), start, internal::get_runtime_value(n)); +} + + +/// This is the const version of segment(Index,NType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedSegmentReturnType::value>::Type +#else +const typename ConstFixedSegmentReturnType<...>::Type +#endif +segment(Index start, NType n) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::value>::Type + (derived(), start, internal::get_runtime_value(n)); +} + +/// \returns an expression of the first coefficients of \c *this with either dynamic or fixed sizes. +/// +/// \only_for_vectors +/// +/// \param n the number of coefficients in the segment +/// \tparam NType the type of the value handling the number of coefficients in the segment, typically Index. +/// +/// Example: \include MatrixBase_start_int.cpp +/// Output: \verbinclude MatrixBase_start_int.out +/// +/// The number of coefficients \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +/// \note Even in the case that the returned expression has dynamic size, in the case +/// when it is applied to a fixed-size vector, it inherits a fixed maximal size, +/// which means that evaluating it does not cause a dynamic memory allocation. +/// +/// \sa class Block, block(Index,Index) +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedSegmentReturnType::value>::Type +#else +typename FixedSegmentReturnType<...>::Type +#endif +head(NType n) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::value>::Type + (derived(), 0, internal::get_runtime_value(n)); +} + +/// This is the const version of head(NType). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedSegmentReturnType::value>::Type +#else +const typename ConstFixedSegmentReturnType<...>::Type +#endif +head(NType n) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::value>::Type + (derived(), 0, internal::get_runtime_value(n)); +} + +/// \returns an expression of a last coefficients of \c *this with either dynamic or fixed sizes. +/// +/// \only_for_vectors +/// +/// \param n the number of coefficients in the segment +/// \tparam NType the type of the value handling the number of coefficients in the segment, typically Index. +/// +/// Example: \include MatrixBase_end_int.cpp +/// Output: \verbinclude MatrixBase_end_int.out +/// +/// The number of coefficients \a n can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. +/// See \link block(Index,Index,NRowsType,NColsType) block() \endlink for the details. +/// +/// \note Even in the case that the returned expression has dynamic size, in the case +/// when it is applied to a fixed-size vector, it inherits a fixed maximal size, +/// which means that evaluating it does not cause a dynamic memory allocation. +/// +/// \sa class Block, block(Index,Index) +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +typename FixedSegmentReturnType::value>::Type +#else +typename FixedSegmentReturnType<...>::Type +#endif +tail(NType n) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::value>::Type + (derived(), this->size() - internal::get_runtime_value(n), internal::get_runtime_value(n)); +} + +/// This is the const version of tail(Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +#ifndef EIGEN_PARSED_BY_DOXYGEN +const typename ConstFixedSegmentReturnType::value>::Type +#else +const typename ConstFixedSegmentReturnType<...>::Type +#endif +tail(NType n) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::value>::Type + (derived(), this->size() - internal::get_runtime_value(n), internal::get_runtime_value(n)); +} + +/// \returns a fixed-size expression of a segment (i.e. a vector block) in \c *this +/// +/// \only_for_vectors +/// +/// \tparam N the number of coefficients in the segment as specified at compile-time +/// \param start the index of the first element in the segment +/// \param n the number of coefficients in the segment as specified at compile-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_segment.cpp +/// Output: \verbinclude MatrixBase_template_int_segment.out +/// +/// \sa segment(Index,NType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedSegmentReturnType::Type segment(Index start, Index n = N) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::Type(derived(), start, n); +} + +/// This is the const version of segment(Index). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstFixedSegmentReturnType::Type segment(Index start, Index n = N) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::Type(derived(), start, n); +} + +/// \returns a fixed-size expression of the first coefficients of \c *this. +/// +/// \only_for_vectors +/// +/// \tparam N the number of coefficients in the segment as specified at compile-time +/// \param n the number of coefficients in the segment as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_start.cpp +/// Output: \verbinclude MatrixBase_template_int_start.out +/// +/// \sa head(NType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedSegmentReturnType::Type head(Index n = N) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::Type(derived(), 0, n); +} + +/// This is the const version of head(). +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstFixedSegmentReturnType::Type head(Index n = N) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::Type(derived(), 0, n); +} + +/// \returns a fixed-size expression of the last coefficients of \c *this. +/// +/// \only_for_vectors +/// +/// \tparam N the number of coefficients in the segment as specified at compile-time +/// \param n the number of coefficients in the segment as specified at run-time +/// +/// The compile-time and run-time information should not contradict. In other words, +/// \a n should equal \a N unless \a N is \a Dynamic. +/// +/// Example: \include MatrixBase_template_int_end.cpp +/// Output: \verbinclude MatrixBase_template_int_end.out +/// +/// \sa tail(NType), class Block +/// +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename FixedSegmentReturnType::Type tail(Index n = N) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename FixedSegmentReturnType::Type(derived(), size() - n); +} + +/// This is the const version of tail. +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename ConstFixedSegmentReturnType::Type tail(Index n = N) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return typename ConstFixedSegmentReturnType::Type(derived(), size() - n); +} + +/// \returns the \a outer -th column (resp. row) of the matrix \c *this if \c *this +/// is col-major (resp. row-major). +/// +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +InnerVectorReturnType innerVector(Index outer) +{ return InnerVectorReturnType(derived(), outer); } + +/// \returns the \a outer -th column (resp. row) of the matrix \c *this if \c *this +/// is col-major (resp. row-major). Read-only. +/// +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const ConstInnerVectorReturnType innerVector(Index outer) const +{ return ConstInnerVectorReturnType(derived(), outer); } + +/// \returns the \a outer -th column (resp. row) of the matrix \c *this if \c *this +/// is col-major (resp. row-major). +/// +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +InnerVectorsReturnType +innerVectors(Index outerStart, Index outerSize) +{ + return Block(derived(), + IsRowMajor ? outerStart : 0, IsRowMajor ? 0 : outerStart, + IsRowMajor ? outerSize : rows(), IsRowMajor ? cols() : outerSize); + +} + +/// \returns the \a outer -th column (resp. row) of the matrix \c *this if \c *this +/// is col-major (resp. row-major). Read-only. +/// +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +const ConstInnerVectorsReturnType +innerVectors(Index outerStart, Index outerSize) const +{ + return Block(derived(), + IsRowMajor ? outerStart : 0, IsRowMajor ? 0 : outerStart, + IsRowMajor ? outerSize : rows(), IsRowMajor ? cols() : outerSize); + +} + +/** \returns the i-th subvector (column or vector) according to the \c Direction + * \sa subVectors() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename internal::conditional::type +subVector(Index i) +{ + return typename internal::conditional::type(derived(),i); +} + +/** This is the const version of subVector(Index) */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +typename internal::conditional::type +subVector(Index i) const +{ + return typename internal::conditional::type(derived(),i); +} + +/** \returns the number of subvectors (rows or columns) in the direction \c Direction + * \sa subVector(Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR +Index subVectors() const +{ return (Direction==Vertical)?cols():rows(); } diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..8b6730ede025dd4c9600baf29a7fe6fafc4f79bc --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h @@ -0,0 +1,115 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2016 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// This file is a base class plugin containing common coefficient wise functions. + +/** \returns an expression of the difference of \c *this and \a other + * + * \note If you want to substract a given scalar from all coefficients, see Cwise::operator-(). + * + * \sa class CwiseBinaryOp, operator-=() + */ +EIGEN_MAKE_CWISE_BINARY_OP(operator-,difference) + +/** \returns an expression of the sum of \c *this and \a other + * + * \note If you want to add a given scalar to all coefficients, see Cwise::operator+(). + * + * \sa class CwiseBinaryOp, operator+=() + */ +EIGEN_MAKE_CWISE_BINARY_OP(operator+,sum) + +/** \returns an expression of a custom coefficient-wise operator \a func of *this and \a other + * + * The template parameter \a CustomBinaryOp is the type of the functor + * of the custom operator (see class CwiseBinaryOp for an example) + * + * Here is an example illustrating the use of custom functors: + * \include class_CwiseBinaryOp.cpp + * Output: \verbinclude class_CwiseBinaryOp.out + * + * \sa class CwiseBinaryOp, operator+(), operator-(), cwiseProduct() + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp +binaryExpr(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other, const CustomBinaryOp& func = CustomBinaryOp()) const +{ + return CwiseBinaryOp(derived(), other.derived(), func); +} + + +#ifndef EIGEN_PARSED_BY_DOXYGEN +EIGEN_MAKE_SCALAR_BINARY_OP(operator*,product) +#else +/** \returns an expression of \c *this scaled by the scalar factor \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + */ +template +const CwiseBinaryOp,Derived,Constant > operator*(const T& scalar) const; +/** \returns an expression of \a expr scaled by the scalar factor \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + */ +template friend +const CwiseBinaryOp,Constant,Derived> operator*(const T& scalar, const StorageBaseType& expr); +#endif + + + +#ifndef EIGEN_PARSED_BY_DOXYGEN +EIGEN_MAKE_SCALAR_BINARY_OP_ONTHERIGHT(operator/,quotient) +#else +/** \returns an expression of \c *this divided by the scalar value \a scalar + * + * \tparam T is the scalar type of \a scalar. It must be compatible with the scalar type of the given expression. + */ +template +const CwiseBinaryOp,Derived,Constant > operator/(const T& scalar) const; +#endif + +/** \returns an expression of the coefficient-wise boolean \b and operator of \c *this and \a other + * + * \warning this operator is for expression of bool only. + * + * Example: \include Cwise_boolean_and.cpp + * Output: \verbinclude Cwise_boolean_and.out + * + * \sa operator||(), select() + */ +template +EIGEN_DEVICE_FUNC +inline const CwiseBinaryOp +operator&&(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + EIGEN_STATIC_ASSERT((internal::is_same::value && internal::is_same::value), + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL); + return CwiseBinaryOp(derived(),other.derived()); +} + +/** \returns an expression of the coefficient-wise boolean \b or operator of \c *this and \a other + * + * \warning this operator is for expression of bool only. + * + * Example: \include Cwise_boolean_or.cpp + * Output: \verbinclude Cwise_boolean_or.out + * + * \sa operator&&(), select() + */ +template +EIGEN_DEVICE_FUNC +inline const CwiseBinaryOp +operator||(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + EIGEN_STATIC_ASSERT((internal::is_same::value && internal::is_same::value), + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_OF_BOOL); + return CwiseBinaryOp(derived(),other.derived()); +} diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..5418dc4154f2b078e964383d6bb5acebe0bf3210 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h @@ -0,0 +1,177 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// This file is a base class plugin containing common coefficient wise functions. + +#ifndef EIGEN_PARSED_BY_DOXYGEN + +/** \internal the return type of conjugate() */ +typedef typename internal::conditional::IsComplex, + const CwiseUnaryOp, const Derived>, + const Derived& + >::type ConjugateReturnType; +/** \internal the return type of real() const */ +typedef typename internal::conditional::IsComplex, + const CwiseUnaryOp, const Derived>, + const Derived& + >::type RealReturnType; +/** \internal the return type of real() */ +typedef typename internal::conditional::IsComplex, + CwiseUnaryView, Derived>, + Derived& + >::type NonConstRealReturnType; +/** \internal the return type of imag() const */ +typedef CwiseUnaryOp, const Derived> ImagReturnType; +/** \internal the return type of imag() */ +typedef CwiseUnaryView, Derived> NonConstImagReturnType; + +typedef CwiseUnaryOp, const Derived> NegativeReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN + +/// \returns an expression of the opposite of \c *this +/// +EIGEN_DOC_UNARY_ADDONS(operator-,opposite) +/// +EIGEN_DEVICE_FUNC +inline const NegativeReturnType +operator-() const { return NegativeReturnType(derived()); } + + +template struct CastXpr { typedef typename internal::cast_return_type, const Derived> >::type Type; }; + +/// \returns an expression of \c *this with the \a Scalar type casted to +/// \a NewScalar. +/// +/// The template parameter \a NewScalar is the type we are casting the scalars to. +/// +EIGEN_DOC_UNARY_ADDONS(cast,conversion function) +/// +/// \sa class CwiseUnaryOp +/// +template +EIGEN_DEVICE_FUNC +typename CastXpr::Type +cast() const +{ + return typename CastXpr::Type(derived()); +} + +/// \returns an expression of the complex conjugate of \c *this. +/// +EIGEN_DOC_UNARY_ADDONS(conjugate,complex conjugate) +/// +/// \sa Math functions, MatrixBase::adjoint() +EIGEN_DEVICE_FUNC +inline ConjugateReturnType +conjugate() const +{ + return ConjugateReturnType(derived()); +} + +/// \returns an expression of the complex conjugate of \c *this if Cond==true, returns derived() otherwise. +/// +EIGEN_DOC_UNARY_ADDONS(conjugate,complex conjugate) +/// +/// \sa conjugate() +template +EIGEN_DEVICE_FUNC +inline typename internal::conditional::type +conjugateIf() const +{ + typedef typename internal::conditional::type ReturnType; + return ReturnType(derived()); +} + +/// \returns a read-only expression of the real part of \c *this. +/// +EIGEN_DOC_UNARY_ADDONS(real,real part function) +/// +/// \sa imag() +EIGEN_DEVICE_FUNC +inline RealReturnType +real() const { return RealReturnType(derived()); } + +/// \returns an read-only expression of the imaginary part of \c *this. +/// +EIGEN_DOC_UNARY_ADDONS(imag,imaginary part function) +/// +/// \sa real() +EIGEN_DEVICE_FUNC +inline const ImagReturnType +imag() const { return ImagReturnType(derived()); } + +/// \brief Apply a unary operator coefficient-wise +/// \param[in] func Functor implementing the unary operator +/// \tparam CustomUnaryOp Type of \a func +/// \returns An expression of a custom coefficient-wise unary operator \a func of *this +/// +/// The function \c ptr_fun() from the C++ standard library can be used to make functors out of normal functions. +/// +/// Example: +/// \include class_CwiseUnaryOp_ptrfun.cpp +/// Output: \verbinclude class_CwiseUnaryOp_ptrfun.out +/// +/// Genuine functors allow for more possibilities, for instance it may contain a state. +/// +/// Example: +/// \include class_CwiseUnaryOp.cpp +/// Output: \verbinclude class_CwiseUnaryOp.out +/// +EIGEN_DOC_UNARY_ADDONS(unaryExpr,unary function) +/// +/// \sa unaryViewExpr, binaryExpr, class CwiseUnaryOp +/// +template +EIGEN_DEVICE_FUNC +inline const CwiseUnaryOp +unaryExpr(const CustomUnaryOp& func = CustomUnaryOp()) const +{ + return CwiseUnaryOp(derived(), func); +} + +/// \returns an expression of a custom coefficient-wise unary operator \a func of *this +/// +/// The template parameter \a CustomUnaryOp is the type of the functor +/// of the custom unary operator. +/// +/// Example: +/// \include class_CwiseUnaryOp.cpp +/// Output: \verbinclude class_CwiseUnaryOp.out +/// +EIGEN_DOC_UNARY_ADDONS(unaryViewExpr,unary function) +/// +/// \sa unaryExpr, binaryExpr class CwiseUnaryOp +/// +template +EIGEN_DEVICE_FUNC +inline const CwiseUnaryView +unaryViewExpr(const CustomViewOp& func = CustomViewOp()) const +{ + return CwiseUnaryView(derived(), func); +} + +/// \returns a non const expression of the real part of \c *this. +/// +EIGEN_DOC_UNARY_ADDONS(real,real part function) +/// +/// \sa imag() +EIGEN_DEVICE_FUNC +inline NonConstRealReturnType +real() { return NonConstRealReturnType(derived()); } + +/// \returns a non const expression of the imaginary part of \c *this. +/// +EIGEN_DOC_UNARY_ADDONS(imag,imaginary part function) +/// +/// \sa real() +EIGEN_DEVICE_FUNC +inline NonConstImagReturnType +imag() { return NonConstImagReturnType(derived()); } diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h new file mode 100644 index 0000000000000000000000000000000000000000..5bfb19ac6cdfd5a66fdf15f001d72f7efc2a8300 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h @@ -0,0 +1,262 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2017 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if !defined(EIGEN_PARSED_BY_DOXYGEN) + +// This file is automatically included twice to generate const and non-const versions + +#ifndef EIGEN_INDEXED_VIEW_METHOD_2ND_PASS +#define EIGEN_INDEXED_VIEW_METHOD_CONST const +#define EIGEN_INDEXED_VIEW_METHOD_TYPE ConstIndexedViewType +#else +#define EIGEN_INDEXED_VIEW_METHOD_CONST +#define EIGEN_INDEXED_VIEW_METHOD_TYPE IndexedViewType +#endif + +#ifndef EIGEN_INDEXED_VIEW_METHOD_2ND_PASS +protected: + +// define some aliases to ease readability + +template +struct IvcRowType : public internal::IndexedViewCompatibleType {}; + +template +struct IvcColType : public internal::IndexedViewCompatibleType {}; + +template +struct IvcType : public internal::IndexedViewCompatibleType {}; + +typedef typename internal::IndexedViewCompatibleType::type IvcIndex; + +template +typename IvcRowType::type +ivcRow(const Indices& indices) const { + return internal::makeIndexedViewCompatible(indices, internal::variable_if_dynamic(derived().rows()),Specialized); +} + +template +typename IvcColType::type +ivcCol(const Indices& indices) const { + return internal::makeIndexedViewCompatible(indices, internal::variable_if_dynamic(derived().cols()),Specialized); +} + +template +typename IvcColType::type +ivcSize(const Indices& indices) const { + return internal::makeIndexedViewCompatible(indices, internal::variable_if_dynamic(derived().size()),Specialized); +} + +public: + +#endif + +template +struct EIGEN_INDEXED_VIEW_METHOD_TYPE { + typedef IndexedView::type, + typename IvcColType::type> type; +}; + +// This is the generic version + +template +typename internal::enable_if::value + && internal::traits::type>::ReturnAsIndexedView, + typename EIGEN_INDEXED_VIEW_METHOD_TYPE::type >::type +operator()(const RowIndices& rowIndices, const ColIndices& colIndices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return typename EIGEN_INDEXED_VIEW_METHOD_TYPE::type + (derived(), ivcRow(rowIndices), ivcCol(colIndices)); +} + +// The following overload returns a Block<> object + +template +typename internal::enable_if::value + && internal::traits::type>::ReturnAsBlock, + typename internal::traits::type>::BlockType>::type +operator()(const RowIndices& rowIndices, const ColIndices& colIndices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + typedef typename internal::traits::type>::BlockType BlockType; + typename IvcRowType::type actualRowIndices = ivcRow(rowIndices); + typename IvcColType::type actualColIndices = ivcCol(colIndices); + return BlockType(derived(), + internal::first(actualRowIndices), + internal::first(actualColIndices), + internal::size(actualRowIndices), + internal::size(actualColIndices)); +} + +// The following overload returns a Scalar + +template +typename internal::enable_if::value + && internal::traits::type>::ReturnAsScalar, + CoeffReturnType >::type +operator()(const RowIndices& rowIndices, const ColIndices& colIndices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return Base::operator()(internal::eval_expr_given_size(rowIndices,rows()),internal::eval_expr_given_size(colIndices,cols())); +} + +#if EIGEN_HAS_STATIC_ARRAY_TEMPLATE + +// The following three overloads are needed to handle raw Index[N] arrays. + +template +IndexedView::type> +operator()(const RowIndicesT (&rowIndices)[RowIndicesN], const ColIndices& colIndices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return IndexedView::type> + (derived(), rowIndices, ivcCol(colIndices)); +} + +template +IndexedView::type, const ColIndicesT (&)[ColIndicesN]> +operator()(const RowIndices& rowIndices, const ColIndicesT (&colIndices)[ColIndicesN]) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return IndexedView::type,const ColIndicesT (&)[ColIndicesN]> + (derived(), ivcRow(rowIndices), colIndices); +} + +template +IndexedView +operator()(const RowIndicesT (&rowIndices)[RowIndicesN], const ColIndicesT (&colIndices)[ColIndicesN]) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return IndexedView + (derived(), rowIndices, colIndices); +} + +#endif // EIGEN_HAS_STATIC_ARRAY_TEMPLATE + +// Overloads for 1D vectors/arrays + +template +typename internal::enable_if< + IsRowMajor && (!(internal::get_compile_time_incr::type>::value==1 || internal::is_valid_index_type::value)), + IndexedView::type> >::type +operator()(const Indices& indices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return IndexedView::type> + (derived(), IvcIndex(0), ivcCol(indices)); +} + +template +typename internal::enable_if< + (!IsRowMajor) && (!(internal::get_compile_time_incr::type>::value==1 || internal::is_valid_index_type::value)), + IndexedView::type,IvcIndex> >::type +operator()(const Indices& indices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return IndexedView::type,IvcIndex> + (derived(), ivcRow(indices), IvcIndex(0)); +} + +template +typename internal::enable_if< + (internal::get_compile_time_incr::type>::value==1) && (!internal::is_valid_index_type::value) && (!symbolic::is_symbolic::value), + VectorBlock::value> >::type +operator()(const Indices& indices) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + typename IvcType::type actualIndices = ivcSize(indices); + return VectorBlock::value> + (derived(), internal::first(actualIndices), internal::size(actualIndices)); +} + +template +typename internal::enable_if::value, CoeffReturnType >::type +operator()(const IndexType& id) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + return Base::operator()(internal::eval_expr_given_size(id,size())); +} + +#if EIGEN_HAS_STATIC_ARRAY_TEMPLATE + +template +typename internal::enable_if >::type +operator()(const IndicesT (&indices)[IndicesN]) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return IndexedView + (derived(), IvcIndex(0), indices); +} + +template +typename internal::enable_if >::type +operator()(const IndicesT (&indices)[IndicesN]) EIGEN_INDEXED_VIEW_METHOD_CONST +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return IndexedView + (derived(), indices, IvcIndex(0)); +} + +#endif // EIGEN_HAS_STATIC_ARRAY_TEMPLATE + +#undef EIGEN_INDEXED_VIEW_METHOD_CONST +#undef EIGEN_INDEXED_VIEW_METHOD_TYPE + +#ifndef EIGEN_INDEXED_VIEW_METHOD_2ND_PASS +#define EIGEN_INDEXED_VIEW_METHOD_2ND_PASS +#include "IndexedViewMethods.h" +#undef EIGEN_INDEXED_VIEW_METHOD_2ND_PASS +#endif + +#else // EIGEN_PARSED_BY_DOXYGEN + +/** + * \returns a generic submatrix view defined by the rows and columns indexed \a rowIndices and \a colIndices respectively. + * + * Each parameter must either be: + * - An integer indexing a single row or column + * - Eigen::all indexing the full set of respective rows or columns in increasing order + * - An ArithmeticSequence as returned by the Eigen::seq and Eigen::seqN functions + * - Any %Eigen's vector/array of integers or expressions + * - Plain C arrays: \c int[N] + * - And more generally any type exposing the following two member functions: + * \code + * operator[]() const; + * size() const; + * \endcode + * where \c stands for any integer type compatible with Eigen::Index (i.e. \c std::ptrdiff_t). + * + * The last statement implies compatibility with \c std::vector, \c std::valarray, \c std::array, many of the Range-v3's ranges, etc. + * + * If the submatrix can be represented using a starting position \c (i,j) and positive sizes \c (rows,columns), then this + * method will returns a Block object after extraction of the relevant information from the passed arguments. This is the case + * when all arguments are either: + * - An integer + * - Eigen::all + * - An ArithmeticSequence with compile-time increment strictly equal to 1, as returned by Eigen::seq(a,b), and Eigen::seqN(a,N). + * + * Otherwise a more general IndexedView object will be returned, after conversion of the inputs + * to more suitable types \c RowIndices' and \c ColIndices'. + * + * For 1D vectors and arrays, you better use the operator()(const Indices&) overload, which behave the same way but taking a single parameter. + * + * See also this question and its answer for an example of how to duplicate coefficients. + * + * \sa operator()(const Indices&), class Block, class IndexedView, DenseBase::block(Index,Index,Index,Index) + */ +template +IndexedView_or_Block +operator()(const RowIndices& rowIndices, const ColIndices& colIndices); + +/** This is an overload of operator()(const RowIndices&, const ColIndices&) for 1D vectors or arrays + * + * \only_for_vectors + */ +template +IndexedView_or_VectorBlock +operator()(const Indices& indices); + +#endif // EIGEN_PARSED_BY_DOXYGEN diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..a0feef8716a4911e2da8011177a38c7dd051b6ae --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h @@ -0,0 +1,152 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// This file is a base class plugin containing matrix specifics coefficient wise functions. + +/** \returns an expression of the Schur product (coefficient wise product) of *this and \a other + * + * Example: \include MatrixBase_cwiseProduct.cpp + * Output: \verbinclude MatrixBase_cwiseProduct.out + * + * \sa class CwiseBinaryOp, cwiseAbs2 + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const EIGEN_CWISE_BINARY_RETURN_TYPE(Derived,OtherDerived,product) +cwiseProduct(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return EIGEN_CWISE_BINARY_RETURN_TYPE(Derived,OtherDerived,product)(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise == operator of *this and \a other + * + * \warning this performs an exact comparison, which is generally a bad idea with floating-point types. + * In order to check for equality between two vectors or matrices with floating-point coefficients, it is + * generally a far better idea to use a fuzzy comparison as provided by isApprox() and + * isMuchSmallerThan(). + * + * Example: \include MatrixBase_cwiseEqual.cpp + * Output: \verbinclude MatrixBase_cwiseEqual.out + * + * \sa cwiseNotEqual(), isApprox(), isMuchSmallerThan() + */ +template +EIGEN_DEVICE_FUNC +inline const CwiseBinaryOp, const Derived, const OtherDerived> +cwiseEqual(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise != operator of *this and \a other + * + * \warning this performs an exact comparison, which is generally a bad idea with floating-point types. + * In order to check for equality between two vectors or matrices with floating-point coefficients, it is + * generally a far better idea to use a fuzzy comparison as provided by isApprox() and + * isMuchSmallerThan(). + * + * Example: \include MatrixBase_cwiseNotEqual.cpp + * Output: \verbinclude MatrixBase_cwiseNotEqual.out + * + * \sa cwiseEqual(), isApprox(), isMuchSmallerThan() + */ +template +EIGEN_DEVICE_FUNC +inline const CwiseBinaryOp, const Derived, const OtherDerived> +cwiseNotEqual(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise min of *this and \a other + * + * Example: \include MatrixBase_cwiseMin.cpp + * Output: \verbinclude MatrixBase_cwiseMin.out + * + * \sa class CwiseBinaryOp, max() + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const OtherDerived> +cwiseMin(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise min of *this and scalar \a other + * + * \sa class CwiseBinaryOp, min() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const ConstantReturnType> +cwiseMin(const Scalar &other) const +{ + return cwiseMin(Derived::Constant(rows(), cols(), other)); +} + +/** \returns an expression of the coefficient-wise max of *this and \a other + * + * Example: \include MatrixBase_cwiseMax.cpp + * Output: \verbinclude MatrixBase_cwiseMax.out + * + * \sa class CwiseBinaryOp, min() + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const OtherDerived> +cwiseMax(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +/** \returns an expression of the coefficient-wise max of *this and scalar \a other + * + * \sa class CwiseBinaryOp, min() + */ +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const ConstantReturnType> +cwiseMax(const Scalar &other) const +{ + return cwiseMax(Derived::Constant(rows(), cols(), other)); +} + + +/** \returns an expression of the coefficient-wise quotient of *this and \a other + * + * Example: \include MatrixBase_cwiseQuotient.cpp + * Output: \verbinclude MatrixBase_cwiseQuotient.out + * + * \sa class CwiseBinaryOp, cwiseProduct(), cwiseInverse() + */ +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseBinaryOp, const Derived, const OtherDerived> +cwiseQuotient(const EIGEN_CURRENT_STORAGE_BASE_CLASS &other) const +{ + return CwiseBinaryOp, const Derived, const OtherDerived>(derived(), other.derived()); +} + +typedef CwiseBinaryOp, const Derived, const ConstantReturnType> CwiseScalarEqualReturnType; + +/** \returns an expression of the coefficient-wise == operator of \c *this and a scalar \a s + * + * \warning this performs an exact comparison, which is generally a bad idea with floating-point types. + * In order to check for equality between two vectors or matrices with floating-point coefficients, it is + * generally a far better idea to use a fuzzy comparison as provided by isApprox() and + * isMuchSmallerThan(). + * + * \sa cwiseEqual(const MatrixBase &) const + */ +EIGEN_DEVICE_FUNC +inline const CwiseScalarEqualReturnType +cwiseEqual(const Scalar& s) const +{ + return CwiseScalarEqualReturnType(derived(), Derived::Constant(rows(), cols(), s), internal::scalar_cmp_op()); +} diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..0514d8f78b5ff44ed659113f85e5aa0e512cc6c5 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h @@ -0,0 +1,95 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// This file is included into the body of the base classes supporting matrix specific coefficient-wise functions. +// This include MatrixBase and SparseMatrixBase. + + +typedef CwiseUnaryOp, const Derived> CwiseAbsReturnType; +typedef CwiseUnaryOp, const Derived> CwiseAbs2ReturnType; +typedef CwiseUnaryOp, const Derived> CwiseArgReturnType; +typedef CwiseUnaryOp, const Derived> CwiseSqrtReturnType; +typedef CwiseUnaryOp, const Derived> CwiseSignReturnType; +typedef CwiseUnaryOp, const Derived> CwiseInverseReturnType; + +/// \returns an expression of the coefficient-wise absolute value of \c *this +/// +/// Example: \include MatrixBase_cwiseAbs.cpp +/// Output: \verbinclude MatrixBase_cwiseAbs.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseAbs,absolute value) +/// +/// \sa cwiseAbs2() +/// +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseAbsReturnType +cwiseAbs() const { return CwiseAbsReturnType(derived()); } + +/// \returns an expression of the coefficient-wise squared absolute value of \c *this +/// +/// Example: \include MatrixBase_cwiseAbs2.cpp +/// Output: \verbinclude MatrixBase_cwiseAbs2.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseAbs2,squared absolute value) +/// +/// \sa cwiseAbs() +/// +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE const CwiseAbs2ReturnType +cwiseAbs2() const { return CwiseAbs2ReturnType(derived()); } + +/// \returns an expression of the coefficient-wise square root of *this. +/// +/// Example: \include MatrixBase_cwiseSqrt.cpp +/// Output: \verbinclude MatrixBase_cwiseSqrt.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseSqrt,square-root) +/// +/// \sa cwisePow(), cwiseSquare() +/// +EIGEN_DEVICE_FUNC +inline const CwiseSqrtReturnType +cwiseSqrt() const { return CwiseSqrtReturnType(derived()); } + +/// \returns an expression of the coefficient-wise signum of *this. +/// +/// Example: \include MatrixBase_cwiseSign.cpp +/// Output: \verbinclude MatrixBase_cwiseSign.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseSign,sign function) +/// +EIGEN_DEVICE_FUNC +inline const CwiseSignReturnType +cwiseSign() const { return CwiseSignReturnType(derived()); } + + +/// \returns an expression of the coefficient-wise inverse of *this. +/// +/// Example: \include MatrixBase_cwiseInverse.cpp +/// Output: \verbinclude MatrixBase_cwiseInverse.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseInverse,inverse) +/// +/// \sa cwiseProduct() +/// +EIGEN_DEVICE_FUNC +inline const CwiseInverseReturnType +cwiseInverse() const { return CwiseInverseReturnType(derived()); } + +/// \returns an expression of the coefficient-wise phase angle of \c *this +/// +/// Example: \include MatrixBase_cwiseArg.cpp +/// Output: \verbinclude MatrixBase_cwiseArg.out +/// +EIGEN_DOC_UNARY_ADDONS(cwiseArg,arg) + +EIGEN_DEVICE_FUNC +inline const CwiseArgReturnType +cwiseArg() const { return CwiseArgReturnType(derived()); } diff --git a/vendor/eigen/include/eigen3/Eigen/src/plugins/ReshapedMethods.h b/vendor/eigen/include/eigen3/Eigen/src/plugins/ReshapedMethods.h new file mode 100644 index 0000000000000000000000000000000000000000..482a6b045ef5a530517f55785b2ce27b448595d8 --- /dev/null +++ b/vendor/eigen/include/eigen3/Eigen/src/plugins/ReshapedMethods.h @@ -0,0 +1,149 @@ + +#ifdef EIGEN_PARSED_BY_DOXYGEN + +/// \returns an expression of \c *this with reshaped sizes. +/// +/// \param nRows the number of rows in the reshaped expression, specified at either run-time or compile-time, or AutoSize +/// \param nCols the number of columns in the reshaped expression, specified at either run-time or compile-time, or AutoSize +/// \tparam Order specifies whether the coefficients should be processed in column-major-order (ColMajor), in row-major-order (RowMajor), +/// or follows the \em natural order of the nested expression (AutoOrder). The default is ColMajor. +/// \tparam NRowsType the type of the value handling the number of rows, typically Index. +/// \tparam NColsType the type of the value handling the number of columns, typically Index. +/// +/// Dynamic size example: \include MatrixBase_reshaped_int_int.cpp +/// Output: \verbinclude MatrixBase_reshaped_int_int.out +/// +/// The number of rows \a nRows and columns \a nCols can also be specified at compile-time by passing Eigen::fix, +/// or Eigen::fix(n) as arguments. In the later case, \c n plays the role of a runtime fallback value in case \c N equals Eigen::Dynamic. +/// Here is an example with a fixed number of rows and columns: +/// \include MatrixBase_reshaped_fixed.cpp +/// Output: \verbinclude MatrixBase_reshaped_fixed.out +/// +/// Finally, one of the sizes parameter can be automatically deduced from the other one by passing AutoSize as in the following example: +/// \include MatrixBase_reshaped_auto.cpp +/// Output: \verbinclude MatrixBase_reshaped_auto.out +/// AutoSize does preserve compile-time sizes when possible, i.e., when the sizes of the input are known at compile time \b and +/// that the other size is passed at compile-time using Eigen::fix as above. +/// +/// \sa class Reshaped, fix, fix(int) +/// +template +EIGEN_DEVICE_FUNC +inline Reshaped +reshaped(NRowsType nRows, NColsType nCols); + +/// This is the const version of reshaped(NRowsType,NColsType). +template +EIGEN_DEVICE_FUNC +inline const Reshaped +reshaped(NRowsType nRows, NColsType nCols) const; + +/// \returns an expression of \c *this with columns (or rows) stacked to a linear column vector +/// +/// \tparam Order specifies whether the coefficients should be processed in column-major-order (ColMajor), in row-major-order (RowMajor), +/// or follows the \em natural order of the nested expression (AutoOrder). The default is ColMajor. +/// +/// This overloads is essentially a shortcut for `A.reshaped(AutoSize,fix<1>)`. +/// +/// - If `Order==ColMajor` (the default), then it returns a column-vector from the stacked columns of \c *this. +/// - If `Order==RowMajor`, then it returns a column-vector from the stacked rows of \c *this. +/// - If `Order==AutoOrder`, then it returns a column-vector with elements stacked following the storage order of \c *this. +/// This mode is the recommended one when the particular ordering of the element is not relevant. +/// +/// Example: +/// \include MatrixBase_reshaped_to_vector.cpp +/// Output: \verbinclude MatrixBase_reshaped_to_vector.out +/// +/// If you want more control, you can still fall back to reshaped(NRowsType,NColsType). +/// +/// \sa reshaped(NRowsType,NColsType), class Reshaped +/// +template +EIGEN_DEVICE_FUNC +inline Reshaped +reshaped(); + +/// This is the const version of reshaped(). +template +EIGEN_DEVICE_FUNC +inline const Reshaped +reshaped() const; + +#else + +// This file is automatically included twice to generate const and non-const versions + +#ifndef EIGEN_RESHAPED_METHOD_2ND_PASS +#define EIGEN_RESHAPED_METHOD_CONST const +#else +#define EIGEN_RESHAPED_METHOD_CONST +#endif + +#ifndef EIGEN_RESHAPED_METHOD_2ND_PASS + +// This part is included once + +#endif + +template +EIGEN_DEVICE_FUNC +inline Reshaped::value, + internal::get_compiletime_reshape_size::value> +reshaped(NRowsType nRows, NColsType nCols) EIGEN_RESHAPED_METHOD_CONST +{ + return Reshaped::value, + internal::get_compiletime_reshape_size::value> + (derived(), + internal::get_runtime_reshape_size(nRows,internal::get_runtime_value(nCols),size()), + internal::get_runtime_reshape_size(nCols,internal::get_runtime_value(nRows),size())); +} + +template +EIGEN_DEVICE_FUNC +inline Reshaped::value, + internal::get_compiletime_reshape_size::value, + internal::get_compiletime_reshape_order::value> +reshaped(NRowsType nRows, NColsType nCols) EIGEN_RESHAPED_METHOD_CONST +{ + return Reshaped::value, + internal::get_compiletime_reshape_size::value, + internal::get_compiletime_reshape_order::value> + (derived(), + internal::get_runtime_reshape_size(nRows,internal::get_runtime_value(nCols),size()), + internal::get_runtime_reshape_size(nCols,internal::get_runtime_value(nRows),size())); +} + +// Views as linear vectors + +EIGEN_DEVICE_FUNC +inline Reshaped +reshaped() EIGEN_RESHAPED_METHOD_CONST +{ + return Reshaped(derived(),size(),1); +} + +template +EIGEN_DEVICE_FUNC +inline Reshaped::value> +reshaped() EIGEN_RESHAPED_METHOD_CONST +{ + EIGEN_STATIC_ASSERT(Order==RowMajor || Order==ColMajor || Order==AutoOrder, INVALID_TEMPLATE_PARAMETER); + return Reshaped::value> + (derived(), size(), 1); +} + +#undef EIGEN_RESHAPED_METHOD_CONST + +#ifndef EIGEN_RESHAPED_METHOD_2ND_PASS +#define EIGEN_RESHAPED_METHOD_2ND_PASS +#include "ReshapedMethods.h" +#undef EIGEN_RESHAPED_METHOD_2ND_PASS +#endif + +#endif // EIGEN_PARSED_BY_DOXYGEN diff --git a/vendor/eigen/include/eigen3/signature_of_eigen3_matrix_library b/vendor/eigen/include/eigen3/signature_of_eigen3_matrix_library new file mode 100644 index 0000000000000000000000000000000000000000..80aaf4621fef3c9455f91c375926cad1ec62d527 --- /dev/null +++ b/vendor/eigen/include/eigen3/signature_of_eigen3_matrix_library @@ -0,0 +1 @@ +This file is just there as a signature to help identify directories containing Eigen3. When writing a script looking for Eigen3, just look for this file. This is especially useful to help disambiguate with Eigen2...