├── .codecov.yml
├── .gitignore
├── tox.ini
├── .pre-commit-config.yaml
├── pyproject.toml
├── setup.py
├── accupy
├── __init__.py
├── dot.py
├── sums.py
└── ill_cond.py
├── justfile
├── .github
└── workflows
│ └── ci.yml
├── setup.cfg
├── tests
├── test_dot.py
└── test_sums.py
├── src
└── pybind11.cpp
├── README.md
└── LICENSE
/.codecov.yml:
--------------------------------------------------------------------------------
1 | comment: no
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.swp
3 | *.prof
4 | MANIFEST
5 | dist/
6 | build/
7 | .coverage
8 | .cache/
9 | *.egg-info/
10 | .pytest_cache/
11 | *.png
12 | *.svg
13 | .tox/
14 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py3
3 | isolated_build = True
4 |
5 | [testenv]
6 | deps =
7 | dufte
8 | perfplot
9 | pytest
10 | pytest-cov
11 | commands =
12 | pytest {posargs}
13 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/PyCQA/isort
3 | rev: 5.9.1
4 | hooks:
5 | - id: isort
6 |
7 | - repo: https://github.com/python/black
8 | rev: 21.6b0
9 | hooks:
10 | - id: black
11 | language_version: python3
12 |
13 | - repo: https://github.com/PyCQA/pylint
14 | rev: v2.9.5
15 | hooks:
16 | - id: pylint
17 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=42", "wheel", "pybind11>=2.6.0"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [tool.isort]
6 | profile = "black"
7 |
8 | [tool.pylint.messages_control]
9 | max-line-length = 88
10 | disable = [
11 | "invalid-name",
12 | "missing-function-docstring",
13 | "missing-module-docstring",
14 | "import-error",
15 | "duplicate-code",
16 | ]
17 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # https://github.com/pybind/python_example
2 | from pybind11.setup_helpers import Pybind11Extension, build_ext
3 | from setuptools import setup
4 |
5 | ext_modules = [
6 | Pybind11Extension(
7 | "_accupy",
8 | ["src/pybind11.cpp"],
9 | include_dirs=["/usr/include/eigen3/"],
10 | )
11 | ]
12 |
13 | if __name__ == "__main__":
14 | setup(
15 | cmdclass={"build_ext": build_ext},
16 | ext_modules=ext_modules,
17 | zip_safe=False,
18 | )
19 |
--------------------------------------------------------------------------------
/accupy/__init__.py:
--------------------------------------------------------------------------------
1 | from .dot import fdot, kdot
2 | from .ill_cond import (
3 | cond,
4 | generate_ill_conditioned_dot_product,
5 | generate_ill_conditioned_sum,
6 | )
7 | from .sums import decker_sum, distill, fsum, kahan_sum, knuth_sum, ksum
8 |
9 | __all__ = [
10 | "cond",
11 | "kdot",
12 | "fdot",
13 | "generate_ill_conditioned_sum",
14 | "generate_ill_conditioned_dot_product",
15 | "knuth_sum",
16 | "decker_sum",
17 | "distill",
18 | "ksum",
19 | "fsum",
20 | "kahan_sum",
21 | ]
22 |
--------------------------------------------------------------------------------
/justfile:
--------------------------------------------------------------------------------
1 | version := `python3 -c "from configparser import ConfigParser; p = ConfigParser(); p.read('setup.cfg'); print(p['metadata']['version'])"`
2 | name := `python3 -c "from configparser import ConfigParser; p = ConfigParser(); p.read('setup.cfg'); print(p['metadata']['name'])"`
3 |
4 |
5 | default:
6 | @echo "\"just publish\"?"
7 |
8 | tag:
9 | @if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
10 | curl -H "Authorization: token `cat ~/.github-access-token`" -d '{"tag_name": "{{version}}"}' https://api.github.com/repos/nschloe/{{name}}/releases
11 |
12 | upload: clean
13 | @if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
14 | # https://stackoverflow.com/a/58756491/353337
15 | python3 -m build --sdist --wheel .
16 | twine upload dist/*.tar.gz
17 |
18 | publish: tag upload
19 |
20 | clean:
21 | @find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
22 | @rm -rf src/*.egg-info/ build/ dist/ .tox/
23 |
24 | format:
25 | isort .
26 | black .
27 | blacken-docs README.md
28 |
29 | lint:
30 | black --check .
31 | pylint .
32 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: ci
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | lint:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Check out repo
16 | uses: actions/checkout@v2
17 | - name: Set up Python
18 | uses: actions/setup-python@v2
19 | - name: Run pre-commit
20 | uses: pre-commit/action@v2.0.3
21 |
22 | build:
23 | runs-on: ubuntu-latest
24 | strategy:
25 | matrix:
26 | python-version: [3.7, 3.8, 3.9]
27 | steps:
28 | - uses: actions/setup-python@v2
29 | with:
30 | python-version: ${{ matrix.python-version }}
31 | - uses: actions/checkout@v2
32 | - name: Install system dependencies
33 | run: sudo apt-get install -y libeigen3-dev
34 | - name: Test with tox
35 | run: |
36 | pip install tox
37 | tox -- --cov accupy --cov-report xml --cov-report term
38 | - uses: codecov/codecov-action@v1
39 | if: ${{ matrix.python-version == '3.9' }}
40 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = accupy
3 | version = 0.3.6
4 | author = Nico Schlömer
5 | author_email = nico.schloemer@gmail.com
6 | description = Accurate sums and dot products for Python
7 | url = https://github.com/nschloe/accupy
8 | project_urls =
9 | Code=https://github.com/nschloe/accupy
10 | Issues=https://github.com/nschloe/accupy/issues
11 | Funding=https://github.com/sponsors/nschloe
12 | long_description = file: README.md
13 | long_description_content_type = text/markdown
14 | license = GPL-3.0-or-later
15 | classifiers =
16 | Development Status :: 4 - Beta
17 | License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
18 | Operating System :: OS Independent
19 | Programming Language :: Python
20 | Programming Language :: Python :: 3
21 | Programming Language :: Python :: 3.7
22 | Programming Language :: Python :: 3.8
23 | Programming Language :: Python :: 3.9
24 | Topic :: Scientific/Engineering
25 | Topic :: Scientific/Engineering :: Mathematics
26 | keywords =
27 | mathematics
28 | physics
29 | engineering
30 | cgal
31 | mesh
32 | mesh generation
33 |
34 | [options]
35 | packages = find:
36 | install_requires =
37 | mpmath
38 | numpy >= 1.20.0
39 | pyfma
40 | python_requires = >=3.7
41 |
--------------------------------------------------------------------------------
/accupy/dot.py:
--------------------------------------------------------------------------------
1 | import _accupy
2 | import numpy as np
3 | from numpy.typing import ArrayLike
4 |
5 | from .sums import fsum, ksum
6 |
7 | # def dot2(x, y, prod2=prod2_fma):
8 | # '''Algorithm 5.3. Dot product in twice the working precision.
9 | # in .
10 | # '''
11 | # p, s = prod2(x[0], y[0])
12 | # n = len(x)
13 | # for k in range(1, n):
14 | # h, r = prod2(x[k], y[k])
15 | # p, q = knuth_sum(p, h)
16 | # s += q+r
17 | # return p + s
18 |
19 |
20 | def kdot(x: ArrayLike, y: ArrayLike, K: int = 2) -> float:
21 | """Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3."""
22 | x = np.asarray(x)
23 | y = np.asarray(y)
24 |
25 | xx = x.reshape(-1, x.shape[-1])
26 | yy = y.reshape(y.shape[0], -1)
27 |
28 | xx = np.ascontiguousarray(xx)
29 | yy = np.ascontiguousarray(yy)
30 |
31 | r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1] + y.shape[1:])
32 | return ksum(r, K - 1)
33 |
34 |
35 | def fdot(x: ArrayLike, y: ArrayLike) -> float:
36 | """Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3."""
37 | x = np.asarray(x)
38 | y = np.asarray(y)
39 |
40 | xx = x.reshape(-1, x.shape[-1])
41 | yy = y.reshape(y.shape[0], -1)
42 |
43 | xx = np.ascontiguousarray(xx)
44 | yy = np.ascontiguousarray(yy)
45 |
46 | r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1] + y.shape[1:])
47 | return fsum(r)
48 |
--------------------------------------------------------------------------------
/accupy/sums.py:
--------------------------------------------------------------------------------
1 | import math
2 | from typing import Tuple
3 |
4 | import _accupy
5 | import numpy as np
6 | from numpy.typing import ArrayLike
7 |
8 |
9 | def knuth_sum(a: float, b: float) -> Tuple[float, float]:
10 | """Error-free transformation of the sum of two floating point numbers according to
11 |
12 | D.E. Knuth.
13 | The Art of Computer Programming: Seminumerical Algorithms, volume 2.
14 | Addison Wesley, Reading, Massachusetts, second edition, 1981.
15 |
16 | The underlying problem is that the exact sum a+b of two floating point number a and
17 | b is not necessarily a floating point number; for example if you add a very large
18 | and a very small number. It is however known that the difference between the best
19 | floating point approximation of a+b and the exact a+b is again a floating point
20 | number. This routine returns the sum and the error.
21 |
22 | Algorithm 3.1 in .
23 | """
24 | x = a + b
25 | z = x - a
26 | y = (a - (x - z)) + (b - z)
27 | return x, y
28 |
29 |
30 | def decker_sum(a: float, b: float) -> Tuple[float, float]:
31 | """Computationally equivalent to knuth_sum, but formally a bit cheaper.
32 | Only works for floats though (and not arrays), and the branch make it in
33 | fact less favorable in terms of actual speed.
34 | """
35 | x = a + b
36 | y = b - (x - a) if abs(a) > abs(b) else a - (x - b)
37 | return x, y
38 |
39 |
40 | def distill(p: ArrayLike, K: int) -> np.ndarray:
41 | """Algorithm 4.3. Error-free vector transformation for summation.
42 |
43 | The vector p is transformed without changing the sum, and p_n is replaced
44 | by float(sum(p)). Kahan [21] calls this a 'distillation algorithm.'
45 | """
46 | p = np.asarray(p)
47 |
48 | q = p.reshape(p.shape[0], -1)
49 | for _ in range(K):
50 | _accupy.distill(q)
51 | return q.reshape(p.shape)
52 |
53 |
54 | def ksum(p: ArrayLike, K: int = 2) -> float:
55 | """From
56 |
57 | T. Ogita, S.M. Rump, and S. Oishi.
58 | Accurate Sum and Dot Product,
59 | SIAM J. Sci. Comput., 26(6), 1955–1988 (34 pages).
60 | .
61 |
62 | Algorithm 4.8. Summation as in K-fold precision by (K−1)-fold error-free
63 | vector transformation.
64 | """
65 | # Don't override the input data.
66 | p = np.asarray(p)
67 | q = p.copy()
68 | distill(q, K - 1)
69 | return np.sum(q[:-1], axis=0) + q[-1]
70 |
71 |
72 | _math_fsum_vec = np.vectorize(math.fsum, signature="(m)->()")
73 |
74 |
75 | def fsum(p: ArrayLike) -> float:
76 | p = np.asarray(p)
77 | return _math_fsum_vec(p.T).T
78 |
79 |
80 | def kahan_sum(p: ArrayLike) -> float:
81 | """Kahan summation
82 | .
83 | """
84 | p = np.asarray(p)
85 | q = p.reshape(p.shape[0], -1)
86 | s = _accupy.kahan(q)
87 | return s.reshape(p.shape[1:])
88 |
--------------------------------------------------------------------------------
/accupy/ill_cond.py:
--------------------------------------------------------------------------------
1 | import math
2 | from typing import Optional, Tuple
3 |
4 | import numpy as np
5 | import pyfma
6 | from mpmath import mp
7 | from numpy.typing import ArrayLike
8 |
9 | from .dot import fdot, fsum
10 |
11 |
12 | def cond(
13 | x: ArrayLike, y: Optional[ArrayLike] = None, dps: Optional[int] = None
14 | ) -> float:
15 | """Compute the condition number of a sum (if only x is given) or a dot-product (if
16 | both x and y are given).
17 | """
18 | if dps is None:
19 | sum_exact = fsum
20 | dot_exact = fdot
21 | else:
22 | mp.dps = dps
23 | sum_exact = mp.fsum
24 | dot_exact = mp.fdot
25 |
26 | if y is None:
27 | return sum_exact(np.abs(x)) / np.abs(sum_exact(x))
28 |
29 | return 2 * dot_exact(np.abs(x), np.abs(y)) / abs(dot_exact(x, y))
30 |
31 |
32 | def generate_ill_conditioned_sum(
33 | n: int, c: float, dps: int = 100
34 | ) -> Tuple[np.ndarray, float, float]:
35 | # From :
36 | # Ill-conditioned sums of length 2n are generated from dot products of
37 | # length n using Algorithm 3.3 (TwoProduct) and randomly permuting the
38 | # summands.
39 | x, y, _, C = generate_ill_conditioned_dot_product(n, c, dps)
40 |
41 | prod = x * y
42 | err = pyfma.fma(x, y, -prod)
43 | res = np.array([prod, err])
44 |
45 | out = np.random.permutation(res.flatten())
46 |
47 | mp.dps = dps
48 | sum_exact = mp.fsum
49 |
50 | exact = sum_exact(out)
51 |
52 | # condition = fsum(np.abs(out)) / abs(exact)
53 | condition = C / 2
54 |
55 | return out, exact, condition
56 |
57 |
58 | def generate_ill_conditioned_dot_product(
59 | n: int, c: float, dps: int = 100
60 | ) -> Tuple[np.ndarray, np.ndarray, float, float]:
61 | """n ... length of vector
62 | c ... target condition number
63 | """
64 | # Algorithm 6.1 from
65 | #
66 | # ACCURATE SUM AND DOT PRODUCT,
67 | # TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI.
68 | assert n >= 6
69 | n2 = round(n / 2)
70 | x = np.zeros(n)
71 | y = np.zeros(n)
72 |
73 | b = math.log2(c)
74 | # vector of exponents between 0 and b/2:
75 | e = np.rint(np.random.rand(n2) * b / 2).astype(int)
76 | # make sure exponents b/2 and 0 actually occur in e
77 | # vectors x,y
78 | e[0] = round(b / 2) + 1
79 | e[-1] = 0
80 |
81 | # generate first half of vectors x, y
82 | rx, ry = np.random.rand(2, n2)
83 | x[:n2] = (2 * rx - 1) * 2 ** e
84 | y[:n2] = (2 * ry - 1) * 2 ** e
85 |
86 | mp.dps = dps
87 | dot_exact = mp.fdot
88 |
89 | # for i=n2+1:n and v=1:i,
90 | # generate x_i, y_i such that (*) x(v)’*y(v) ~ 2^e(i-n2)
91 | # generate exponents for second half
92 | e = np.rint(np.linspace(b / 2, 0, n - n2)).astype(int)
93 | rx, ry = np.random.rand(2, n2)
94 | for i in range(n2, n):
95 | # x_i random with generated exponent
96 | x[i] = (2 * rx[i - n2] - 1) * 2 ** e[i - n2]
97 | # y_i according to (*)
98 | y[i] = (
99 | (2 * ry[i - n2] - 1) * 2 ** e[i - n2] - dot_exact(x[: i + 1], y[: i + 1])
100 | ) / x[i]
101 |
102 | x, y = np.random.permutation((x, y))
103 | # the true dot product rounded to nearest floating point
104 | d = dot_exact(x, y)
105 | # the actual condition number
106 | C = 2 * dot_exact(abs(x), abs(y)) / abs(d)
107 |
108 | return x, y, d, C
109 |
--------------------------------------------------------------------------------
/tests/test_dot.py:
--------------------------------------------------------------------------------
1 | import dufte
2 | import matplotlib.pyplot as plt
3 | import numpy as np
4 | import perfplot
5 | import pytest
6 |
7 | import accupy
8 |
9 |
10 | def test_cond():
11 | cond = accupy.cond([np.pi, np.e], [23225 / 8544, -355 / 113])
12 | print(cond)
13 | ref = 4.852507317687677e7
14 | assert abs(cond - ref) < 1.0e-13 * abs(ref)
15 |
16 |
17 | @pytest.mark.parametrize("cond", [1.0, 1.0e15])
18 | def test_kdot2(cond):
19 | x, y, ref, _ = accupy.generate_ill_conditioned_dot_product(100, cond)
20 | assert abs(accupy.kdot(x, y, K=2) - ref) < 1.0e-13 * abs(ref)
21 |
22 |
23 | @pytest.mark.parametrize("cond", [1.0, 1.0e15, 1.0e30])
24 | def test_kdot3(cond):
25 | x, y, ref, _ = accupy.generate_ill_conditioned_dot_product(100, cond)
26 | assert abs(accupy.kdot(x, y, K=3) - ref) < 1.0e-13 * abs(ref)
27 |
28 |
29 | @pytest.mark.parametrize("cond", [1.0, 1.0e15, 1.0e30, 1.0e38])
30 | def test_fdot(cond):
31 | x, y, ref, _ = accupy.generate_ill_conditioned_dot_product(100, cond)
32 | assert abs(accupy.fdot(x, y) - ref) < 1.0e-13 * abs(ref)
33 |
34 |
35 | def test_accuracy_comparison_illcond(target_cond=None):
36 | plt.style.use(dufte.style)
37 |
38 | if target_cond is None:
39 | target_cond = [10 ** k for k in range(2)]
40 |
41 | kernels = [
42 | np.dot,
43 | lambda x, y: accupy.kdot(x, y, K=2),
44 | lambda x, y: accupy.kdot(x, y, K=3),
45 | accupy.fdot,
46 | ]
47 | labels = ["np.dot", "accupy.kdot[2]", "accupy.kdot[3]", "accupy.fdot"]
48 | data = np.empty((len(target_cond), len(kernels)))
49 | condition_numbers = np.empty(len(target_cond))
50 | np.random.seed(0)
51 | for k, tc in enumerate(target_cond):
52 | x, y, ref, C = accupy.generate_ill_conditioned_dot_product(1000, tc)
53 | condition_numbers[k] = C
54 | data[k] = [abs(kernel(x, y) - ref) / abs(ref) for kernel in kernels]
55 |
56 | # sort
57 | s = np.argsort(condition_numbers)
58 | condition_numbers = condition_numbers[s]
59 | data = data[s]
60 |
61 | for label, d in zip(labels, data.T):
62 | plt.loglog(condition_numbers, d, label=label)
63 |
64 | dufte.legend()
65 | plt.xlabel("condition number")
66 | dufte.ylabel("relative error")
67 |
68 |
69 | def test_speed_comparison1(n_range=None):
70 | plt.style.use(dufte.style)
71 |
72 | if n_range is None:
73 | n_range = [2 ** k for k in range(2)]
74 |
75 | np.random.seed(0)
76 | perfplot.plot(
77 | setup=lambda n: (np.random.rand(n, 100), np.random.rand(100, n)),
78 | kernels=[
79 | lambda xy: np.dot(*xy),
80 | lambda xy: accupy.kdot(*xy, K=2),
81 | lambda xy: accupy.kdot(*xy, K=3),
82 | lambda xy: accupy.fdot(*xy),
83 | ],
84 | labels=["np.dot", "accupy.kdot[2]", "accupy.kdot[3]", "accupy.fdot"],
85 | n_range=n_range,
86 | xlabel="n",
87 | )
88 | plt.title("dot(random(n, 100), random(100, n))")
89 |
90 |
91 | def test_speed_comparison2(n_range=None):
92 | if n_range is None:
93 | n_range = [2 ** k for k in range(2)]
94 |
95 | np.random.seed(0)
96 | perfplot.plot(
97 | setup=lambda n: (np.random.rand(100, n), np.random.rand(n, 100)),
98 | kernels=[
99 | lambda xy: np.dot(*xy),
100 | lambda xy: accupy.kdot(*xy, K=2),
101 | lambda xy: accupy.kdot(*xy, K=3),
102 | lambda xy: accupy.fdot(*xy),
103 | ],
104 | labels=["np.dot", "accupy.kdot[2]", "accupy.kdot[3]", "accupy.fdot"],
105 | n_range=n_range,
106 | xlabel="n",
107 | logx=True,
108 | logy=True,
109 | )
110 | plt.title("dot(random(100, n), random(n, 100))")
111 |
112 |
113 | def test_discontiguous():
114 | x = np.random.rand(3, 10)
115 | y = np.random.rand(3, 10)
116 | accupy.kdot(x.T, y)
117 | accupy.fdot(x.T, y)
118 |
119 |
120 | if __name__ == "__main__":
121 | test_accuracy_comparison_illcond([10 ** k for k in range(0, 37, 1)])
122 | plt.savefig("accuracy-dot.svg", transparent=True, bbox_inches="tight")
123 | plt.close()
124 |
125 | test_speed_comparison1(n_range=[2 ** k for k in range(8)])
126 | plt.savefig("speed-comparison-dot1.svg", transparent=True, bbox_inches="tight")
127 | plt.close()
128 |
129 | test_speed_comparison2(n_range=[2 ** k for k in range(8)])
130 | plt.savefig("speed-comparison-dot2.svg", transparent=True, bbox_inches="tight")
131 | plt.close()
132 |
--------------------------------------------------------------------------------
/src/pybind11.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | #include
8 |
9 | namespace py = pybind11;
10 | using namespace pybind11::literals;
11 |
12 |
13 | // =============================================================================
14 | // sum.h
15 | // =============================================================================
16 | // void
17 | // distill(py::array_t p) {
18 | // auto r = p.mutable_unchecked<2>();
19 | // for (ssize_t i = 1; i < r.shape(0); i++) {
20 | // for (ssize_t j = 0; j < r.shape(1); j++) {
21 | // double x = r(i, j) + r(i-1, j);
22 | // double z = x - r(i, j);
23 | // double y = (r(i, j) - (x-z)) + (r(i-1, j) - z);
24 | // r(i, j) = x;
25 | // r(i-1, j) = y;
26 | // }
27 | // }
28 | // }
29 |
30 | using RowMatrixXd = Eigen::Matrix;
31 |
32 | // Algorithm 4.3. Error-free vector transformation for summation.
33 | //
34 | // The vector p is transformed without changing the sum, and p_n is replaced
35 | // by float(sum(p)). Kahan [21] calls this a "distillation algorithm".
36 | void
37 | distill(Eigen::Ref r) {
38 | for (int i = 1; i < r.rows(); i++) {
39 | auto x = r.row(i) + r.row(i-1);
40 | auto z = x - r.row(i);
41 | for (int j = 0; j < r.cols(); j++) {
42 | const double xj = x(j);
43 | r(i-1, j) = (r(i, j) - (x(j) - z(j))) + (r(i-1, j) - z(j));
44 | r(i, j) = xj;
45 | }
46 | }
47 | }
48 |
49 |
50 | py::array_t
51 | kahan(py::array_t p) {
52 | // Kahan summation.
53 | // See for
54 | // details.
55 | auto buf_p = p.request();
56 | if (buf_p.ndim != 2)
57 | throw std::runtime_error("Number of dimensions must be two");
58 |
59 | const ssize_t m = buf_p.shape[0];
60 | const ssize_t n = buf_p.shape[1];
61 |
62 | auto s = py::array_t(n);
63 | auto buf_s = s.request();
64 |
65 | auto c = py::array_t(n);
66 | auto buf_c = c.request();
67 |
68 | double *ptr_p = (double *) buf_p.ptr;
69 | double *ptr_c = (double *) buf_c.ptr;
70 | double *ptr_s = (double *) buf_s.ptr;
71 |
72 | // zero out c and s
73 | std::fill(ptr_c, ptr_c+n, 0.0);
74 | std::fill(ptr_s, ptr_s+n, 0.0);
75 |
76 | // Kahan
77 | for (ssize_t i = 0; i < m; i++) {
78 | for (ssize_t j = 0; j < n; j++) {
79 | double y = ptr_p[i*n + j] - ptr_c[j];
80 | double t = ptr_s[j] + y;
81 | ptr_c[j] = (t - ptr_s[j]) - y;
82 | ptr_s[j] = t;
83 | }
84 | }
85 | return s;
86 | }
87 | // =============================================================================
88 | // dot.h
89 | // Headers aren't automatically installed though;
90 | // .
91 | // =============================================================================
92 | using RowMatrixXd = Eigen::Matrix;
93 |
94 | py::array_t
95 | kdot_helper(Eigen::Ref x, Eigen::Ref y) {
96 | // Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3.
97 | if (x.cols() != y.rows())
98 | throw std::runtime_error("Input shapes must match");
99 |
100 | const int n = x.cols();
101 |
102 | // Use Eigen::Tensor to avoid stack overflows with native C arrays.
103 | Eigen::Tensor result(2, n, x.rows(), y.cols());
104 |
105 | // After the loop, p will hold the naive values of the dot product, result(0)
106 | // the multiplication errors and result(1) the addition errors.
107 | auto p = RowMatrixXd(x.rows(), y.cols());
108 | p.setZero();
109 |
110 | // Use ikj ordering for speed; see, e.g.,
111 | //
112 | for (int i=0; i < x.rows(); i++) {
113 | for (int k=0; k < n; k++) {
114 | for (int j=0; j < y.cols(); j++) {
115 | // product with exact error
116 | double h = x(i, k) * y(k, j);
117 | result(0, k, i, j) = fma(x(i, k), y(k, j), -h);
118 | // Knuth sum: p+h with exact error z2
119 | double z0 = p(i, j) + h;
120 | double z1 = z0 - p(i, j);
121 | double z2 = (p(i, j) - (z0-z1)) + (h-z1);
122 | p(i, j) = z0;
123 | result(1, k, i, j) = z2;
124 | }
125 | }
126 | }
127 |
128 | // Override the meaningless first addition error; it's exactly 0.0 anyways.
129 | for (int i=0; i < x.rows(); i++)
130 | for (int j=0; j < y.cols(); j++)
131 | result(1, 0, i, j) = p(i, j);
132 |
133 | return py::array_t(
134 | std::vector{2, n, x.rows(), y.cols()},
135 | result.data()
136 | );
137 | }
138 | // =============================================================================
139 | PYBIND11_MODULE(_accupy, m) {
140 | // sum:
141 | m.def("distill", &distill, "r"_a.noconvert());
142 | m.def("kahan", &kahan, "p"_a.noconvert());
143 | // dot:
144 | m.def("kdot_helper", &kdot_helper, "x"_a.noconvert(), "y"_a.noconvert());
145 | }
146 |
--------------------------------------------------------------------------------
/tests/test_sums.py:
--------------------------------------------------------------------------------
1 | import dufte
2 | import matplotlib.pyplot as plt
3 | import numpy as np
4 | import perfplot
5 | import pytest
6 |
7 | import accupy
8 |
9 |
10 | def test_cond():
11 | cond = accupy.cond([1.0, 1.0e-16, -1.0])
12 | ref = 2.0e16
13 | assert abs(cond - ref) < 1.0e-13 * abs(ref)
14 |
15 |
16 | @pytest.mark.parametrize("cond", [1.0, 1.0e15])
17 | def test_ksum2(cond):
18 | p, ref, _ = accupy.generate_ill_conditioned_sum(100, cond)
19 | assert abs(accupy.ksum(p, K=2) - ref) < 1.0e-15 * abs(ref)
20 |
21 |
22 | @pytest.mark.parametrize("cond", [1.0, 1.0e15, 1.0e30])
23 | def test_ksum3(cond):
24 | p, ref, _ = accupy.generate_ill_conditioned_sum(100, cond)
25 | assert abs(accupy.ksum(p, K=3) - ref) < 1.0e-15 * abs(ref)
26 |
27 |
28 | @pytest.mark.parametrize("cond", [1.0, 1.0e15, 1.0e30, 1.0e35])
29 | def test_fsum(cond):
30 | p, ref, _ = accupy.generate_ill_conditioned_sum(100, cond)
31 | assert abs(accupy.fsum(p) - ref) < 1.0e-15 * abs(ref)
32 |
33 |
34 | def test_accuracy_comparison_illcond(target_conds=None):
35 | plt.style.use(dufte.style)
36 |
37 | if target_conds is None:
38 | target_conds = [10 ** k for k in range(1, 2)]
39 |
40 | kernels = [
41 | sum,
42 | np.sum,
43 | accupy.kahan_sum,
44 | lambda p: accupy.ksum(p, K=2),
45 | lambda p: accupy.ksum(p, K=3),
46 | accupy.fsum,
47 | ]
48 | labels = [
49 | "sum",
50 | "np.sum",
51 | "accupy.kahan_sum",
52 | "accupy.ksum[2]",
53 | "accupy.ksum[3]",
54 | "accupy.fsum",
55 | ]
56 | colors = plt.rcParams["axes.prop_cycle"].by_key()["color"][: len(labels)]
57 |
58 | data = np.empty((len(target_conds), len(kernels)))
59 | condition_numbers = np.empty(len(target_conds))
60 | np.random.seed(0)
61 | for k, target_cond in enumerate(target_conds):
62 | p, ref, C = accupy.generate_ill_conditioned_sum(1000, target_cond)
63 | condition_numbers[k] = C
64 | data[k] = [abs(kernel(p) - ref) / abs(ref) for kernel in kernels]
65 |
66 | # sort
67 | s = np.argsort(condition_numbers)
68 | condition_numbers = condition_numbers[s]
69 | data = data[s]
70 |
71 | for label, color, d in zip(labels, colors, data.T):
72 | plt.loglog(condition_numbers, d, label=label, color=color)
73 |
74 | dufte.legend()
75 | plt.xlabel("condition number")
76 | dufte.ylabel("relative error")
77 | # plt.gca().set_aspect(1.3)
78 |
79 |
80 | def test_speed_comparison1(n_range=None):
81 | plt.style.use(dufte.style)
82 |
83 | if n_range is None:
84 | n_range = [2 ** k for k in range(2)]
85 |
86 | np.random.seed(0)
87 | perfplot.plot(
88 | setup=lambda n: np.random.rand(n, 100),
89 | kernels=[
90 | sum,
91 | lambda p: np.sum(p, axis=0),
92 | accupy.kahan_sum,
93 | lambda p: accupy.ksum(p, K=2),
94 | lambda p: accupy.ksum(p, K=3),
95 | accupy.fsum,
96 | ],
97 | labels=[
98 | "sum",
99 | "np.sum",
100 | "accupy.kahan_sum",
101 | "accupy.ksum[2]",
102 | "accupy.ksum[3]",
103 | "accupy.fsum",
104 | ],
105 | n_range=n_range,
106 | xlabel="n",
107 | )
108 | plt.title("Sum(random(n, 100))")
109 |
110 |
111 | def test_speed_comparison2(n_range=None):
112 | plt.style.use(dufte.style)
113 |
114 | if n_range is None:
115 | n_range = [2 ** k for k in range(2)]
116 |
117 | np.random.seed(0)
118 | perfplot.plot(
119 | setup=lambda n: np.random.rand(100, n),
120 | kernels=[
121 | sum,
122 | lambda p: np.sum(p, axis=0),
123 | accupy.kahan_sum,
124 | lambda p: accupy.ksum(p, K=2),
125 | lambda p: accupy.ksum(p, K=3),
126 | accupy.fsum,
127 | ],
128 | labels=[
129 | "sum",
130 | "np.sum",
131 | "accupy.kahan_sum",
132 | "accupy.ksum[2]",
133 | "accupy.ksum[3]",
134 | "accupy.fsum",
135 | ],
136 | n_range=n_range,
137 | xlabel="n",
138 | )
139 | plt.title("Sum(random(100, n))")
140 |
141 |
142 | def test_knuth_sum():
143 | a16 = np.float16(1.0e1)
144 | b16 = np.float16(1.0e-1)
145 | x16, y16 = accupy.knuth_sum(a16, b16)
146 | xy = np.float64(x16) + np.float64(y16)
147 | ab = np.float64(a16) + np.float64(b16)
148 | assert abs(xy - ab) < 1.0e-15 * ab
149 |
150 |
151 | def test_decker_sum():
152 | a16 = np.float16(1.0e1)
153 | b16 = np.float16(1.0e-1)
154 | x16, y16 = accupy.decker_sum(a16, b16)
155 | xy = np.float64(x16) + np.float64(y16)
156 | ab = np.float64(a16) + np.float64(b16)
157 | assert abs(xy - ab) < 1.0e-15 * ab
158 |
159 |
160 | def test_discontiguous():
161 | x = np.random.rand(3, 10).T
162 | accupy.ksum(x.T)
163 | accupy.fsum(x.T)
164 |
165 |
166 | if __name__ == "__main__":
167 | test_accuracy_comparison_illcond([10 ** k for k in range(0, 37, 1)])
168 | plt.savefig("accuracy-sum.svg", transparent=True, bbox_inches="tight")
169 | plt.close()
170 |
171 | test_speed_comparison1(n_range=[2 ** k for k in range(15)])
172 | plt.savefig("speed-comparison1.svg", transparent=True, bbox_inches="tight")
173 | plt.close()
174 |
175 | test_speed_comparison2(n_range=[2 ** k for k in range(15)])
176 | plt.savefig("speed-comparison2.svg", transparent=True, bbox_inches="tight")
177 | plt.close()
178 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Accurate sums and (dot) products for Python.
4 |
5 |
6 | [](https://pypi.org/project/accupy)
7 | [](https://pypi.org/pypi/accupy/)
8 | [](https://doi.org/10.5281/zenodo.1185173)
9 | [](https://github.com/nschloe/accupy)
10 | [](https://pypistats.org/packages/accupy)
11 |
12 | [](https://discord.gg/hnTJ5MRX2Y)
13 |
14 | [](https://github.com/nschloe/accupy/actions?query=workflow%3Aci)
15 | [](https://codecov.io/gh/nschloe/accupy)
16 | [](https://github.com/psf/black)
17 |
18 | ### Sums
19 |
20 | Summing up values in a list can get tricky if the values are floating point
21 | numbers; digit cancellation can occur and the result may come out wrong. A
22 | classical example is the sum
23 |
24 | ```
25 | 1.0e16 + 1.0 - 1.0e16
26 | ```
27 |
28 | The actual result is `1.0`, but in double precision, this will result in `0.0`.
29 | While in this example the failure is quite obvious, it can get a lot more
30 | tricky than that. accupy provides
31 |
32 | ```python
33 | p, exact, cond = accupy.generate_ill_conditioned_sum(100, 1.0e20)
34 | ```
35 |
36 | which, given a length and a target condition number, will produce an array of
37 | floating point numbers that is hard to sum up.
38 |
39 | Given one or two vectors, accupy can compute the condition of the sum or dot product via
40 |
41 | ```python
42 | accupy.cond(x)
43 | accupy.cond(x, y)
44 | ```
45 |
46 | accupy has the following methods for summation:
47 |
48 | - `accupy.kahan_sum(p)`: [Kahan
49 | summation](https://en.wikipedia.org/wiki/Kahan_summation_algorithm)
50 |
51 | - `accupy.fsum(p)`: A vectorization wrapper around
52 | [math.fsum](https://docs.python.org/3/library/math.html#math.fsum) (which
53 | uses Shewchuck's algorithm [[1]](#references) (see also
54 | [here](https://code.activestate.com/recipes/393090/))).
55 |
56 | - `accupy.ksum(p, K=2)`: Summation in K-fold precision (from [[2]](#references))
57 |
58 | All summation methods sum the first dimension of a multidimensional NumPy array.
59 |
60 | Let's compare them.
61 |
62 | #### Accuracy comparison (sum)
63 |
64 | 
65 |
66 | As expected, the naive
67 | [sum](https://docs.python.org/3/library/functions.html#sum) performs very badly
68 | with ill-conditioned sums; likewise for
69 | [`numpy.sum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html)
70 | which uses pairwise summation. Kahan summation not significantly better; [this,
71 | too, is
72 | expected](https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Accuracy).
73 |
74 | Computing the sum with 2-fold accuracy in `accupy.ksum` gives the correct
75 | result if the condition is at most in the range of machine precision; further
76 | increasing `K` helps with worse conditions.
77 |
78 | Shewchuck's algorithm in `math.fsum` always gives the correct result to full
79 | floating point precision.
80 |
81 | #### Runtime comparison (sum)
82 |
83 | 
84 |
85 | 
86 |
87 | We compare more and more sums of fixed size (above) and larger and larger sums,
88 | but a fixed number of them (below). In both cases, the least accurate method is
89 | the fastest (`numpy.sum`), and the most accurate the slowest (`accupy.fsum`).
90 |
91 | ### Dot products
92 |
93 | accupy has the following methods for dot products:
94 |
95 | - `accupy.fdot(p)`: A transformation of the dot product of length _n_ into a
96 | sum of length _2n_, computed with
97 | [math.fsum](https://docs.python.org/3/library/math.html#math.fsum)
98 |
99 | - `accupy.kdot(p, K=2)`: Dot product in K-fold precision (from
100 | [[2]](#references))
101 |
102 | Let's compare them.
103 |
104 | #### Accuracy comparison (dot)
105 |
106 | accupy can construct ill-conditioned dot products with
107 |
108 | ```python
109 | x, y, exact, cond = accupy.generate_ill_conditioned_dot_product(100, 1.0e20)
110 | ```
111 |
112 | With this, the accuracy of the different methods is compared.
113 |
114 | 
115 |
116 | As for sums, `numpy.dot` is the least accurate, followed by instanced of `kdot`.
117 | `fdot` is provably accurate up into the last digit
118 |
119 | #### Runtime comparison (dot)
120 |
121 | 
122 | 
123 |
124 | NumPy's `numpy.dot` is _much_ faster than all alternatives provided by accupy.
125 | This is because the bookkeeping of truncation errors takes more steps, but
126 | mostly because of NumPy's highly optimized dot implementation.
127 |
128 | ### References
129 |
130 | 1. [Richard Shewchuk, _Adaptive Precision Floating-Point Arithmetic and Fast
131 | Robust Geometric Predicates_, J. Discrete Comput. Geom. (1997), 18(305),
132 | 305–363](https://doi.org/10.1007/PL00009321)
133 |
134 | 2. [Takeshi Ogita, Siegfried M. Rump, and Shin'ichi Oishi, _Accurate Sum and Dot
135 | Product_, SIAM J. Sci. Comput. (2006), 26(6), 1955–1988 (34
136 | pages)](https://doi.org/10.1137/030601818)
137 |
138 | ### Dependencies
139 |
140 | accupy needs the C++ [Eigen
141 | library](http://eigen.tuxfamily.org/index.php?title=Main_Page), provided in
142 | Debian/Ubuntu by
143 | [`libeigen3-dev`](https://packages.ubuntu.com/search?keywords=libeigen3-dev).
144 |
145 | ### Installation
146 |
147 | accupy is [available from the Python Package Index](https://pypi.org/project/accupy/), so with
148 |
149 | ```
150 | pip install accupy
151 | ```
152 |
153 | you can install.
154 |
155 | ### Testing
156 |
157 | To run the tests, just check out this repository and type
158 |
159 | ```
160 | MPLBACKEND=Agg pytest
161 | ```
162 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------