├── .gitattributes ├── examples ├── Example.png └── example_readme.py ├── docs ├── api.rst ├── index.rst ├── make.bat ├── Makefile └── conf.py ├── wheelhouse ├── .gitignore └── debug_wheel.py ├── .gitignore ├── tests ├── test_import.py ├── conftest.py └── test_extension.py ├── pyproject.toml ├── RELEASE.md ├── .github ├── scripts │ └── bump_version.py └── workflows │ └── build-wheels.yml ├── README.md ├── cmake └── FindNumPy.cmake ├── setup.py ├── LICENSE └── src └── main.cpp /.gitattributes: -------------------------------------------------------------------------------- 1 | *.whl binary 2 | -------------------------------------------------------------------------------- /examples/Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bgailleton/TVD_Condat2013/HEAD/examples/Example.png -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | .. automodule:: TVDCondat2013 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /wheelhouse/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore build artefacts generated by cibuildwheel 2 | *.whl 3 | SHA256SUMS 4 | 5 | # Allow utility scripts to remain tracked 6 | !debug_wheel.py 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info/ 2 | .eggs/ 3 | .ipynb_checkpoints/ 4 | dist/ 5 | build/ 6 | *.py[cod] 7 | *.so 8 | tmp/ 9 | 10 | # OS X 11 | .DS_Store 12 | 13 | # Wheel artefacts are generated during CI builds 14 | wheelhouse/*.whl 15 | wheelhouse/SHA256SUMS 16 | -------------------------------------------------------------------------------- /tests/test_import.py: -------------------------------------------------------------------------------- 1 | """Basic import test to ensure the compiled extension loads.""" 2 | 3 | import os 4 | import sys 5 | import importlib 6 | 7 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 8 | 9 | 10 | def test_extension_imports(): 11 | """The module should expose both TVD variants.""" 12 | module = importlib.import_module('TVDCondat2013') 13 | assert hasattr(module, 'tvd_2013') 14 | assert hasattr(module, 'tvd_2017') 15 | assert hasattr(module, 'tvd_tautstring') 16 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Pytest configuration ensuring the native extension is built before tests.""" 2 | 3 | from __future__ import annotations 4 | 5 | import subprocess 6 | import sys 7 | from pathlib import Path 8 | 9 | try: 10 | import sysconfig 11 | except ImportError as exc: # pragma: no cover - Python always provides sysconfig 12 | raise RuntimeError("sysconfig module missing") from exc 13 | 14 | 15 | def _build_extension() -> None: 16 | root = Path(__file__).resolve().parent.parent 17 | ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") 18 | if ext_suffix is None: 19 | raise RuntimeError("Cannot determine extension suffix") 20 | 21 | target = root / f"TVDCondat2013{ext_suffix}" 22 | if target.exists(): 23 | return 24 | 25 | subprocess.run( 26 | [sys.executable, "setup.py", "build_ext", "--inplace"], 27 | cwd=root, 28 | check=True, 29 | ) 30 | 31 | 32 | _build_extension() 33 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=68", 4 | "wheel", 5 | "pybind11>=2.0.1", 6 | "numpy", 7 | ] 8 | build-backend = "setuptools.build_meta" 9 | 10 | [project] 11 | name = "TVDCondat2013" 12 | version = "0.0.9" 13 | description = "Python port of Condat (2013) 1D Total Variation Denoising using pybind11 and NumPy" 14 | readme = "README.md" 15 | authors = [ 16 | { name = "Boris Gailleton", email = "b.gailleton@sms.ed.ac.uk" } 17 | ] 18 | license = { file = "LICENSE" } 19 | requires-python = ">=3.8" 20 | dependencies = ["numpy"] 21 | urls = { "Homepage" = "https://github.com/bgailleton/TVDCondat2013" } 22 | 23 | [tool.setuptools] 24 | # keep legacy setup.py build logic for pybind11 extension 25 | include-package-data = false 26 | license-files = ["LICENSE"] 27 | 28 | 29 | [tool.setuptools.packages.find] 30 | where = ["."] 31 | exclude = ["tests*", "examples*"] 32 | 33 | [tool.pybind11] 34 | # optional, but helps cibuildwheel detect pybind11 usage 35 | default-include = true 36 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | # Release checklist 2 | 3 | 1. Update the version number in `setup.py` and `docs/conf.py` using the `bump_version.py` 4 | helper (or edit both files manually if preparing a one-off hotfix). Commit the change 5 | before starting the wheel build workflow. 6 | 2. Run `python -m build` locally to confirm the sdist and the platform wheel can be 7 | produced and pass `python wheelhouse/debug_wheel.py dist` to verify the archives. 8 | 3. Trigger the "Release wheels" workflow in GitHub Actions. The workflow invokes 9 | `cibuildwheel` on Linux, macOS, and Windows, validates the resulting archives with 10 | `wheelhouse/debug_wheel.py`, and publishes the release artefacts. If the 11 | validator reports corruption, wipe the workspace artefacts (including any 12 | previously committed wheels), rerun the workflow, and allow it to rebuild the 13 | archives from source. 14 | 4. **Do not edit wheels in place.** Any post-processing that rewrites files inside a wheel 15 | (for example running `strip` or an antivirus scanner on `TVDCondat2013*.so/.pyd` inside 16 | the archive) changes the payload without updating the zip metadata. The debug script will 17 | report a CRC mismatch and the wheel will be rejected by `pip`. If you need a modified 18 | binary, rebuild the wheel from source instead of mutating an existing artefact. 19 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | TVDCondat2013 Documentation 2 | ======================================= 3 | 4 | TVDCondat2013 provides fast 1‑D total variation denoising routines based on 5 | Laurent Condat's algorithms. The core is written in C++ and exposed to Python 6 | through pybind11, offering a tiny, dependency‑free extension. Four 7 | implementations are available: 8 | 9 | * ``tvd_2013`` — direct port of the 2013 algorithm. 10 | * ``tvd_2017`` — an accelerated variant derived from Condat's 2017 work with 11 | improved convergence on large signals. 12 | * ``tvd_tautstring`` — taut string algorithm adapted from Lutz Dümbgen's Matlab 13 | code. 14 | * ``fused_lasso`` — fused lasso signal approximator with an additional 15 | :math:`\ell_1` penalty term. 16 | 17 | Quick start 18 | ----------- 19 | 20 | .. code-block:: python 21 | 22 | import numpy as np 23 | from TVDCondat2013 import ( 24 | fused_lasso, 25 | tvd_2013, 26 | tvd_2017, 27 | tvd_tautstring, 28 | ) 29 | 30 | noisy = np.random.randn(100) 31 | denoised = tvd_2013(noisy, 10.0) # 2013 algorithm 32 | denoised_fast = tvd_2017(noisy, 10.0) # 2017 algorithm 33 | denoised_ts = tvd_tautstring(noisy, 10.0) # taut string algorithm 34 | denoised_fl = fused_lasso(noisy, 10.0, 1.0) # fused lasso variant 35 | 36 | See the :doc:`api` reference for the complete list of functions and their 37 | arguments. 38 | 39 | References 40 | ---------- 41 | 42 | * L. Condat, "A Direct Algorithm for 1D Total Variation Denoising," *IEEE 43 | Signal Processing Letters*, 2013. 44 | * L. Condat, "Fast Projection onto the Simplex and the L1 Ball," *Mathematical 45 | Programming*, 2017. 46 | * L. Dümbgen, Matlab code for the taut string algorithm, University of Bern. 47 | 48 | .. toctree:: 49 | :maxdepth: 1 50 | 51 | api 52 | 53 | -------------------------------------------------------------------------------- /.github/scripts/bump_version.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | from pathlib import Path 4 | 5 | if len(sys.argv) != 2: 6 | raise SystemExit("usage: bump_version.py ") 7 | 8 | increment = sys.argv[1] 9 | 10 | allowed_increments = { 11 | "+1": "major", 12 | "+0.1": "minor", 13 | "+0.0.1": "patch", 14 | } 15 | 16 | if increment not in allowed_increments: 17 | choices = ", ".join(sorted(allowed_increments)) 18 | raise SystemExit(f"increment must be one of: {choices}") 19 | 20 | setup_path = Path("setup.py") 21 | conf_path = Path("docs/conf.py") 22 | 23 | def read_version(text): 24 | m = re.search(r"__version__\s*=\s*['\"](\d+)\.(\d+)\.(\d+)['\"]", text) 25 | if not m: 26 | raise RuntimeError("version string not found") 27 | return [int(part) for part in m.groups()] 28 | 29 | major, minor, patch = version_parts = read_version(setup_path.read_text()) 30 | 31 | kind = allowed_increments[increment] 32 | 33 | if kind == "major": 34 | major += 1 35 | minor = 0 36 | patch = 0 37 | elif kind == "minor": 38 | minor += 1 39 | patch = 0 40 | else: 41 | patch += 1 42 | 43 | version_parts = [major, minor, patch] 44 | new_version = ".".join(str(p) for p in version_parts) 45 | 46 | setup_text = re.sub( 47 | r"(__version__\s*=\s*['\"])([^'\"]+)(['\"])", 48 | lambda m: f"{m.group(1)}{new_version}{m.group(3)}", 49 | setup_path.read_text(), 50 | ) 51 | setup_path.write_text(setup_text) 52 | 53 | conf_text = conf_path.read_text() 54 | conf_text = re.sub( 55 | r"(version = u')([^']+)('\n)", 56 | lambda m: f"{m.group(1)}{new_version}{m.group(3)}", 57 | conf_text, 58 | ) 59 | conf_text = re.sub( 60 | r"(release = u')([^']+)('\n)", 61 | lambda m: f"{m.group(1)}{new_version}{m.group(3)}", 62 | conf_text, 63 | ) 64 | 65 | conf_path.write_text(conf_text) 66 | 67 | print(new_version) 68 | -------------------------------------------------------------------------------- /tests/test_extension.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | """Smoke tests for the TVDCondat2013 extension.""" 3 | 4 | import os 5 | import sys 6 | import numpy as np 7 | 8 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 9 | import TVDCondat2013 as tvd 10 | 11 | 12 | def test_tvd_preserves_dtype_and_values(): 13 | """Lambda zero should yield an identical array with the same dtype.""" 14 | x32 = np.array([0, 1, 2, 3], dtype=np.float32) 15 | for func in (tvd.tvd_2013, tvd.tvd_2017, tvd.tvd_tautstring): 16 | y32 = func(x32, np.float32(0.0)) 17 | assert y32.dtype == np.float32 18 | np.testing.assert_array_equal(y32, x32) 19 | 20 | x64 = np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float64) 21 | for func in (tvd.tvd_2013, tvd.tvd_2017, tvd.tvd_tautstring): 22 | y64 = func(x64, 0.0) 23 | assert y64.dtype == np.float64 24 | np.testing.assert_array_equal(y64, x64) 25 | 26 | 27 | def test_fused_lasso_identity(): 28 | """Lambda and mu zero should return the original signal.""" 29 | x32 = np.array([0, 1, 2, 3], dtype=np.float32) 30 | y32 = tvd.fused_lasso(x32, np.float32(0.0), np.float32(0.0)) 31 | assert y32.dtype == np.float32 32 | np.testing.assert_array_equal(y32, x32) 33 | 34 | x64 = np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float64) 35 | y64 = tvd.fused_lasso(x64, 0.0, 0.0) 36 | assert y64.dtype == np.float64 37 | np.testing.assert_array_equal(y64, x64) 38 | 39 | 40 | def _total_variation(arr: np.ndarray) -> float: 41 | """Compute the total variation of a 1-D array.""" 42 | return np.sum(np.abs(np.diff(arr))) 43 | 44 | 45 | def test_tvd_reduces_variation(): 46 | """Denoising should not increase total variation.""" 47 | x32 = np.array([0, 2, 1, 3, 0], dtype=np.float32) 48 | for func in (tvd.tvd_2013, tvd.tvd_2017, tvd.tvd_tautstring): 49 | y32 = func(x32, np.float32(0.5)) 50 | assert _total_variation(y32) <= _total_variation(x32) + 1e-6 51 | 52 | x64 = np.array([0, 2, 1, 3, 0], dtype=np.float64) 53 | for func in (tvd.tvd_2013, tvd.tvd_2017, tvd.tvd_tautstring): 54 | y64 = func(x64, 0.5) 55 | assert _total_variation(y64) <= _total_variation(x64) + 1e-12 56 | 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TVDCondat2013 2 | ============== 3 | 4 | TVDCondat2013 is a python portage of the 1D Total Variation Denoising algorithm from Condat 2013 and subsequent improvements: _A Direct Algorithm for 1D Total Variation Denoising_ (Sign. Proc. Letters, DOI:10.1109/LSP.2013.2278339) using pybind11 to bind C++ and NumPy directly. 5 | 6 | This is a minimal implementation with `pybind11` 7 | 8 | 9 | The `c++` core code has been adapted from `C` version available on the website of the manuscript orignal authors: [The Paper](https://lcondat.github.io/publis/Condat-fast_TV-SPL-2013.pdf) 10 | 11 | 12 | *Cite it if you use it.* 13 | 14 | 15 | 16 | Straightfoward API 17 | ------------ 18 | 19 | The following denoising of a `numpy` array are implemented. The 20 | original 2013 algorithm, the faster 2017 variant, a taut string algorithm, and 21 | a fused lasso variant with an additional :math:`\ell_1` penalty are exposed: 22 | 23 | generic api: `method(numpy_array_1D, scalar_regulator)` 24 | 25 | ``` 26 | from TVDCondat2013 import fused_lasso, tvd_2013, tvd_2017, tvd_tautstring 27 | ... 28 | denoised_v1 = tvd_2013(MyNumpyArray, lambda_TVD) # 2013 algorithm 29 | denoised_v2 = tvd_2017(MyNumpyArray, lambda_TVD) # 2017 algorithm 30 | denoised_ts = tvd_tautstring(MyNumpyArray, lambda_TVD) # taut string 31 | denoised_fl = fused_lasso(MyNumpyArray, lambda_TVD, mu_L1) # fused lasso 32 | ... 33 | 34 | ``` 35 | 36 | Run `python examples/example_readme.py` to generate a figure comparing the 37 | original, noisy, and denoised signals using all algorithms. The script builds a 38 | piecewise-constant signal, corrupts it with Gaussian noise, denoises it with 39 | ``tvd_2013``, ``tvd_2017``, ``tvd_tautstring`` and ``fused_lasso``, and plots 40 | the results in aligned subplots, saving the figure as `examples/Example.png`. 41 | 42 | 43 | Installation 44 | ------------ 45 | 46 | Using `pip`: 47 | 48 | `pip install tvdcondat2013` 49 | 50 | Binaries are CI using github action for `python` 3.9-3.13, for Linux, Windows (64 bits) and MacOS (both ARM and intel). 51 | 52 | From source, install `numpy, pybind11, scikit-build`, clone this repo and `pip install .` in the directory. 53 | 54 | Copyright 55 | --------- 56 | 57 | Portions of this software are Copyright (c) 2013-2025 Laurent Condat. 58 | The taut string algorithm is adapted from Matlab code by Lutz Dümbgen. 59 | 60 | Full info [here](https://lcondat.github.io/software.html) 61 | 62 | License: 63 | -------- 64 | 65 | CeCILL 2.1: strong copyleft open-source 66 | 67 | Author: 68 | ------- 69 | 70 | Boris Gailleton - boris.gailleton@univ-rennes.fr 71 | 72 | Université de Rennes - University of Edinburgh - GFZ Potsdam 73 | -------------------------------------------------------------------------------- /examples/example_readme.py: -------------------------------------------------------------------------------- 1 | """Example illustrating 1D denoising with :mod:`TVDCondat2013`. 2 | 3 | The script generates a piecewise-constant signal, corrupts it with Gaussian 4 | noise, denoises it with all available algorithms, and saves a figure comparing 5 | the results. 6 | """ 7 | 8 | import matplotlib 9 | 10 | matplotlib.use("Agg") 11 | import numpy as np 12 | from matplotlib import pyplot as plt 13 | from pathlib import Path 14 | 15 | from TVDCondat2013 import fused_lasso, tvd_2013, tvd_2017, tvd_tautstring 16 | 17 | 18 | def main() -> None: 19 | """Generate the figure demonstrating 1-D total-variation denoising.""" 20 | # ------------------------------------------------------------------ 21 | # Generate a piecewise-constant signal corrupted by Gaussian noise 22 | # ------------------------------------------------------------------ 23 | rng = np.random.default_rng(0) 24 | segment_values = [0, 4, 1, 3, 0] 25 | segment_length = 100 26 | clean = np.repeat(segment_values, segment_length) 27 | noisy = clean + rng.normal(scale=1.0, size=clean.size) 28 | 29 | # Denoise the 1-D signal with a reasonable lambda 30 | lambda_tvd = 10. 31 | lambda_tvd2 = 1.5 32 | mu_l1 = 0.5 33 | denoised_v1 = tvd_2013(noisy, lambda_tvd) 34 | denoised_v2 = tvd_2017(noisy, lambda_tvd2) 35 | denoised_ts = tvd_tautstring(noisy, lambda_tvd) 36 | denoised_fl = fused_lasso(noisy, lambda_tvd, mu_l1) 37 | 38 | # ------------------------------------------------------------------ 39 | # Plot original, noisy, and denoised signals in separate panels 40 | # ------------------------------------------------------------------ 41 | x = np.arange(clean.size) 42 | fig, axes = plt.subplots(6, 1, sharex=True, figsize=(8, 12)) 43 | 44 | axes[0].plot(x, clean, color="k", lw=1) 45 | axes[0].set_ylabel("Amplitude") 46 | axes[0].set_title("Original signal") 47 | 48 | axes[1].plot(x, noisy, color="0.6", lw=1) 49 | axes[1].set_ylabel("Amplitude") 50 | axes[1].set_title("Noisy signal") 51 | 52 | axes[2].plot(x, noisy, color="0.6", lw=1) 53 | axes[2].plot(x, denoised_v1, color="C1", lw=1.5) 54 | axes[2].set_ylabel("Amplitude") 55 | axes[2].set_title(f"tvd_2013 (lambda={lambda_tvd})") 56 | 57 | axes[3].plot(x, noisy, color="0.6", lw=1) 58 | axes[3].plot(x, denoised_v2, color="C2", lw=1.5) 59 | axes[3].set_ylabel("Amplitude") 60 | axes[3].set_title(f"tvd_2017 (lambda={lambda_tvd2})") 61 | 62 | axes[4].plot(x, noisy, color="0.6", lw=1) 63 | axes[4].plot(x, denoised_ts, color="C3", lw=1.5) 64 | axes[4].set_ylabel("Amplitude") 65 | axes[4].set_title(f"tvd_tautstring (lambda={lambda_tvd})") 66 | 67 | axes[5].plot(x, noisy, color="0.6", lw=1) 68 | axes[5].plot(x, denoised_fl, color="C4", lw=1.5) 69 | axes[5].set_xlabel("Sample") 70 | axes[5].set_ylabel("Amplitude") 71 | axes[5].set_title( 72 | f"fused_lasso (lambda={lambda_tvd}, mu={mu_l1})" 73 | ) 74 | 75 | fig.tight_layout() 76 | output_path = Path(__file__).with_name("Example.png") 77 | fig.savefig(output_path, dpi=300) 78 | plt.close(fig) 79 | 80 | 81 | if __name__ == "__main__": # pragma: no cover - example script 82 | main() 83 | 84 | -------------------------------------------------------------------------------- /wheelhouse/debug_wheel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Utilities for validating wheel archives produced by the CI.""" 3 | 4 | from __future__ import annotations 5 | 6 | import sys 7 | import zipfile 8 | from pathlib import Path 9 | from typing import Iterable 10 | 11 | import zlib 12 | 13 | HEADER_SIGNATURE = b"PK\x03\x04" 14 | 15 | 16 | def _read_ignoring_crc(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes: 17 | with zf.open(info) as handle: 18 | handle._update_crc = lambda *_args, **_kwargs: None # type: ignore[attr-defined] 19 | return handle.read() 20 | 21 | 22 | def _nearest_header_offset(path: Path, expected: int, search: int = 64) -> int | None: 23 | start = max(0, expected - search) 24 | with path.open("rb") as fh: 25 | fh.seek(start) 26 | blob = fh.read(search * 2) 27 | idx = blob.find(HEADER_SIGNATURE) 28 | if idx == -1: 29 | return None 30 | return start + idx 31 | 32 | 33 | def _check_member(path: Path, zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> Iterable[str]: 34 | try: 35 | with zf.open(info) as handle: 36 | for _ in iter(lambda: handle.read(1 << 14), b""): 37 | pass 38 | except zipfile.BadZipFile as exc: 39 | message = str(exc) 40 | details: list[str] = [] 41 | if "Bad CRC-32" in message: 42 | payload = _read_ignoring_crc(zf, info) 43 | actual_crc = zlib.crc32(payload) & 0xFFFFFFFF 44 | details.append( 45 | "CRC mismatch: expected 0x%08x but archive contains 0x%08x" 46 | % (info.CRC, actual_crc) 47 | ) 48 | details.append( 49 | "The member was modified after the wheel was built. Rebuild the wheel instead of editing it in place." 50 | ) 51 | elif "Bad magic number" in message: 52 | actual = _nearest_header_offset(path, info.header_offset) 53 | if actual is None: 54 | details.append( 55 | "Local file header missing at offset %d; the archive is truncated." % info.header_offset 56 | ) 57 | else: 58 | delta = actual - info.header_offset 59 | details.append( 60 | "Local file header shifted by %d bytes (expected %d, found %d)." 61 | % (delta, info.header_offset, actual) 62 | ) 63 | details.append( 64 | "This indicates a post-processing step rewrote compressed data without updating zip metadata." 65 | ) 66 | else: 67 | details.append(message) 68 | yield f"{info.filename}: {'; '.join(details)}" 69 | 70 | 71 | def check_wheels(directory: str) -> int: 72 | """Validate wheels and return 0 if all are OK else 1.""" 73 | 74 | status = 0 75 | for wheel in sorted(Path(directory).glob("*.whl")): 76 | try: 77 | with zipfile.ZipFile(wheel) as zf: 78 | issues = [msg for info in zf.infolist() for msg in _check_member(wheel, zf, info)] 79 | if issues: 80 | status = 1 81 | print(f"{wheel.name}: CORRUPTED") 82 | for msg in issues: 83 | print(f" - {msg}") 84 | else: 85 | print(f"{wheel.name}: OK") 86 | except zipfile.BadZipFile as exc: 87 | print(f"{wheel.name}: not a valid zip archive ({exc})") 88 | status = 1 89 | return status 90 | 91 | 92 | if __name__ == "__main__": 93 | target_dir = sys.argv[1] if len(sys.argv) > 1 else "." 94 | sys.exit(check_wheels(target_dir)) 95 | -------------------------------------------------------------------------------- /cmake/FindNumPy.cmake: -------------------------------------------------------------------------------- 1 | # - Find the NumPy libraries 2 | # This module finds if NumPy is installed, and sets the following variables 3 | # indicating where it is. 4 | # 5 | # TODO: Update to provide the libraries and paths for linking npymath lib. 6 | # 7 | # NUMPY_FOUND - was NumPy found 8 | # NUMPY_VERSION - the version of NumPy found as a string 9 | # NUMPY_VERSION_MAJOR - the major version number of NumPy 10 | # NUMPY_VERSION_MINOR - the minor version number of NumPy 11 | # NUMPY_VERSION_PATCH - the patch version number of NumPy 12 | # NUMPY_VERSION_DECIMAL - e.g. version 1.6.1 is 10601 13 | # NUMPY_INCLUDE_DIRS - path to the NumPy include files 14 | 15 | #============================================================================ 16 | # Copyright 2012 Continuum Analytics, Inc. 17 | # 18 | # MIT License 19 | # 20 | # Permission is hereby granted, free of charge, to any person obtaining 21 | # a copy of this software and associated documentation files 22 | # (the "Software"), to deal in the Software without restriction, including 23 | # without limitation the rights to use, copy, modify, merge, publish, 24 | # distribute, sublicense, and/or sell copies of the Software, and to permit 25 | # persons to whom the Software is furnished to do so, subject to 26 | # the following conditions: 27 | # 28 | # The above copyright notice and this permission notice shall be included 29 | # in all copies or substantial portions of the Software. 30 | # 31 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 32 | # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 33 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 34 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 35 | # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 36 | # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 37 | # OTHER DEALINGS IN THE SOFTWARE. 38 | # 39 | #============================================================================ 40 | 41 | # Finding NumPy involves calling the Python interpreter 42 | if(NumPy_FIND_REQUIRED) 43 | find_package(PythonInterp REQUIRED) 44 | else() 45 | find_package(PythonInterp) 46 | endif() 47 | 48 | if(NOT PYTHONINTERP_FOUND) 49 | set(NUMPY_FOUND FALSE) 50 | endif() 51 | 52 | execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-c" 53 | "import numpy as n; print(n.__version__); print(n.get_include());" 54 | RESULT_VARIABLE _NUMPY_SEARCH_SUCCESS 55 | OUTPUT_VARIABLE _NUMPY_VALUES 56 | ERROR_VARIABLE _NUMPY_ERROR_VALUE 57 | OUTPUT_STRIP_TRAILING_WHITESPACE) 58 | 59 | if(NOT _NUMPY_SEARCH_SUCCESS MATCHES 0) 60 | if(NumPy_FIND_REQUIRED) 61 | message(FATAL_ERROR 62 | "NumPy import failure:\n${_NUMPY_ERROR_VALUE}") 63 | endif() 64 | set(NUMPY_FOUND FALSE) 65 | endif() 66 | 67 | # Convert the process output into a list 68 | string(REGEX REPLACE ";" "\\\\;" _NUMPY_VALUES ${_NUMPY_VALUES}) 69 | string(REGEX REPLACE "\n" ";" _NUMPY_VALUES ${_NUMPY_VALUES}) 70 | list(GET _NUMPY_VALUES 0 NUMPY_VERSION) 71 | list(GET _NUMPY_VALUES 1 NUMPY_INCLUDE_DIRS) 72 | 73 | # Make sure all directory separators are '/' 74 | string(REGEX REPLACE "\\\\" "/" NUMPY_INCLUDE_DIRS ${NUMPY_INCLUDE_DIRS}) 75 | 76 | # Get the major and minor version numbers 77 | string(REGEX REPLACE "\\." ";" _NUMPY_VERSION_LIST ${NUMPY_VERSION}) 78 | list(GET _NUMPY_VERSION_LIST 0 NUMPY_VERSION_MAJOR) 79 | list(GET _NUMPY_VERSION_LIST 1 NUMPY_VERSION_MINOR) 80 | list(GET _NUMPY_VERSION_LIST 2 NUMPY_VERSION_PATCH) 81 | string(REGEX MATCH "[0-9]*" NUMPY_VERSION_PATCH ${NUMPY_VERSION_PATCH}) 82 | math(EXPR NUMPY_VERSION_DECIMAL 83 | "(${NUMPY_VERSION_MAJOR} * 10000) + (${NUMPY_VERSION_MINOR} * 100) + ${NUMPY_VERSION_PATCH}") 84 | 85 | find_package_message(NUMPY 86 | "Found NumPy: version \"${NUMPY_VERSION}\" ${NUMPY_INCLUDE_DIRS}" 87 | "${NUMPY_INCLUDE_DIRS}${NUMPY_VERSION}") 88 | 89 | set(NUMPY_FOUND TRUE) 90 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | from setuptools.command.build_ext import build_ext 3 | import sys 4 | import os 5 | import setuptools 6 | 7 | __version__ = '0.0.18' 8 | 9 | 10 | class get_pybind_include(object): 11 | """Helper class to determine the pybind11 include path 12 | 13 | The purpose of this class is to postpone importing pybind11 14 | until it is actually installed, so that the ``get_include()`` 15 | method can be invoked. """ 16 | 17 | def __init__(self, user=False): 18 | self.user = user 19 | 20 | def __str__(self): 21 | import pybind11 22 | return pybind11.get_include(self.user) 23 | 24 | 25 | class get_numpy_include(object): 26 | """Helper class to determine the numpy include path 27 | 28 | The purpose of this class is to postpone importing numpy 29 | until it is actually installed, so that the ``get_include()`` 30 | method can be invoked. """ 31 | 32 | def __init__(self): 33 | pass 34 | 35 | def __str__(self): 36 | import numpy as np 37 | return np.get_include() 38 | 39 | 40 | ext_modules = [ 41 | Extension( 42 | 'TVDCondat2013', 43 | ['src/main.cpp'], 44 | include_dirs=[ 45 | # Path to pybind11 headers 46 | get_pybind_include(), 47 | get_pybind_include(user=True), 48 | get_numpy_include(), 49 | os.path.join(sys.prefix, 'include'), 50 | os.path.join(sys.prefix, 'Library', 'include') 51 | ], 52 | language='c++' 53 | ), 54 | ] 55 | 56 | 57 | def has_flag(compiler, flagname): 58 | """Return a boolean indicating whether a flag name is supported on 59 | the specified compiler. 60 | """ 61 | import tempfile 62 | with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: 63 | f.write('int main (int argc, char **argv) { return 0; }') 64 | try: 65 | compiler.compile([f.name], extra_postargs=[flagname]) 66 | except setuptools.distutils.errors.CompileError: 67 | return False 68 | return True 69 | 70 | 71 | def cpp_flag(compiler): 72 | """Return the -std=c++14 compiler flag and errors when the flag is 73 | no available. 74 | """ 75 | if has_flag(compiler, '-std=c++14'): 76 | return '-std=c++14' 77 | else: 78 | raise RuntimeError('C++14 support is required') 79 | 80 | 81 | class BuildExt(build_ext): 82 | """A custom build extension for adding compiler-specific options.""" 83 | c_opts = { 84 | 'msvc': ['/EHsc'], 85 | 'unix': [], 86 | } 87 | 88 | if sys.platform == 'darwin': 89 | c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7'] 90 | 91 | def build_extensions(self): 92 | ct = self.compiler.compiler_type 93 | opts = self.c_opts.get(ct, []) 94 | if ct == 'unix': 95 | opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version()) 96 | opts.append(cpp_flag(self.compiler)) 97 | if has_flag(self.compiler, '-fvisibility=hidden'): 98 | opts.append('-fvisibility=hidden') 99 | elif ct == 'msvc': 100 | opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()) 101 | for ext in self.extensions: 102 | ext.extra_compile_args = opts 103 | build_ext.build_extensions(self) 104 | 105 | setup( 106 | name='TVDCondat2013', 107 | version=__version__, 108 | author='Boris Gailleton', 109 | author_email='b.gailleton@sms.ed.ac.uk', 110 | url='https://github.com/bgailleton/TVDCondat2013', 111 | description= 'TVDCondat2013 is a python portage of the 1D Total Variation Denoising algorithm from Condat 2013: "A Direct Algorithm for 1D Total Variation Denoising" (Sign. Proc. Letters) using pybind11 to bind C++ and NumPy.', 112 | long_description='', 113 | ext_modules=ext_modules, 114 | setup_requires=['pybind11>=2.0.1', 'numpy'], 115 | install_requires=['numpy'], 116 | cmdclass={'build_ext': BuildExt}, 117 | zip_safe=False, 118 | ) 119 | -------------------------------------------------------------------------------- /.github/workflows/build-wheels.yml: -------------------------------------------------------------------------------- 1 | name: Release wheels 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | increment: 7 | description: "Version bump (+1=major, +0.1=minor, +0.0.1=patch)" 8 | required: true 9 | default: "+0.0.1" 10 | type: choice 11 | options: ["+1", "+0.1", "+0.0.1"] 12 | 13 | permissions: 14 | contents: write 15 | 16 | jobs: 17 | prepare: 18 | runs-on: ubuntu-latest 19 | outputs: 20 | version: ${{ steps.bump.outputs.version }} 21 | sha: ${{ steps.commit.outputs.sha }} 22 | steps: 23 | - uses: actions/checkout@v4 24 | with: 25 | fetch-depth: 0 26 | 27 | - name: Bump version 28 | id: bump 29 | run: | 30 | new_version=$(python .github/scripts/bump_version.py ${{ inputs.increment }}) 31 | echo "version=$new_version" >> "$GITHUB_OUTPUT" 32 | 33 | - name: Commit version and tag 34 | id: commit 35 | run: | 36 | git config user.name "${GITHUB_ACTOR}" 37 | git config user.email "${GITHUB_ACTOR}@users.noreply.github.com" 38 | git commit -am "Bump version to ${{ steps.bump.outputs.version }}" 39 | git tag "v${{ steps.bump.outputs.version }}" 40 | git push origin HEAD --tags 41 | echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" 42 | 43 | build: 44 | name: Build wheels on ${{ matrix.os }} 45 | needs: prepare 46 | runs-on: ${{ matrix.os }} 47 | strategy: 48 | fail-fast: false 49 | matrix: 50 | os: ["ubuntu-latest", "windows-latest", "macos-13", "macos-14"] 51 | steps: 52 | - uses: actions/checkout@v4 53 | with: 54 | ref: ${{ needs.prepare.outputs.sha }} 55 | 56 | - uses: actions/setup-python@v5 57 | with: 58 | python-version: "3.11" 59 | 60 | - name: Install cibuildwheel 61 | run: | 62 | python -m pip install --upgrade pip 63 | pip install --upgrade cibuildwheel 64 | 65 | - name: Clean outputs 66 | if: runner.os != 'Windows' 67 | run: rm -rf wheelhouse build dist *.egg-info || true 68 | 69 | - name: Clean outputs (Windows) 70 | if: runner.os == 'Windows' 71 | shell: cmd 72 | run: | 73 | rmdir /s /q wheelhouse 2>nul || exit /b 0 74 | rmdir /s /q build 2>nul || exit /b 0 75 | rmdir /s /q dist 2>nul || exit /b 0 76 | for /d %%G in (*.egg-info) do rmdir /s /q "%%G" 77 | 78 | 79 | - name: Build wheels 80 | run: cibuildwheel --output-dir wheelhouse 81 | env: 82 | CIBW_BUILD: "cp38-* cp39-* cp310-* cp311-* cp312-* cp313-*" 83 | CIBW_ARCHS_LINUX: "x86_64" 84 | CIBW_ARCHS_MACOS: "x86_64 arm64" 85 | CIBW_ARCHS_WINDOWS: "AMD64 x86" 86 | CIBW_REPAIR_WHEEL_COMMAND_LINUX: "auditwheel repair -w {dest_dir} {wheel}" 87 | 88 | - name: Upload wheel artifacts 89 | uses: actions/upload-artifact@v4 90 | with: 91 | name: wheels-${{ matrix.os }} 92 | path: wheelhouse/*.whl 93 | if-no-files-found: error 94 | compression-level: 0 95 | 96 | publish: 97 | name: Publish to PyPI (Linux only) 98 | needs: [build, prepare] 99 | runs-on: ubuntu-latest 100 | environment: pypi 101 | permissions: 102 | id-token: write 103 | contents: read 104 | steps: 105 | - uses: actions/download-artifact@v4 106 | with: 107 | pattern: wheels-* 108 | path: wheelhouse 109 | merge-multiple: true 110 | 111 | - uses: actions/setup-python@v5 112 | with: 113 | python-version: "3.11" 114 | 115 | - name: Twine metadata check 116 | run: | 117 | python -m pip install -U twine pkginfo 118 | twine check wheelhouse/*.whl 119 | 120 | - name: Upload to PyPI (trusted publisher) 121 | uses: pypa/gh-action-pypi-publish@release/v1 122 | with: 123 | packages-dir: wheelhouse 124 | skip-existing: true 125 | verbose: true 126 | 127 | github-release: 128 | name: Create GitHub Release 129 | needs: [publish, prepare] 130 | runs-on: ubuntu-latest 131 | steps: 132 | - uses: actions/download-artifact@v4 133 | with: 134 | pattern: wheels-* 135 | path: wheelhouse 136 | merge-multiple: true 137 | 138 | - name: Create GitHub Release 139 | uses: softprops/action-gh-release@v1 140 | with: 141 | tag_name: v${{ needs.prepare.outputs.version }} 142 | name: v${{ needs.prepare.outputs.version }} 143 | files: wheelhouse/*.whl 144 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 1>NUL 2>NUL 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python_example.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python_example.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python_example.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python_example.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python_example" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python_example" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # TVDCondat2013 documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Feb 26 00:29:33 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # Ensure the compiled extension and package root are importable when building 19 | # the documentation. This allows ``autodoc`` to pull docstrings from the 20 | # extension module without requiring installation beforehand. 21 | sys.path.insert(0, os.path.abspath('..')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.intersphinx', 34 | 'sphinx.ext.autosummary', 35 | 'sphinx.ext.napoleon', 36 | ] 37 | 38 | autosummary_generate = True 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['_templates'] 42 | 43 | # The suffix(es) of source filenames. 44 | # You can specify multiple suffix as a list of string: 45 | # source_suffix = ['.rst', '.md'] 46 | source_suffix = '.rst' 47 | 48 | # The encoding of source files. 49 | #source_encoding = 'utf-8-sig' 50 | 51 | # The master toctree document. 52 | master_doc = 'index' 53 | 54 | # General information about the project. 55 | project = u'TVDCondat2013' 56 | copyright = u'2016, Boris Gailleton' 57 | author = u'Boris Gailleton' 58 | 59 | # The version info for the project you're documenting, acts as replacement for 60 | # |version| and |release|, also used in various other places throughout the 61 | # built documents. 62 | # 63 | # The short X.Y version. 64 | version = u'0.0.18' 65 | # The full version, including alpha/beta/rc tags. 66 | release = u'0.0.18' 67 | 68 | # The language for content autogenerated by Sphinx. Refer to documentation 69 | # for a list of supported languages. 70 | # 71 | # This is also used if you do content translation via gettext catalogs. 72 | # Usually you set "language" from the command line for these cases. 73 | language = 'en' 74 | 75 | # There are two options for replacing |today|: either, you set today to some 76 | # non-false value, then it is used: 77 | #today = '' 78 | # Else, today_fmt is used as the format for a strftime call. 79 | #today_fmt = '%B %d, %Y' 80 | 81 | # List of patterns, relative to source directory, that match files and 82 | # directories to ignore when looking for source files. 83 | exclude_patterns = ['_build'] 84 | 85 | # The reST default role (used for this markup: `text`) to use for all 86 | # documents. 87 | #default_role = None 88 | 89 | # If true, '()' will be appended to :func: etc. cross-reference text. 90 | #add_function_parentheses = True 91 | 92 | # If true, the current module name will be prepended to all description 93 | # unit titles (such as .. function::). 94 | #add_module_names = True 95 | 96 | # If true, sectionauthor and moduleauthor directives will be shown in the 97 | # output. They are ignored by default. 98 | #show_authors = False 99 | 100 | # The name of the Pygments (syntax highlighting) style to use. 101 | pygments_style = 'sphinx' 102 | 103 | # A list of ignored prefixes for module index sorting. 104 | #modindex_common_prefix = [] 105 | 106 | # If true, keep warnings as "system message" paragraphs in the built documents. 107 | #keep_warnings = False 108 | 109 | # If true, `todo` and `todoList` produce output, else they produce nothing. 110 | todo_include_todos = False 111 | 112 | 113 | # -- Options for HTML output ---------------------------------------------- 114 | 115 | # The theme to use for HTML pages. ``furo`` provides a clean, responsive layout 116 | # without additional configuration and gives the documentation a more modern 117 | # appearance. If the theme is not available (for example, when building the 118 | # documentation in environments where the optional dependency is not 119 | # installed), fall back to the Sphinx default theme so that documentation 120 | # generation still succeeds. 121 | try: 122 | import furo # noqa: F401 123 | html_theme = "furo" 124 | except Exception: # pragma: no cover - best effort for optional dependency 125 | html_theme = "alabaster" 126 | 127 | # Theme options are theme-specific and customize the look and feel of a theme 128 | # further. For a list of options available for each theme, see the 129 | # documentation. 130 | #html_theme_options = {} 131 | 132 | # Add any paths that contain custom themes here, relative to this directory. 133 | #html_theme_path = [] 134 | 135 | # The name for this set of Sphinx documents. If None, it defaults to 136 | # " v documentation". 137 | #html_title = None 138 | 139 | # A shorter title for the navigation bar. Default is the same as html_title. 140 | #html_short_title = None 141 | 142 | # The name of an image file (relative to this directory) to place at the top 143 | # of the sidebar. 144 | #html_logo = None 145 | 146 | # The name of an image file (within the static path) to use as favicon of the 147 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 148 | # pixels large. 149 | #html_favicon = None 150 | 151 | # Add any paths that contain custom static files (such as style sheets) here, 152 | # relative to this directory. They are copied after the builtin static files, 153 | # so a file named "default.css" will overwrite the builtin "default.css". 154 | #html_static_path = ['_static'] 155 | 156 | # Add any extra paths that contain custom files (such as robots.txt or 157 | # .htaccess) here, relative to this directory. These files are copied 158 | # directly to the root of the documentation. 159 | #html_extra_path = [] 160 | 161 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 162 | # using the given strftime format. 163 | #html_last_updated_fmt = '%b %d, %Y' 164 | 165 | # If true, SmartyPants will be used to convert quotes and dashes to 166 | # typographically correct entities. 167 | #html_use_smartypants = True 168 | 169 | # Custom sidebar templates, maps document names to template names. 170 | #html_sidebars = {} 171 | 172 | # Additional templates that should be rendered to pages, maps page names to 173 | # template names. 174 | #html_additional_pages = {} 175 | 176 | # If false, no module index is generated. 177 | #html_domain_indices = True 178 | 179 | # If false, no index is generated. 180 | #html_use_index = True 181 | 182 | # If true, the index is split into individual pages for each letter. 183 | #html_split_index = False 184 | 185 | # If true, links to the reST sources are added to the pages. 186 | #html_show_sourcelink = True 187 | 188 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 189 | #html_show_sphinx = True 190 | 191 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 192 | #html_show_copyright = True 193 | 194 | # If true, an OpenSearch description file will be output, and all pages will 195 | # contain a tag referring to it. The value of this option must be the 196 | # base URL from which the finished HTML is served. 197 | #html_use_opensearch = '' 198 | 199 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 200 | #html_file_suffix = None 201 | 202 | # Language to be used for generating the HTML full-text search index. 203 | # Sphinx supports the following languages: 204 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 205 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 206 | #html_search_language = 'en' 207 | 208 | # A dictionary with options for the search language support, empty by default. 209 | # Now only 'ja' uses this config value 210 | #html_search_options = {'type': 'default'} 211 | 212 | # The name of a javascript file (relative to the configuration directory) that 213 | # implements a search results scorer. If empty, the default will be used. 214 | #html_search_scorer = 'scorer.js' 215 | 216 | # Output file base name for HTML help builder. 217 | htmlhelp_basename = 'TVDCondat2013doc' 218 | 219 | # -- Options for LaTeX output --------------------------------------------- 220 | 221 | latex_elements = { 222 | # The paper size ('letterpaper' or 'a4paper'). 223 | #'papersize': 'letterpaper', 224 | 225 | # The font size ('10pt', '11pt' or '12pt'). 226 | #'pointsize': '10pt', 227 | 228 | # Additional stuff for the LaTeX preamble. 229 | #'preamble': '', 230 | 231 | # Latex figure (float) alignment 232 | #'figure_align': 'htbp', 233 | } 234 | 235 | # Grouping the document tree into LaTeX files. List of tuples 236 | # (source start file, target name, title, 237 | # author, documentclass [howto, manual, or own class]). 238 | latex_documents = [ 239 | (master_doc, 'TVDCondat2013.tex', u'TVDCondat2013 Documentation', 240 | u'Boris Gailleton', 'manual'), 241 | ] 242 | 243 | # The name of an image file (relative to this directory) to place at the top of 244 | # the title page. 245 | #latex_logo = None 246 | 247 | # For "manual" documents, if this is true, then toplevel headings are parts, 248 | # not chapters. 249 | #latex_use_parts = False 250 | 251 | # If true, show page references after internal links. 252 | #latex_show_pagerefs = False 253 | 254 | # If true, show URL addresses after external links. 255 | #latex_show_urls = False 256 | 257 | # Documents to append as an appendix to all manuals. 258 | #latex_appendices = [] 259 | 260 | # If false, no module index is generated. 261 | #latex_domain_indices = True 262 | 263 | 264 | # -- Options for manual page output --------------------------------------- 265 | 266 | # One entry per manual page. List of tuples 267 | # (source start file, name, description, authors, manual section). 268 | man_pages = [ 269 | (master_doc, 'TVDCondat2013', u'TVDCondat2013 Documentation', 270 | [author], 1) 271 | ] 272 | 273 | # If true, show URL addresses after external links. 274 | #man_show_urls = False 275 | 276 | 277 | # -- Options for Texinfo output ------------------------------------------- 278 | 279 | # Grouping the document tree into Texinfo files. List of tuples 280 | # (source start file, target name, title, author, 281 | # dir menu entry, description, category) 282 | texinfo_documents = [ 283 | (master_doc, 'TVDCondat2013', u'TVDCondat2013 Documentation', 284 | author, 'TVDCondat2013', 'One line description of project.', 285 | 'Miscellaneous'), 286 | ] 287 | 288 | # Documents to append as an appendix to all manuals. 289 | #texinfo_appendices = [] 290 | 291 | # If false, no module index is generated. 292 | #texinfo_domain_indices = True 293 | 294 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 295 | #texinfo_show_urls = 'footnote' 296 | 297 | # If true, do not generate a @detailmenu in the "Top" node's menu. 298 | #texinfo_no_detailmenu = False 299 | 300 | 301 | # Example configuration for intersphinx: refer to the Python standard library. 302 | intersphinx_mapping = { 303 | 'python': ('https://docs.python.org/3', None), 304 | } 305 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CeCILL FREE SOFTWARE LICENSE AGREEMENT 2 | 3 | Version 2.1 dated 2013-06-21 4 | 5 | 6 | Notice 7 | 8 | This Agreement is a Free Software license agreement that is the result 9 | of discussions between its authors in order to ensure compliance with 10 | the two main principles guiding its drafting: 11 | 12 | * firstly, compliance with the principles governing the distribution 13 | of Free Software: access to source code, broad rights granted to users, 14 | * secondly, the election of a governing law, French law, with which it 15 | is conformant, both as regards the law of torts and intellectual 16 | property law, and the protection that it offers to both authors and 17 | holders of the economic rights over software. 18 | 19 | The authors of the CeCILL (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) 20 | license are: 21 | 22 | Commissariat à l'énergie atomique et aux énergies alternatives - CEA, a 23 | public scientific, technical and industrial research establishment, 24 | having its principal place of business at 25 rue Leblanc, immeuble Le 25 | Ponant D, 75015 Paris, France. 26 | 27 | Centre National de la Recherche Scientifique - CNRS, a public scientific 28 | and technological establishment, having its principal place of business 29 | at 3 rue Michel-Ange, 75794 Paris cedex 16, France. 30 | 31 | Institut National de Recherche en Informatique et en Automatique - 32 | Inria, a public scientific and technological establishment, having its 33 | principal place of business at Domaine de Voluceau, Rocquencourt, BP 34 | 105, 78153 Le Chesnay cedex, France. 35 | 36 | 37 | Preamble 38 | 39 | The purpose of this Free Software license agreement is to grant users 40 | the right to modify and redistribute the software governed by this 41 | license within the framework of an open source distribution model. 42 | 43 | The exercising of this right is conditional upon certain obligations for 44 | users so as to preserve this status for all subsequent redistributions. 45 | 46 | In consideration of access to the source code and the rights to copy, 47 | modify and redistribute granted by the license, users are provided only 48 | with a limited warranty and the software's author, the holder of the 49 | economic rights, and the successive licensors only have limited liability. 50 | 51 | In this respect, the risks associated with loading, using, modifying 52 | and/or developing or reproducing the software by the user are brought to 53 | the user's attention, given its Free Software status, which may make it 54 | complicated to use, with the result that its use is reserved for 55 | developers and experienced professionals having in-depth computer 56 | knowledge. Users are therefore encouraged to load and test the 57 | suitability of the software as regards their requirements in conditions 58 | enabling the security of their systems and/or data to be ensured and, 59 | more generally, to use and operate it in the same conditions of 60 | security. This Agreement may be freely reproduced and published, 61 | provided it is not altered, and that no provisions are either added or 62 | removed herefrom. 63 | 64 | This Agreement may apply to any or all software for which the holder of 65 | the economic rights decides to submit the use thereof to its provisions. 66 | 67 | Frequently asked questions can be found on the official website of the 68 | CeCILL licenses family (http://www.cecill.info/index.en.html) for any 69 | necessary clarification. 70 | 71 | 72 | Article 1 - DEFINITIONS 73 | 74 | For the purpose of this Agreement, when the following expressions 75 | commence with a capital letter, they shall have the following meaning: 76 | 77 | Agreement: means this license agreement, and its possible subsequent 78 | versions and annexes. 79 | 80 | Software: means the software in its Object Code and/or Source Code form 81 | and, where applicable, its documentation, "as is" when the Licensee 82 | accepts the Agreement. 83 | 84 | Initial Software: means the Software in its Source Code and possibly its 85 | Object Code form and, where applicable, its documentation, "as is" when 86 | it is first distributed under the terms and conditions of the Agreement. 87 | 88 | Modified Software: means the Software modified by at least one 89 | Contribution. 90 | 91 | Source Code: means all the Software's instructions and program lines to 92 | which access is required so as to modify the Software. 93 | 94 | Object Code: means the binary files originating from the compilation of 95 | the Source Code. 96 | 97 | Holder: means the holder(s) of the economic rights over the Initial 98 | Software. 99 | 100 | Licensee: means the Software user(s) having accepted the Agreement. 101 | 102 | Contributor: means a Licensee having made at least one Contribution. 103 | 104 | Licensor: means the Holder, or any other individual or legal entity, who 105 | distributes the Software under the Agreement. 106 | 107 | Contribution: means any or all modifications, corrections, translations, 108 | adaptations and/or new functions integrated into the Software by any or 109 | all Contributors, as well as any or all Internal Modules. 110 | 111 | Module: means a set of sources files including their documentation that 112 | enables supplementary functions or services in addition to those offered 113 | by the Software. 114 | 115 | External Module: means any or all Modules, not derived from the 116 | Software, so that this Module and the Software run in separate address 117 | spaces, with one calling the other when they are run. 118 | 119 | Internal Module: means any or all Module, connected to the Software so 120 | that they both execute in the same address space. 121 | 122 | GNU GPL: means the GNU General Public License version 2 or any 123 | subsequent version, as published by the Free Software Foundation Inc. 124 | 125 | GNU Affero GPL: means the GNU Affero General Public License version 3 or 126 | any subsequent version, as published by the Free Software Foundation Inc. 127 | 128 | EUPL: means the European Union Public License version 1.1 or any 129 | subsequent version, as published by the European Commission. 130 | 131 | Parties: mean both the Licensee and the Licensor. 132 | 133 | These expressions may be used both in singular and plural form. 134 | 135 | 136 | Article 2 - PURPOSE 137 | 138 | The purpose of the Agreement is the grant by the Licensor to the 139 | Licensee of a non-exclusive, transferable and worldwide license for the 140 | Software as set forth in Article 5 <#scope> hereinafter for the whole 141 | term of the protection granted by the rights over said Software. 142 | 143 | 144 | Article 3 - ACCEPTANCE 145 | 146 | 3.1 The Licensee shall be deemed as having accepted the terms and 147 | conditions of this Agreement upon the occurrence of the first of the 148 | following events: 149 | 150 | * (i) loading the Software by any or all means, notably, by 151 | downloading from a remote server, or by loading from a physical medium; 152 | * (ii) the first time the Licensee exercises any of the rights granted 153 | hereunder. 154 | 155 | 3.2 One copy of the Agreement, containing a notice relating to the 156 | characteristics of the Software, to the limited warranty, and to the 157 | fact that its use is restricted to experienced users has been provided 158 | to the Licensee prior to its acceptance as set forth in Article 3.1 159 | <#accepting> hereinabove, and the Licensee hereby acknowledges that it 160 | has read and understood it. 161 | 162 | 163 | Article 4 - EFFECTIVE DATE AND TERM 164 | 165 | 166 | 4.1 EFFECTIVE DATE 167 | 168 | The Agreement shall become effective on the date when it is accepted by 169 | the Licensee as set forth in Article 3.1 <#accepting>. 170 | 171 | 172 | 4.2 TERM 173 | 174 | The Agreement shall remain in force for the entire legal term of 175 | protection of the economic rights over the Software. 176 | 177 | 178 | Article 5 - SCOPE OF RIGHTS GRANTED 179 | 180 | The Licensor hereby grants to the Licensee, who accepts, the following 181 | rights over the Software for any or all use, and for the term of the 182 | Agreement, on the basis of the terms and conditions set forth hereinafter. 183 | 184 | Besides, if the Licensor owns or comes to own one or more patents 185 | protecting all or part of the functions of the Software or of its 186 | components, the Licensor undertakes not to enforce the rights granted by 187 | these patents against successive Licensees using, exploiting or 188 | modifying the Software. If these patents are transferred, the Licensor 189 | undertakes to have the transferees subscribe to the obligations set 190 | forth in this paragraph. 191 | 192 | 193 | 5.1 RIGHT OF USE 194 | 195 | The Licensee is authorized to use the Software, without any limitation 196 | as to its fields of application, with it being hereinafter specified 197 | that this comprises: 198 | 199 | 1. permanent or temporary reproduction of all or part of the Software 200 | by any or all means and in any or all form. 201 | 202 | 2. loading, displaying, running, or storing the Software on any or all 203 | medium. 204 | 205 | 3. entitlement to observe, study or test its operation so as to 206 | determine the ideas and principles behind any or all constituent 207 | elements of said Software. This shall apply when the Licensee 208 | carries out any or all loading, displaying, running, transmission or 209 | storage operation as regards the Software, that it is entitled to 210 | carry out hereunder. 211 | 212 | 213 | 5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS 214 | 215 | The right to make Contributions includes the right to translate, adapt, 216 | arrange, or make any or all modifications to the Software, and the right 217 | to reproduce the resulting software. 218 | 219 | The Licensee is authorized to make any or all Contributions to the 220 | Software provided that it includes an explicit notice that it is the 221 | author of said Contribution and indicates the date of the creation thereof. 222 | 223 | 224 | 5.3 RIGHT OF DISTRIBUTION 225 | 226 | In particular, the right of distribution includes the right to publish, 227 | transmit and communicate the Software to the general public on any or 228 | all medium, and by any or all means, and the right to market, either in 229 | consideration of a fee, or free of charge, one or more copies of the 230 | Software by any means. 231 | 232 | The Licensee is further authorized to distribute copies of the modified 233 | or unmodified Software to third parties according to the terms and 234 | conditions set forth hereinafter. 235 | 236 | 237 | 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION 238 | 239 | The Licensee is authorized to distribute true copies of the Software in 240 | Source Code or Object Code form, provided that said distribution 241 | complies with all the provisions of the Agreement and is accompanied by: 242 | 243 | 1. a copy of the Agreement, 244 | 245 | 2. a notice relating to the limitation of both the Licensor's warranty 246 | and liability as set forth in Articles 8 and 9, 247 | 248 | and that, in the event that only the Object Code of the Software is 249 | redistributed, the Licensee allows effective access to the full Source 250 | Code of the Software for a period of at least three years from the 251 | distribution of the Software, it being understood that the additional 252 | acquisition cost of the Source Code shall not exceed the cost of the 253 | data transfer. 254 | 255 | 256 | 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE 257 | 258 | When the Licensee makes a Contribution to the Software, the terms and 259 | conditions for the distribution of the resulting Modified Software 260 | become subject to all the provisions of this Agreement. 261 | 262 | The Licensee is authorized to distribute the Modified Software, in 263 | source code or object code form, provided that said distribution 264 | complies with all the provisions of the Agreement and is accompanied by: 265 | 266 | 1. a copy of the Agreement, 267 | 268 | 2. a notice relating to the limitation of both the Licensor's warranty 269 | and liability as set forth in Articles 8 and 9, 270 | 271 | and, in the event that only the object code of the Modified Software is 272 | redistributed, 273 | 274 | 3. a note stating the conditions of effective access to the full source 275 | code of the Modified Software for a period of at least three years 276 | from the distribution of the Modified Software, it being understood 277 | that the additional acquisition cost of the source code shall not 278 | exceed the cost of the data transfer. 279 | 280 | 281 | 5.3.3 DISTRIBUTION OF EXTERNAL MODULES 282 | 283 | When the Licensee has developed an External Module, the terms and 284 | conditions of this Agreement do not apply to said External Module, that 285 | may be distributed under a separate license agreement. 286 | 287 | 288 | 5.3.4 COMPATIBILITY WITH OTHER LICENSES 289 | 290 | The Licensee can include a code that is subject to the provisions of one 291 | of the versions of the GNU GPL, GNU Affero GPL and/or EUPL in the 292 | Modified or unmodified Software, and distribute that entire code under 293 | the terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL. 294 | 295 | The Licensee can include the Modified or unmodified Software in a code 296 | that is subject to the provisions of one of the versions of the GNU GPL, 297 | GNU Affero GPL and/or EUPL and distribute that entire code under the 298 | terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL. 299 | 300 | 301 | Article 6 - INTELLECTUAL PROPERTY 302 | 303 | 304 | 6.1 OVER THE INITIAL SOFTWARE 305 | 306 | The Holder owns the economic rights over the Initial Software. Any or 307 | all use of the Initial Software is subject to compliance with the terms 308 | and conditions under which the Holder has elected to distribute its work 309 | and no one shall be entitled to modify the terms and conditions for the 310 | distribution of said Initial Software. 311 | 312 | The Holder undertakes that the Initial Software will remain ruled at 313 | least by this Agreement, for the duration set forth in Article 4.2 <#term>. 314 | 315 | 316 | 6.2 OVER THE CONTRIBUTIONS 317 | 318 | The Licensee who develops a Contribution is the owner of the 319 | intellectual property rights over this Contribution as defined by 320 | applicable law. 321 | 322 | 323 | 6.3 OVER THE EXTERNAL MODULES 324 | 325 | The Licensee who develops an External Module is the owner of the 326 | intellectual property rights over this External Module as defined by 327 | applicable law and is free to choose the type of agreement that shall 328 | govern its distribution. 329 | 330 | 331 | 6.4 JOINT PROVISIONS 332 | 333 | The Licensee expressly undertakes: 334 | 335 | 1. not to remove, or modify, in any manner, the intellectual property 336 | notices attached to the Software; 337 | 338 | 2. to reproduce said notices, in an identical manner, in the copies of 339 | the Software modified or not. 340 | 341 | The Licensee undertakes not to directly or indirectly infringe the 342 | intellectual property rights on the Software of the Holder and/or 343 | Contributors, and to take, where applicable, vis-à-vis its staff, any 344 | and all measures required to ensure respect of said intellectual 345 | property rights of the Holder and/or Contributors. 346 | 347 | 348 | Article 7 - RELATED SERVICES 349 | 350 | 7.1 Under no circumstances shall the Agreement oblige the Licensor to 351 | provide technical assistance or maintenance services for the Software. 352 | 353 | However, the Licensor is entitled to offer this type of services. The 354 | terms and conditions of such technical assistance, and/or such 355 | maintenance, shall be set forth in a separate instrument. Only the 356 | Licensor offering said maintenance and/or technical assistance services 357 | shall incur liability therefor. 358 | 359 | 7.2 Similarly, any Licensor is entitled to offer to its licensees, under 360 | its sole responsibility, a warranty, that shall only be binding upon 361 | itself, for the redistribution of the Software and/or the Modified 362 | Software, under terms and conditions that it is free to decide. Said 363 | warranty, and the financial terms and conditions of its application, 364 | shall be subject of a separate instrument executed between the Licensor 365 | and the Licensee. 366 | 367 | 368 | Article 8 - LIABILITY 369 | 370 | 8.1 Subject to the provisions of Article 8.2, the Licensee shall be 371 | entitled to claim compensation for any direct loss it may have suffered 372 | from the Software as a result of a fault on the part of the relevant 373 | Licensor, subject to providing evidence thereof. 374 | 375 | 8.2 The Licensor's liability is limited to the commitments made under 376 | this Agreement and shall not be incurred as a result of in particular: 377 | (i) loss due the Licensee's total or partial failure to fulfill its 378 | obligations, (ii) direct or consequential loss that is suffered by the 379 | Licensee due to the use or performance of the Software, and (iii) more 380 | generally, any consequential loss. In particular the Parties expressly 381 | agree that any or all pecuniary or business loss (i.e. loss of data, 382 | loss of profits, operating loss, loss of customers or orders, 383 | opportunity cost, any disturbance to business activities) or any or all 384 | legal proceedings instituted against the Licensee by a third party, 385 | shall constitute consequential loss and shall not provide entitlement to 386 | any or all compensation from the Licensor. 387 | 388 | 389 | Article 9 - WARRANTY 390 | 391 | 9.1 The Licensee acknowledges that the scientific and technical 392 | state-of-the-art when the Software was distributed did not enable all 393 | possible uses to be tested and verified, nor for the presence of 394 | possible defects to be detected. In this respect, the Licensee's 395 | attention has been drawn to the risks associated with loading, using, 396 | modifying and/or developing and reproducing the Software which are 397 | reserved for experienced users. 398 | 399 | The Licensee shall be responsible for verifying, by any or all means, 400 | the suitability of the product for its requirements, its good working 401 | order, and for ensuring that it shall not cause damage to either persons 402 | or properties. 403 | 404 | 9.2 The Licensor hereby represents, in good faith, that it is entitled 405 | to grant all the rights over the Software (including in particular the 406 | rights set forth in Article 5 <#scope>). 407 | 408 | 9.3 The Licensee acknowledges that the Software is supplied "as is" by 409 | the Licensor without any other express or tacit warranty, other than 410 | that provided for in Article 9.2 <#good-faith> and, in particular, 411 | without any warranty as to its commercial value, its secured, safe, 412 | innovative or relevant nature. 413 | 414 | Specifically, the Licensor does not warrant that the Software is free 415 | from any error, that it will operate without interruption, that it will 416 | be compatible with the Licensee's own equipment and software 417 | configuration, nor that it will meet the Licensee's requirements. 418 | 419 | 9.4 The Licensor does not either expressly or tacitly warrant that the 420 | Software does not infringe any third party intellectual property right 421 | relating to a patent, software or any other property right. Therefore, 422 | the Licensor disclaims any and all liability towards the Licensee 423 | arising out of any or all proceedings for infringement that may be 424 | instituted in respect of the use, modification and redistribution of the 425 | Software. Nevertheless, should such proceedings be instituted against 426 | the Licensee, the Licensor shall provide it with technical and legal 427 | expertise for its defense. Such technical and legal expertise shall be 428 | decided on a case-by-case basis between the relevant Licensor and the 429 | Licensee pursuant to a memorandum of understanding. The Licensor 430 | disclaims any and all liability as regards the Licensee's use of the 431 | name of the Software. No warranty is given as regards the existence of 432 | prior rights over the name of the Software or as regards the existence 433 | of a trademark. 434 | 435 | 436 | Article 10 - TERMINATION 437 | 438 | 10.1 In the event of a breach by the Licensee of its obligations 439 | hereunder, the Licensor may automatically terminate this Agreement 440 | thirty (30) days after notice has been sent to the Licensee and has 441 | remained ineffective. 442 | 443 | 10.2 A Licensee whose Agreement is terminated shall no longer be 444 | authorized to use, modify or distribute the Software. However, any 445 | licenses that it may have granted prior to termination of the Agreement 446 | shall remain valid subject to their having been granted in compliance 447 | with the terms and conditions hereof. 448 | 449 | 450 | Article 11 - MISCELLANEOUS 451 | 452 | 453 | 11.1 EXCUSABLE EVENTS 454 | 455 | Neither Party shall be liable for any or all delay, or failure to 456 | perform the Agreement, that may be attributable to an event of force 457 | majeure, an act of God or an outside cause, such as defective 458 | functioning or interruptions of the electricity or telecommunications 459 | networks, network paralysis following a virus attack, intervention by 460 | government authorities, natural disasters, water damage, earthquakes, 461 | fire, explosions, strikes and labor unrest, war, etc. 462 | 463 | 11.2 Any failure by either Party, on one or more occasions, to invoke 464 | one or more of the provisions hereof, shall under no circumstances be 465 | interpreted as being a waiver by the interested Party of its right to 466 | invoke said provision(s) subsequently. 467 | 468 | 11.3 The Agreement cancels and replaces any or all previous agreements, 469 | whether written or oral, between the Parties and having the same 470 | purpose, and constitutes the entirety of the agreement between said 471 | Parties concerning said purpose. No supplement or modification to the 472 | terms and conditions hereof shall be effective as between the Parties 473 | unless it is made in writing and signed by their duly authorized 474 | representatives. 475 | 476 | 11.4 In the event that one or more of the provisions hereof were to 477 | conflict with a current or future applicable act or legislative text, 478 | said act or legislative text shall prevail, and the Parties shall make 479 | the necessary amendments so as to comply with said act or legislative 480 | text. All other provisions shall remain effective. Similarly, invalidity 481 | of a provision of the Agreement, for any reason whatsoever, shall not 482 | cause the Agreement as a whole to be invalid. 483 | 484 | 485 | 11.5 LANGUAGE 486 | 487 | The Agreement is drafted in both French and English and both versions 488 | are deemed authentic. 489 | 490 | 491 | Article 12 - NEW VERSIONS OF THE AGREEMENT 492 | 493 | 12.1 Any person is authorized to duplicate and distribute copies of this 494 | Agreement. 495 | 496 | 12.2 So as to ensure coherence, the wording of this Agreement is 497 | protected and may only be modified by the authors of the License, who 498 | reserve the right to periodically publish updates or new versions of the 499 | Agreement, each with a separate number. These subsequent versions may 500 | address new issues encountered by Free Software. 501 | 502 | 12.3 Any Software distributed under a given version of the Agreement may 503 | only be subsequently distributed under the same version of the Agreement 504 | or a subsequent version, subject to the provisions of Article 5.3.4 505 | <#compatibility>. 506 | 507 | 508 | Article 13 - GOVERNING LAW AND JURISDICTION 509 | 510 | 13.1 The Agreement is governed by French law. The Parties agree to 511 | endeavor to seek an amicable solution to any disagreements or disputes 512 | that may arise during the performance of the Agreement. 513 | 514 | 13.2 Failing an amicable solution within two (2) months as from their 515 | occurrence, and unless emergency proceedings are necessary, the 516 | disagreements or disputes shall be referred to the Paris Courts having 517 | jurisdiction, by the more diligent Party. 518 | 519 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // Core implementation of 1-D Total Variation Denoising using Condat's 2013 2 | // and 2017 algorithms. The routines operate directly on raw pointers and are 3 | // exposed to Python through pybind11 with NumPy array support. 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | namespace py = pybind11; 13 | 14 | namespace tvd { 15 | 16 | // ----------------------------------------------------------------------------- 17 | // 2013 algorithm (version 1) 18 | // ----------------------------------------------------------------------------- 19 | /** 20 | * @brief Perform 1‑D total variation denoising. 21 | * 22 | * Direct implementation of Laurent Condat's 2013 algorithm. The body is kept 23 | * as close as possible to the original C reference code; only minimal changes 24 | * were made to operate on generic floating point types and integrate with the 25 | * Python wrapper. 26 | * 27 | * @tparam T Floating point type (float or double). 28 | * @param input Noisy input signal. 29 | * @param output Buffer receiving the denoised signal. ``input`` and ``output`` 30 | * may point to the same memory for in‑place operation. 31 | * @param width Number of samples in the signal. 32 | * @param lambda Regularisation parameter (non‑negative). 33 | */ 34 | template 35 | void tv1d_denoise(const T *input, T *output, int width, T lambda) 36 | { 37 | if (width > 0) 38 | { 39 | int k = 0, k0 = 0; // current index and segment start 40 | T umin = lambda, umax = -lambda; // dual variables 41 | T vmin = input[0] - lambda, vmax = input[0] + lambda; // segment bounds 42 | int kplus = 0, kminus = 0; // last positions of constraints 43 | const T twolambda = static_cast(2) * lambda; 44 | const T minlambda = -lambda; 45 | for (;;) // iterative process 46 | { 47 | while (k == width - 1) // apply boundary condition 48 | { 49 | if (umin < static_cast(0)) 50 | { 51 | do 52 | output[k0++] = vmin; 53 | while (k0 <= kminus); 54 | umax = (vmin = input[kminus = k = k0]) + (umin = lambda) - vmax; 55 | } 56 | else if (umax > static_cast(0)) 57 | { 58 | do 59 | output[k0++] = vmax; 60 | while (k0 <= kplus); 61 | umin = (vmax = input[kplus = k = k0]) + (umax = minlambda) - vmin; 62 | } 63 | else 64 | { 65 | vmin += umin / (k - k0 + 1); 66 | do 67 | output[k0++] = vmin; 68 | while (k0 <= k); 69 | return; 70 | } 71 | } 72 | if ((umin += input[k + 1] - vmin) < minlambda) // negative jump 73 | { 74 | do 75 | output[k0++] = vmin; 76 | while (k0 <= kminus); 77 | vmax = (vmin = input[kplus = kminus = k = k0]) + twolambda; 78 | umin = lambda; 79 | umax = minlambda; 80 | } 81 | else if ((umax += input[k + 1] - vmax) > lambda) // positive jump 82 | { 83 | do 84 | output[k0++] = vmax; 85 | while (k0 <= kplus); 86 | vmin = (vmax = input[kplus = kminus = k = k0]) - twolambda; 87 | umin = lambda; 88 | umax = minlambda; 89 | } 90 | else // no jump, continue 91 | { 92 | k++; 93 | if (umin >= lambda) 94 | { 95 | vmin += (umin - lambda) / ((kminus = k) - k0 + 1); 96 | umin = lambda; 97 | } 98 | if (umax <= minlambda) 99 | { 100 | vmax += (umax + lambda) / ((kplus = k) - k0 + 1); 101 | umax = minlambda; 102 | } 103 | } 104 | } 105 | } 106 | } 107 | 108 | /** 109 | * @brief Fused Lasso Signal Approximator. 110 | * 111 | * Extension of the above routine including an additional ``mu`` parameter. 112 | * The implementation mirrors the reference C code closely and supports 113 | * in‑place operation. 114 | */ 115 | template 116 | void fused_lasso(const T *input, T *output, int width, T lambda, T mu) 117 | { 118 | if (width > 0) 119 | { 120 | int k = 0, k0 = 0; 121 | T umin = lambda, umax = -lambda; 122 | T vmin = input[0] - lambda, vmax = input[0] + lambda; 123 | int kplus = 0, kminus = 0; 124 | const T twolambda = static_cast(2) * lambda; 125 | const T minlambda = -lambda; 126 | for (;;) 127 | { 128 | while (k == width - 1) 129 | { 130 | if (umin < static_cast(0)) 131 | { 132 | vmin = vmin > mu ? vmin - mu 133 | : vmin < -mu ? vmin + mu : static_cast(0); 134 | do 135 | output[k0++] = vmin; 136 | while (k0 <= kminus); 137 | umax = (vmin = input[kminus = k = k0]) + (umin = lambda) - vmax; 138 | } 139 | else if (umax > static_cast(0)) 140 | { 141 | vmax = vmax > mu ? vmax - mu 142 | : vmax < -mu ? vmax + mu : static_cast(0); 143 | do 144 | output[k0++] = vmax; 145 | while (k0 <= kplus); 146 | umin = (vmax = input[kplus = k = k0]) + (umax = minlambda) - vmin; 147 | } 148 | else 149 | { 150 | vmin += umin / (k - k0 + 1); 151 | vmin = vmin > mu ? vmin - mu 152 | : vmin < -mu ? vmin + mu : static_cast(0); 153 | do 154 | output[k0++] = vmin; 155 | while (k0 <= k); 156 | return; 157 | } 158 | } 159 | if ((umin += input[k + 1] - vmin) < minlambda) 160 | { 161 | vmin = vmin > mu ? vmin - mu 162 | : vmin < -mu ? vmin + mu : static_cast(0); 163 | do 164 | output[k0++] = vmin; 165 | while (k0 <= kminus); 166 | vmax = (vmin = input[kplus = kminus = k = k0]) + twolambda; 167 | umin = lambda; 168 | umax = minlambda; 169 | } 170 | else if ((umax += input[k + 1] - vmax) > lambda) 171 | { 172 | vmax = vmax > mu ? vmax - mu 173 | : vmax < -mu ? vmax + mu : static_cast(0); 174 | do 175 | output[k0++] = vmax; 176 | while (k0 <= kplus); 177 | vmin = (vmax = input[kplus = kminus = k = k0]) - twolambda; 178 | umin = lambda; 179 | umax = minlambda; 180 | } 181 | else 182 | { 183 | k++; 184 | if (umin >= lambda) 185 | { 186 | vmin += (umin - lambda) / ((kminus = k) - k0 + 1); 187 | umin = lambda; 188 | } 189 | if (umax <= minlambda) 190 | { 191 | vmax += (umax + lambda) / ((kplus = k) - k0 + 1); 192 | umax = minlambda; 193 | } 194 | } 195 | } 196 | } 197 | } 198 | 199 | // ----------------------------------------------------------------------------- 200 | // 2017 algorithm (version 2) by Laurent Condat under the CeCILL licence. 201 | // ----------------------------------------------------------------------------- 202 | 203 | /** 204 | * @brief 1‑D total variation denoising (Condat 2017). 205 | * 206 | * Implementation of the revised algorithm published in 2017, which is a 207 | * simplified and slightly faster variant of the original 2013 routine. 208 | * The code is a C++ port of Laurent Condat's reference implementation and 209 | * carries the same CeCILL licence (GPL compatible). 210 | * 211 | * @tparam T Floating point type (float or double). 212 | * @param input Pointer to the noisy input signal. 213 | * @param output Pointer to a pre‑allocated buffer that will receive the 214 | * denoised signal. 215 | * @param width Number of samples in the signal. 216 | * @param lambda Regularisation parameter controlling the amount of 217 | * smoothing. 218 | */ 219 | // The reference implementation operates in double precision. We keep an 220 | // internal double routine and expose a templated wrapper that casts inputs and 221 | // outputs appropriately so that float arrays still benefit from the increased 222 | // numerical robustness. 223 | static void tv1d_denoise_v2_double(const double *input, double *output, 224 | unsigned int width, double lambda) 225 | { 226 | std::vector indstart_low(width); 227 | std::vector indstart_up(width); 228 | 229 | unsigned int j_low = 0, j_up = 0, jseg = 0, indjseg = 0, i = 1, indjseg2, ind; 230 | double output_low_first = input[0] - lambda; 231 | double output_low_curr = output_low_first; 232 | double output_up_first = input[0] + lambda; 233 | double output_up_curr = output_up_first; 234 | const double twolambda = 2.0 * lambda; 235 | 236 | if (width == 1) 237 | { 238 | output[0] = input[0]; 239 | return; 240 | } 241 | 242 | indstart_low[0] = 0; 243 | indstart_up[0] = 0; 244 | width--; 245 | for (; i < width; i++) 246 | { 247 | if (input[i] >= output_low_curr) 248 | { 249 | if (input[i] <= output_up_curr) 250 | { 251 | output_up_curr += 252 | (input[i] - output_up_curr) / (i - indstart_up[j_up] + 1); 253 | output[indjseg] = output_up_first; 254 | while ((j_up > jseg) && 255 | (output_up_curr <= output[ind = indstart_up[j_up - 1]])) 256 | output_up_curr += (output[ind] - output_up_curr) * 257 | (double)(indstart_up[j_up--] - ind) / 258 | (i - ind + 1); 259 | if (j_up == jseg) 260 | { 261 | while ((output_up_curr <= output_low_first) && (jseg < j_low)) 262 | { 263 | indjseg2 = indstart_low[++jseg]; 264 | output_up_curr += (output_up_curr - output_low_first) * 265 | (double)(indjseg2 - indjseg) / 266 | (i - indjseg2 + 1); 267 | while (indjseg < indjseg2) 268 | output[indjseg++] = output_low_first; 269 | output_low_first = output[indjseg]; 270 | } 271 | output_up_first = output_up_curr; 272 | indstart_up[j_up = jseg] = indjseg; 273 | } 274 | else 275 | output[indstart_up[j_up]] = output_up_curr; 276 | } 277 | else 278 | { 279 | output_up_curr = output[i] = input[indstart_up[++j_up] = i]; 280 | output_low_curr += 281 | (input[i] - output_low_curr) / 282 | (i - indstart_low[j_low] + 1); 283 | output[indjseg] = output_low_first; 284 | while ((j_low > jseg) && 285 | (output_low_curr >= output[ind = indstart_low[j_low - 1]])) 286 | output_low_curr += (output[ind] - output_low_curr) * 287 | (double)(indstart_low[j_low--] - ind) / 288 | (i - ind + 1); 289 | if (j_low == jseg) 290 | { 291 | while ((output_low_curr >= output_up_first) && (jseg < j_up)) 292 | { 293 | indjseg2 = indstart_up[++jseg]; 294 | output_low_curr += (output_low_curr - output_up_first) * 295 | (double)(indjseg2 - indjseg) / 296 | (i - indjseg2 + 1); 297 | while (indjseg < indjseg2) 298 | output[indjseg++] = output_up_first; 299 | output_up_first = output[indjseg]; 300 | } 301 | if ((indstart_low[j_low = jseg] = indjseg) == i) 302 | output_low_first = output_up_first - twolambda; 303 | else 304 | output_low_first = output_low_curr; 305 | } 306 | else 307 | output[indstart_low[j_low]] = output_low_curr; 308 | } 309 | } 310 | else 311 | { 312 | output_up_curr += ((output_low_curr = output[i] = 313 | input[indstart_low[++j_low] = i]) - 314 | output_up_curr) / 315 | (i - indstart_up[j_up] + 1); 316 | output[indjseg] = output_up_first; 317 | while ((j_up > jseg) && 318 | (output_up_curr <= output[ind = indstart_up[j_up - 1]])) 319 | output_up_curr += (output[ind] - output_up_curr) * 320 | (double)(indstart_up[j_up--] - ind) / 321 | (i - ind + 1); 322 | if (j_up == jseg) 323 | { 324 | while ((output_up_curr <= output_low_first) && (jseg < j_low)) 325 | { 326 | indjseg2 = indstart_low[++jseg]; 327 | output_up_curr += (output_up_curr - output_low_first) * 328 | (double)(indjseg2 - indjseg) / 329 | (i - indjseg2 + 1); 330 | while (indjseg < indjseg2) 331 | output[indjseg++] = output_low_first; 332 | output_low_first = output[indjseg]; 333 | } 334 | if ((indstart_up[j_up = jseg] = indjseg) == i) 335 | output_up_first = output_low_first + twolambda; 336 | else 337 | output_up_first = output_up_curr; 338 | } 339 | else 340 | output[indstart_up[j_up]] = output_up_curr; 341 | } 342 | } 343 | 344 | if (input[i] + lambda <= output_low_curr) 345 | { 346 | while (jseg < j_low) 347 | { 348 | indjseg2 = indstart_low[++jseg]; 349 | while (indjseg < indjseg2) 350 | output[indjseg++] = output_low_first; 351 | output_low_first = output[indjseg]; 352 | } 353 | while (indjseg < i) 354 | output[indjseg++] = output_low_first; 355 | output[indjseg] = input[i] + lambda; 356 | } 357 | else if (input[i] - lambda >= output_up_curr) 358 | { 359 | while (jseg < j_up) 360 | { 361 | indjseg2 = indstart_up[++jseg]; 362 | while (indjseg < indjseg2) 363 | output[indjseg++] = output_up_first; 364 | output_up_first = output[indjseg]; 365 | } 366 | while (indjseg < i) 367 | output[indjseg++] = output_up_first; 368 | output[indjseg] = input[i] - lambda; 369 | } 370 | else 371 | { 372 | output_low_curr += (input[i] + lambda - output_low_curr) / 373 | (i - indstart_low[j_low] + 1); 374 | output[indjseg] = output_low_first; 375 | while ((j_low > jseg) && 376 | (output_low_curr >= output[ind = indstart_low[j_low - 1]])) 377 | output_low_curr += (output[ind] - output_low_curr) * 378 | (double)(indstart_low[j_low--] - ind) / 379 | (i - ind + 1); 380 | if (j_low == jseg) 381 | { 382 | if (output_up_first >= output_low_curr) 383 | while (indjseg <= i) 384 | output[indjseg++] = output_low_curr; 385 | else 386 | { 387 | output_up_curr += (input[i] - lambda - output_up_curr) / 388 | (i - indstart_up[j_up] + 1); 389 | output[indjseg] = output_up_first; 390 | while ((j_up > jseg) && 391 | (output_up_curr <= output[ind = indstart_up[j_up - 1]])) 392 | output_up_curr += (output[ind] - output_up_curr) * 393 | (double)(indstart_up[j_up--] - ind) / 394 | (i - ind + 1); 395 | while (jseg < j_up) 396 | { 397 | indjseg2 = indstart_up[++jseg]; 398 | while (indjseg < indjseg2) 399 | output[indjseg++] = output_up_first; 400 | output_up_first = output[indjseg]; 401 | } 402 | indjseg = indstart_up[j_up]; 403 | while (indjseg <= i) 404 | output[indjseg++] = output_up_curr; 405 | } 406 | } 407 | else 408 | { 409 | while (jseg < j_low) 410 | { 411 | indjseg2 = indstart_low[++jseg]; 412 | while (indjseg < indjseg2) 413 | output[indjseg++] = output_low_first; 414 | output_low_first = output[indjseg]; 415 | } 416 | indjseg = indstart_low[j_low]; 417 | while (indjseg <= i) 418 | output[indjseg++] = output_low_curr; 419 | } 420 | } 421 | } 422 | 423 | template 424 | void tv1d_denoise_v2(const T *input, T *output, unsigned int width, T lambda) 425 | { 426 | // Run the core algorithm in double precision for robustness and cast back 427 | // to the original dtype once finished. 428 | std::vector in(width), out(width); 429 | for (unsigned int k = 0; k < width; ++k) 430 | in[k] = static_cast(input[k]); 431 | tv1d_denoise_v2_double(in.data(), out.data(), width, 432 | static_cast(lambda)); 433 | for (unsigned int k = 0; k < width; ++k) 434 | output[k] = static_cast(out[k]); 435 | } 436 | 437 | /** 438 | * @brief 1‑D total variation denoising using the taut string algorithm. 439 | * 440 | * Adapted from the Matlab implementation by Lutz Dümbgen. 441 | * Uses double precision internally for numerical stability. 442 | */ 443 | template 444 | void tv1d_denoise_tautstring(const T *input, T *output, int width, T lambda) 445 | { 446 | if (width <= 0) 447 | return; 448 | using FT = double; 449 | int N = width + 1; 450 | std::vector index_low(N), index_up(N), index(N); 451 | std::vector slope_low(N), slope_up(N), z(N), y_low(N), y_up(N); 452 | 453 | int s_low = 0, c_low = 0, s_up = 0, c_up = 0, c = 0; 454 | int i = 2; 455 | 456 | y_low[0] = y_up[0] = 0; 457 | y_low[1] = static_cast(input[0]) - static_cast(lambda); 458 | y_up[1] = static_cast(input[0]) + static_cast(lambda); 459 | for (; i < N; ++i) 460 | { 461 | y_low[i] = y_low[i - 1] + static_cast(input[i - 1]); 462 | y_up[i] = y_up[i - 1] + static_cast(input[i - 1]); 463 | } 464 | y_low[N - 1] += static_cast(lambda); 465 | y_up[N - 1] -= static_cast(lambda); 466 | 467 | slope_low[0] = std::numeric_limits::infinity(); 468 | slope_up[0] = -std::numeric_limits::infinity(); 469 | z[0] = y_low[0]; 470 | 471 | for (i = 1; i < N; ++i) 472 | { 473 | index_low[++c_low] = index_up[++c_up] = i; 474 | slope_low[c_low] = y_low[i] - y_low[i - 1]; 475 | while ((c_low > s_low + 1) && 476 | (slope_low[std::max(s_low, c_low - 1)] <= slope_low[c_low])) 477 | { 478 | index_low[--c_low] = i; 479 | if (c_low > s_low + 1) 480 | slope_low[c_low] = (y_low[i] - y_low[index_low[c_low - 1]]) / 481 | (i - index_low[c_low - 1]); 482 | else 483 | slope_low[c_low] = (y_low[i] - z[c]) / (i - index[c]); 484 | } 485 | 486 | slope_up[c_up] = y_up[i] - y_up[i - 1]; 487 | while ((c_up > s_up + 1) && 488 | (slope_up[std::max(c_up - 1, s_up)] >= slope_up[c_up])) 489 | { 490 | index_up[--c_up] = i; 491 | if (c_up > s_up + 1) 492 | slope_up[c_up] = (y_up[i] - y_up[index_up[c_up - 1]]) / 493 | (i - index_up[c_up - 1]); 494 | else 495 | slope_up[c_up] = (y_up[i] - z[c]) / (i - index[c]); 496 | } 497 | 498 | while ((c_low == s_low + 1) && (c_up > s_up + 1) && 499 | (slope_low[c_low] >= slope_up[s_up + 1])) 500 | { 501 | index[++c] = index_up[++s_up]; 502 | z[c] = y_up[index[c]]; 503 | index_low[s_low] = index[c]; 504 | slope_low[c_low] = (y_low[i] - z[c]) / (i - index[c]); 505 | } 506 | while ((c_up == s_up + 1) && (c_low > s_low + 1) && 507 | (slope_up[c_up] <= slope_low[s_low + 1])) 508 | { 509 | index[++c] = index_low[++s_low]; 510 | z[c] = y_low[index[c]]; 511 | index_up[s_up] = index[c]; 512 | slope_up[c_up] = (y_up[i] - z[c]) / (i - index[c]); 513 | } 514 | } 515 | 516 | for (i = 1; i <= c_low - s_low; ++i) 517 | z[c + i] = y_low[index[c + i] = index_low[s_low + i]]; 518 | c += c_low - s_low; 519 | 520 | int j = 0; 521 | T a; 522 | for (i = 1; i <= c; ++i) 523 | { 524 | a = static_cast((z[i] - z[i - 1]) / (index[i] - index[i - 1])); 525 | while (j < index[i]) 526 | output[j++] = a; 527 | } 528 | } 529 | 530 | // ----------------------------------------------------------------------------- 531 | // Wrappers operating on NumPy arrays 532 | // ----------------------------------------------------------------------------- 533 | 534 | /** 535 | * @brief Convenience wrapper around tv1d_denoise for NumPy arrays. 536 | * 537 | * The input array is copied into a contiguous buffer (if required), passed to 538 | * the core implementation and the denoised result is returned as a new 539 | * NumPy array. The function preserves the dtype of the input array and is 540 | * exposed to Python as ``tvd_2013``. 541 | * 542 | * @tparam T Floating point type (float or double). 543 | * @param in 1‑D NumPy array containing the noisy signal. 544 | * @param lambda Regularisation parameter controlling the amount of smoothing. 545 | * @returns New NumPy array with the denoised signal. 546 | */ 547 | template 548 | py::array_t tvd_2013(py::array_t in, 549 | double lambda) 550 | { 551 | auto buf = in.request(); 552 | auto n = static_cast(buf.size); 553 | const T *data = static_cast(buf.ptr); 554 | py::array_t result(buf.size); 555 | tv1d_denoise(data, result.mutable_data(), n, static_cast(lambda)); 556 | return result; 557 | } 558 | 559 | /** 560 | * @brief Wrapper for the revised 2017 denoising algorithm. 561 | * 562 | * This function behaves identically to :func:`tvd_2013` but calls the ``v2`` 563 | * implementation which trades a small amount of precision for improved 564 | * performance. Both single and double precision signals are supported. 565 | */ 566 | template 567 | py::array_t tvd_2017(py::array_t in, 568 | double lambda) 569 | { 570 | auto buf = in.request(); 571 | auto n = static_cast(buf.size); 572 | const T *data = static_cast(buf.ptr); 573 | py::array_t result(buf.size); 574 | tv1d_denoise_v2(data, result.mutable_data(), n, static_cast(lambda)); 575 | return result; 576 | } 577 | 578 | /** 579 | * @brief Wrapper for the taut string denoising algorithm. 580 | */ 581 | template 582 | py::array_t tvd_tautstring( 583 | py::array_t in, double lambda) 584 | { 585 | auto buf = in.request(); 586 | auto n = static_cast(buf.size); 587 | const T *data = static_cast(buf.ptr); 588 | py::array_t result(buf.size); 589 | tv1d_denoise_tautstring(data, result.mutable_data(), n, 590 | static_cast(lambda)); 591 | return result; 592 | } 593 | 594 | /** 595 | * @brief Wrapper for the fused lasso signal approximator. 596 | */ 597 | template 598 | py::array_t fused_lasso_py( 599 | py::array_t in, double lambda, 600 | double mu) 601 | { 602 | auto buf = in.request(); 603 | auto n = static_cast(buf.size); 604 | const T *data = static_cast(buf.ptr); 605 | py::array_t result(buf.size); 606 | fused_lasso(data, result.mutable_data(), n, static_cast(lambda), 607 | static_cast(mu)); 608 | return result; 609 | } 610 | 611 | } // namespace tvd 612 | PYBIND11_MODULE(TVDCondat2013, m) 613 | { 614 | // Module level documentation with references to the original publications 615 | m.doc() = R"pbdoc( 616 | Python bindings for 1-D total variation denoising based on 617 | Laurent Condat's algorithms\ [Condat2013]_\ [Condat2017]_. 618 | Includes a taut string variant adapted from Lutz Dümbgen's Matlab code. 619 | 620 | .. [Condat2013] L. Condat, "A Direct Algorithm for 1D Total Variation 621 | Denoising," *IEEE Signal Processing Letters*, 2013. 622 | .. [Condat2017] L. Condat, "Fast Projection onto the Simplex and the 623 | L1 Ball," *Mathematical Programming*, 2017. 624 | 625 | Copyright (c) 2013-2025 Laurent Condat and contributors. 626 | )pbdoc"; 627 | 628 | const char *tvd_doc = R"pbdoc( 629 | Apply 1-D total variation denoising to a signal. 630 | 631 | :param numpy.ndarray signal: 1-D array of ``float32`` or ``float64`` 632 | values. 633 | :param float lambda: Regularisation parameter controlling smoothing. 634 | :returns: Denoised signal with the same dtype as ``signal``. 635 | :rtype: numpy.ndarray 636 | 637 | Copyright (c) 2013-2025 Laurent Condat. 638 | )pbdoc"; 639 | 640 | m.def("tvd_2013", &tvd::tvd_2013, py::arg("signal").noconvert(), 641 | py::arg("lambda"), tvd_doc); 642 | m.def("tvd_2013", &tvd::tvd_2013, py::arg("signal").noconvert(), 643 | py::arg("lambda"), tvd_doc); 644 | 645 | m.def("tvd_2017", &tvd::tvd_2017, py::arg("signal").noconvert(), 646 | py::arg("lambda"), tvd_doc); 647 | m.def("tvd_2017", &tvd::tvd_2017, py::arg("signal").noconvert(), 648 | py::arg("lambda"), tvd_doc); 649 | 650 | m.def("tvd_tautstring", &tvd::tvd_tautstring, 651 | py::arg("signal").noconvert(), py::arg("lambda"), tvd_doc); 652 | m.def("tvd_tautstring", &tvd::tvd_tautstring, 653 | py::arg("signal").noconvert(), py::arg("lambda"), tvd_doc); 654 | 655 | const char *fl_doc = R"pbdoc( 656 | Fused lasso signal approximation. 657 | 658 | :param numpy.ndarray signal: 1-D array of ``float32`` or ``float64`` 659 | values. 660 | :param float lambda: Total variation regularisation parameter. 661 | :param float mu: L1 penalty on the signal values. 662 | :returns: Denoised signal with the same dtype as ``signal``. 663 | :rtype: numpy.ndarray 664 | 665 | Copyright (c) 2013-2025 Laurent Condat. 666 | )pbdoc"; 667 | 668 | m.def("fused_lasso", &tvd::fused_lasso_py, 669 | py::arg("signal").noconvert(), py::arg("lambda"), py::arg("mu"), 670 | fl_doc); 671 | m.def("fused_lasso", &tvd::fused_lasso_py, 672 | py::arg("signal").noconvert(), py::arg("lambda"), py::arg("mu"), 673 | fl_doc); 674 | } 675 | 676 | --------------------------------------------------------------------------------