├── .codecov.yml ├── src └── cplot │ ├── __about__.py │ ├── __init__.py │ ├── _riemann_sphere.py │ ├── _tri.py │ ├── benchmark.py │ ├── _colors.py │ └── _main.py ├── .flake8 ├── tests ├── test_riemann.py ├── test_plot.py ├── test_tools.py ├── logo.py ├── test_tripcolor.py └── generate-readme-figures.py ├── .gitignore ├── tox.ini ├── CITATION.cff ├── .pre-commit-config.yaml ├── anim ├── create-az-anim.py ├── create-za-anim.py ├── justfile └── create-taylor-anim.py ├── justfile ├── .github └── workflows │ └── tests.yml ├── pyproject.toml ├── experiments └── create.py ├── README.md └── LICENSE /.codecov.yml: -------------------------------------------------------------------------------- 1 | comment: no 2 | -------------------------------------------------------------------------------- /src/cplot/__about__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.9.3" 2 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E203, E266, E501, W503 3 | max-line-length = 80 4 | max-complexity = 18 5 | select = B,C,E,F,W,T4,B9 6 | -------------------------------------------------------------------------------- /tests/test_riemann.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pytest 3 | 4 | import cplot 5 | 6 | 7 | def test_riemann(): 8 | pytest.importorskip("pyvista") 9 | cplot.riemann_sphere(np.log, off_screen=True) 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.prof 4 | MANIFEST 5 | README.rst 6 | dist/ 7 | build/ 8 | .coverage 9 | .cache/ 10 | *.egg-info/ 11 | .pytest_cache/ 12 | *.png 13 | *.svg 14 | .tox/ 15 | plots/ 16 | experiments/ 17 | article/ 18 | -------------------------------------------------------------------------------- /tests/test_plot.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cplot 4 | 5 | 6 | def test_basic(): 7 | def f(z): 8 | return np.sin(z**3) / z 9 | 10 | plt = cplot.plot(f, (-2.0, +2.0, 400), (-2.0, +2.0, 400)) 11 | plt.show() 12 | -------------------------------------------------------------------------------- /tests/test_tools.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cplot 4 | 5 | 6 | def test_array(): 7 | np.random.seed(0) 8 | n = 5 9 | z = np.random.rand(n) + 1j * np.random.rand(n) 10 | vals = cplot.get_srgb1(z) 11 | assert vals.shape == (n, 3) 12 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py3 3 | isolated_build = True 4 | 5 | [testenv] 6 | deps = 7 | pytest 8 | pytest-codeblocks >= 0.15.0 9 | pytest-cov 10 | pytest-randomly 11 | mpmath 12 | scipy 13 | extras = all 14 | commands = 15 | pytest {posargs} --codeblocks 16 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this software, please cite it as below." 3 | authors: 4 | - family-names: "Schlömer" 5 | given-names: "Nico" 6 | orcid: "https://orcid.org/0000-0001-5228-0946" 7 | title: "cplot: Plot complex functions" 8 | doi: 10.5281/zenodo.5599493 9 | url: https://github.com/nschloe/cplot 10 | license: GPL-3.0 11 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/PyCQA/isort 3 | rev: 5.11.4 4 | hooks: 5 | - id: isort 6 | 7 | - repo: https://github.com/python/black 8 | rev: 22.12.0 9 | hooks: 10 | - id: black 11 | language_version: python3 12 | 13 | - repo: https://github.com/PyCQA/flake8 14 | rev: 6.0.0 15 | hooks: 16 | - id: flake8 17 | -------------------------------------------------------------------------------- /anim/create-az-anim.py: -------------------------------------------------------------------------------- 1 | import matplotlib 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | import cplot 6 | 7 | # https://github.com/matplotlib/matplotlib/issues/23701#issuecomment-1222008929 8 | matplotlib.use("GTK3Agg") 9 | 10 | p = cplot.Plotter((-2.2, 2.2, 400), (-2.2, 2.2, 400)) 11 | 12 | for idx, a in enumerate(np.linspace(-5.0, 5.0, 501)): 13 | p.plot(a**p.Z) 14 | plt.suptitle(f"${{{a:.2f}}}^z$") 15 | plt.savefig(f"data/out{idx:04d}.png", bbox_inches="tight") 16 | plt.close() 17 | -------------------------------------------------------------------------------- /anim/create-za-anim.py: -------------------------------------------------------------------------------- 1 | import matplotlib 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | import cplot 6 | 7 | # https://github.com/matplotlib/matplotlib/issues/23701#issuecomment-1222008929 8 | matplotlib.use("GTK3Agg") 9 | 10 | p = cplot.Plotter((-2.2, 2.2, 400), (-2.2, 2.2, 400)) 11 | 12 | for idx, a in enumerate(np.linspace(-5.0, 5.0, 501)): 13 | p.plot(p.Z**a) 14 | plt.suptitle(f"$z^{{{a:.2f}}}$") 15 | plt.savefig(f"data/out{idx:04d}.png", bbox_inches="tight") 16 | plt.close() 17 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | version := `python3 -c "from src.cplot.__about__ import __version__; print(__version__)"` 2 | 3 | default: 4 | @echo "\"just publish\"?" 5 | 6 | publish: clean 7 | @if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi 8 | gh release create "v{{version}}" 9 | python3 -m build --sdist --wheel . 10 | twine upload dist/* 11 | 12 | clean: 13 | @find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf 14 | @rm -rf src/*.egg-info/ build/ dist/ .tox/ 15 | 16 | format: 17 | isort . 18 | black . 19 | blacken-docs README.md 20 | 21 | lint: 22 | black --check . 23 | flake8 . 24 | -------------------------------------------------------------------------------- /src/cplot/__init__.py: -------------------------------------------------------------------------------- 1 | from .__about__ import __version__ 2 | from ._colors import get_srgb1 3 | from ._main import Plotter, plot, plot_abs, plot_arg, plot_contours, plot_phase 4 | from ._riemann_sphere import riemann_sphere 5 | from ._tri import tricontour_abs, tripcolor 6 | from .benchmark import show_kovesi_test_image, show_test_function 7 | 8 | __all__ = [ 9 | "show_test_function", 10 | "show_kovesi_test_image", 11 | "get_srgb1", 12 | "plot", 13 | "plot_arg", 14 | "plot_abs", 15 | "plot_phase", 16 | "plot_contours", 17 | # 18 | "riemann_sphere", 19 | # 20 | "tripcolor", 21 | "tricontour_abs", 22 | # 23 | "Plotter", 24 | # 25 | "__version__", 26 | ] 27 | -------------------------------------------------------------------------------- /.github/workflows/tests.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 | - uses: actions/checkout@v3 16 | - uses: actions/setup-python@v3 17 | - uses: pre-commit/action@v3.0.0 18 | 19 | build: 20 | runs-on: ubuntu-latest 21 | needs: [lint] 22 | strategy: 23 | matrix: 24 | python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] 25 | steps: 26 | - uses: actions/setup-python@v3 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | - uses: actions/checkout@v3 30 | - name: Test with tox 31 | run: | 32 | pip install tox 33 | tox -- --cov cplot --cov-report xml --cov-report term 34 | - uses: codecov/codecov-action@v1 35 | if: ${{ matrix.python-version == '3.11' }} 36 | -------------------------------------------------------------------------------- /anim/justfile: -------------------------------------------------------------------------------- 1 | opt: 2 | # for file in data/*.png; do convert -resize x400 $file $file; done 3 | # for file in data/*.png; do optipng -quiet $file; done 4 | for file in data/*.png; do optipng $file; done 5 | 6 | apng: 7 | # /kc is essential for the frames not to overlap 8 | apngasm out.png data/*.png /kc /kp 9 | 10 | gif: 11 | # 12 | convert -dispose 2 -delay 10 -loop 0 data/*.png out.gif 13 | 14 | webp: 15 | img2webp data/*.png -min_size -lossy -o out.webp 16 | 17 | mp4: 18 | ffmpeg -framerate 30 -i data/out%04d.png -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2:color=white" -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4 19 | 20 | webm: 21 | # ffmpeg -framerate 2 -i data/out%04d.png -c:v libaom-av1 -strict -2 -r 30 -pix_fmt yuv420p out.webm 22 | # ffmpeg -framerate 2 -i data/out%04d.png -c:v libvpx-vp9 out.webm 23 | # Two-pass encoding, see 24 | ffmpeg -framerate 30 -i data/out%04d.png -c:v libvpx-vp9 -b:v 0 -crf 30 -pass 1 -an -f null /dev/null && ffmpeg -framerate 2 -i data/out%04d.png -c:v libvpx-vp9 -b:v 0 -crf 30 -pass 2 -an out.webm 25 | -------------------------------------------------------------------------------- /tests/logo.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.tri as tri 3 | import numpy as np 4 | 5 | import cplot 6 | 7 | 8 | def create_logo(): 9 | # Adapted from 10 | # 11 | # First create the x and y coordinates of the points. 12 | n_angles = 314 13 | n_radii = 100 14 | radii = np.linspace(0.0, 1.0, n_radii) 15 | 16 | angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) 17 | angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) 18 | angles[:, 1::2] += np.pi / n_angles 19 | 20 | x = (radii * np.cos(angles)).flatten() 21 | y = (radii * np.sin(angles)).flatten() 22 | 23 | # Create the Triangulation; no triangles so Delaunay triangulation created. 24 | triang = tri.Triangulation(x, y) 25 | 26 | # print(triang) 27 | # exit(1) 28 | # import dmsh 29 | # geo = dmsh.Circle([0.0, 0.0], 1.0) 30 | # X, cells = dmsh.generate(geo, 0.1) 31 | 32 | z = x + 1j * y 33 | # z /= np.abs(z) 34 | 35 | cplot.tripcolor(triang, z, alpha=0) 36 | plt.gca().set_aspect("equal", "datalim") 37 | plt.axis("off") 38 | 39 | plt.savefig("logo.png", transparent=True) 40 | return 41 | 42 | 43 | if __name__ == "__main__": 44 | create_logo() 45 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.isort] 6 | profile = "black" 7 | 8 | [project] 9 | name = "cplot" 10 | authors = [{name = "Nico Schlömer", email = "nico.schloemer@gmail.com"}] 11 | description = "Plot complex-valued functions" 12 | readme = "README.md" 13 | license = {file = "LICENSE"} 14 | classifiers = [ 15 | "Development Status :: 4 - Beta", 16 | "Framework :: Matplotlib", 17 | "Intended Audience :: Science/Research", 18 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 19 | "Operating System :: OS Independent", 20 | "Programming Language :: Python", 21 | "Programming Language :: Python :: 3", 22 | "Programming Language :: Python :: 3.7", 23 | "Programming Language :: Python :: 3.8", 24 | "Programming Language :: Python :: 3.9", 25 | "Programming Language :: Python :: 3.10", 26 | "Topic :: Scientific/Engineering", 27 | "Topic :: Scientific/Engineering :: Visualization", 28 | ] 29 | dynamic = ["version"] 30 | requires-python = ">=3.7" 31 | dependencies = [ 32 | "matplotlib", 33 | "matplotx[all] >= 0.3.10", 34 | "npx", 35 | "numpy >= 1.20.0", 36 | ] 37 | 38 | [project.optional-dependencies] 39 | all = [ 40 | "meshzoo", 41 | "pyvista", 42 | ] 43 | 44 | [tool.setuptools.dynamic] 45 | version = {attr = "cplot.__about__.__version__"} 46 | 47 | [project.urls] 48 | Code = "https://github.com/nschloe/cplot" 49 | Issues = "https://github.com/nschloe/cplot/issues" 50 | Funding = "https://github.com/sponsors/nschloe" 51 | -------------------------------------------------------------------------------- /src/cplot/_riemann_sphere.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Callable 4 | 5 | import numpy as np 6 | 7 | from ._colors import get_srgb1 8 | from ._main import _abs_scaling_from_float 9 | 10 | 11 | def riemann_sphere( 12 | f: Callable[[np.ndarray], np.ndarray], 13 | filename: str | None = None, 14 | n: int = 50, 15 | # If you're changing contours_abs to x and want the abs_scaling to follow along, 16 | # you'll have to set it to the same value. 17 | abs_scaling: float | Callable[[np.ndarray], np.ndarray] = 2, 18 | saturation_adjustment: float = 1.28, 19 | off_screen: bool = False, 20 | ) -> None: 21 | import meshzoo 22 | import pyvista as pv 23 | import vtk 24 | 25 | # Use a "flat top" to make sure we never evaluate _exactly_ at infty or 0, 26 | # just close to it. May save a bit of numerical trouble. 27 | points, cells = meshzoo.icosa_sphere(n, flat_top=True) 28 | 29 | # stereographic projection onto complex plane 30 | x, y, z = points.T 31 | assert np.all(np.abs(x**2 + y**2 + z**2 - 1.0) < 1.0e-13) 32 | Z = (x + 1j * y) / (1 - z) 33 | 34 | rgb = get_srgb1( 35 | f(Z), 36 | abs_scaling if callable(abs_scaling) else _abs_scaling_from_float(abs_scaling), 37 | saturation_adjustment, 38 | ) 39 | 40 | celltypes = np.full(len(cells), vtk.VTK_TRIANGLE, dtype=np.uint8) 41 | cells = np.column_stack([np.full(cells.shape[0], cells.shape[1]), cells]).ravel() 42 | grid = pv.UnstructuredGrid(cells, celltypes, points) 43 | grid["rgb"] = rgb 44 | p = pv.Plotter(off_screen=off_screen) 45 | p.add_mesh(grid, scalars="rgb", rgb=True, lighting=False) 46 | p.add_axes(xlabel="Re", ylabel="Im", zlabel="abs+") 47 | 48 | return p 49 | -------------------------------------------------------------------------------- /experiments/create.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | 5 | def show_linear(vals) -> None: 6 | plt.imshow(np.multiply.outer(np.ones(60), vals.data.T)) 7 | plt.show() 8 | 9 | 10 | def show_circular(vals, rot=0.0): 11 | n = 256 12 | x, y = np.meshgrid(np.linspace(-n, +n), np.linspace(-n, +n)) 13 | 14 | alpha = np.mod(np.arctan2(y, x) - rot, 2 * np.pi) 15 | 16 | m = vals.data.shape[1] 17 | ls = np.linspace(0, 2 * np.pi, m, endpoint=False) 18 | r = np.interp(alpha.reshape(-1), ls, vals.data[0]).reshape(alpha.shape) 19 | g = np.interp(alpha.reshape(-1), ls, vals.data[1]).reshape(alpha.shape) 20 | b = np.interp(alpha.reshape(-1), ls, vals.data[2]).reshape(alpha.shape) 21 | out = np.array([r, g, b]) 22 | 23 | plt.imshow(out.T) 24 | plt.show() 25 | 26 | 27 | def find_max_srgb_radius(cs, L=50, tol=1.0e-6): 28 | from colorio.cs import ColorCoordinates, convert 29 | 30 | # In the given color space find the circle in the L=50-plane with the center (50, 0, 31 | # 0) such that it's as large as possible while still being in the SRGB gamut. 32 | n = 256 33 | alpha = np.linspace(0, 2 * np.pi, n, endpoint=False) 34 | 35 | # bisection 36 | r0 = 0.0 37 | r1 = 100.0 38 | while r1 - r0 > tol: 39 | r = 0.5 * (r1 + r0) 40 | 41 | coords = ColorCoordinates( 42 | [np.full(n, L), r * np.cos(alpha), r * np.sin(alpha)], cs 43 | ) 44 | vals = convert(coords, "srgb1", mode="ignore") 45 | 46 | if np.any(vals < 0) or np.any(vals > 1): 47 | r1 = r 48 | else: 49 | r0 = r 50 | return r0 51 | 52 | 53 | def create_colormap(L=50): 54 | import colorio 55 | from colorio.cs import SRGB1, ColorCoordinates, convert 56 | 57 | cs = colorio.cs.CAM16UCS(c=0.69, Y_b=20, L_A=15) 58 | # cs = colorio.cs.CAM02('UCS', 0.69, 20, 15) 59 | # cs = colorio.cs.CIELAB() 60 | 61 | r0 = find_max_srgb_radius(cs, L=L) 62 | 63 | n = 256 64 | alpha = np.linspace(0, 2 * np.pi, n, endpoint=False) 65 | 66 | coords = ColorCoordinates( 67 | [np.full(n, L), r0 * np.cos(alpha), r0 * np.sin(alpha)], cs 68 | ) 69 | return convert(coords, SRGB1("clip")) 70 | -------------------------------------------------------------------------------- /anim/create-taylor-anim.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Callable 4 | 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import sympy 8 | from rich.progress import track 9 | from sympy import diff, lambdify, simplify 10 | 11 | import cplot 12 | 13 | 14 | class Taylor: 15 | def __init__(self, f: Callable, z0: complex, Z: np.ndarray): 16 | self.z0 = z0 17 | self.var = sympy.Symbol("z") 18 | self.Zz0 = Z - self.z0 19 | self.val = None 20 | self.zk = np.ones_like(Z) 21 | self.k = 0 22 | self.df = f(self.var) 23 | 24 | def __next__(self) -> np.ndarray: 25 | if self.k == 0: 26 | self.val = lambdify(self.var, self.df)(self.z0).astype(complex) * self.zk 27 | self.k += 1 28 | return self.val 29 | 30 | self.zk *= self.Zz0 / self.k 31 | self.df = simplify(diff(self.df, self.var)) 32 | self.val += lambdify(self.var, self.df)(self.z0) * self.zk 33 | self.k += 1 34 | return self.val 35 | 36 | 37 | def create_taylor_anim(taylor: Taylor, p: cplot.Plotter, name: str, max_degree: int): 38 | p.plot(lambdify(taylor.var, taylor.df)(p.Z)) 39 | plt.savefig(f"{name}.svg", bbox_inches="tight") 40 | plt.close() 41 | 42 | idx = 0 43 | for k in track(range(max_degree + 1), description="Creating PNGs..."): 44 | val = next(taylor) 45 | p.plot(val) 46 | plt.suptitle(f"Taylor expansion of {name} around {taylor.z0}, degree {k}") 47 | plt.savefig(f"data/out{idx:04d}.png", bbox_inches="tight") 48 | plt.close() 49 | idx += 1 50 | 51 | 52 | # name = "exp" 53 | # p = cplot.Plotter((-7.0, 7.0, 400), (-7.0, 7.0, 400)) 54 | # taylor = Taylor(sympy.exp, 0, p.Z) 55 | # max_degree = 30 56 | 57 | # name = "sin" 58 | # p = cplot.Plotter((-10.0, 10.0, 640), (-6.0, 6.0, 400)) 59 | # taylor = Taylor(sympy.sin, 0, p.Z) 60 | # max_degree = 30 61 | 62 | # name = "log" 63 | # p = cplot.Plotter((-0.7, 2.7, 400), (-1.7, 1.7, 400)) 64 | # taylor = Taylor(sympy.log, 1, p.Z) 65 | # max_degree = 40 66 | 67 | name = "tan" 68 | p = cplot.Plotter((-2.2, 2.2, 400), (-2.2, 2.2, 400)) 69 | taylor = Taylor(sympy.tan, 0, p.Z) 70 | max_degree = 40 71 | 72 | 73 | create_taylor_anim(taylor, p, name, max_degree) 74 | -------------------------------------------------------------------------------- /src/cplot/_tri.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import warnings 4 | from typing import Callable 5 | 6 | import matplotlib as mpl 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | from numpy.typing import ArrayLike 10 | 11 | from ._colors import get_srgb1 12 | 13 | 14 | def tripcolor( 15 | triang, 16 | fz: ArrayLike, 17 | abs_scaling: Callable[[np.ndarray], np.ndarray] = lambda x: x / (x + 1), 18 | ): 19 | fz = np.asarray(fz) 20 | rgb = get_srgb1(fz, abs_scaling=abs_scaling) 21 | 22 | # https://github.com/matplotlib/matplotlib/issues/10265#issuecomment-358684592 23 | n = fz.shape[0] 24 | z2 = np.arange(n) 25 | cmap = mpl.colors.LinearSegmentedColormap.from_list("mymap", rgb, N=n) 26 | plt.tripcolor(triang, z2, shading="gouraud", cmap=cmap) 27 | return plt 28 | 29 | 30 | def tricontour_abs(triang, fz: ArrayLike, contours: ArrayLike | None = None): 31 | vals = np.abs(fz) 32 | 33 | def plot_contours(levels, colors, linestyles, alpha): 34 | with warnings.catch_warnings(): 35 | warnings.filterwarnings( 36 | "ignore", "No contour levels were found within the data range." 37 | ) 38 | plt.tricontour( 39 | triang, 40 | vals, 41 | levels=levels, 42 | colors=colors, 43 | linestyles=linestyles, 44 | alpha=alpha, 45 | ) 46 | 47 | if contours is None: 48 | base = 2.0 49 | min_exp = np.log(np.min(vals)) / np.log(base) 50 | min_exp = int(max(min_exp, -100)) 51 | max_exp = np.log(np.max(vals)) / np.log(base) 52 | max_exp = int(min(max_exp, 100)) 53 | contours_neg = [base**k for k in range(min_exp, 0)] 54 | contours_pos = [base**k for k in range(1, max_exp + 1)] 55 | 56 | plot_contours(levels=contours_neg, colors="0.8", linestyles="solid", alpha=0.2) 57 | plot_contours([1.0], colors="0.8", linestyles=[(5, (5, 5))], alpha=0.3) 58 | plot_contours([1.0], colors="0.3", linestyles=[(0, (5, 5))], alpha=0.3) 59 | plot_contours(levels=contours_pos, colors="0.3", linestyles="solid", alpha=0.2) 60 | else: 61 | plot_contours(levels=contours, colors="0.8", linestyles="solid", alpha=0.2) 62 | 63 | return plt 64 | 65 | 66 | # tricontour_arg is not useful or possible until 67 | # 68 | # 69 | # def tricontour_arg( 70 | # triang, 71 | # fz: ArrayLike, 72 | # # f: Callable[[np.ndarray], np.ndarray], 73 | # contours: ArrayLike = (-np.pi / 2, 0.0, np.pi / 2, np.pi), 74 | # ): 75 | -------------------------------------------------------------------------------- /tests/test_tripcolor.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.tri as tri 3 | import numpy as np 4 | 5 | import cplot 6 | 7 | 8 | def test_tripcolor(): 9 | # Adapted from 10 | # 11 | # First create the x and y coordinates of the points. 12 | n_angles = 36 13 | n_radii = 8 14 | min_radius = 0.25 15 | radii = np.linspace(min_radius, 0.95, n_radii) 16 | 17 | angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) 18 | angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) 19 | angles[:, 1::2] += np.pi / n_angles 20 | 21 | x = (radii * np.cos(angles)).flatten() 22 | y = (radii * np.sin(angles)).flatten() 23 | z = 2 * (x + 1j * y) 24 | 25 | # Create the Triangulation; no triangles so Delaunay triangulation created. 26 | triang = tri.Triangulation(x, y) 27 | 28 | # Mask off unwanted triangles. 29 | triang.set_mask( 30 | np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) 31 | < min_radius 32 | ) 33 | 34 | cplot.tripcolor(triang, z) 35 | plt.gca().set_aspect("equal", "datalim") 36 | plt.show() 37 | 38 | 39 | def test_tricontour(): 40 | # Adapted from 41 | # 42 | # First create the x and y coordinates of the points. 43 | n_angles = 288 44 | n_radii = 64 45 | min_radius = 0.25 46 | radii = np.linspace(min_radius, 0.95, n_radii) 47 | 48 | angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) 49 | angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) 50 | angles[:, 1::2] += np.pi / n_angles 51 | 52 | x = (radii * np.cos(angles)).flatten() 53 | y = (radii * np.sin(angles)).flatten() 54 | z = x + 1j * y 55 | 56 | # Create the Triangulation; no triangles so Delaunay triangulation created. 57 | triang = tri.Triangulation(x, y) 58 | 59 | # Mask off unwanted triangles. 60 | triang.set_mask( 61 | np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) 62 | < min_radius 63 | ) 64 | 65 | fz = np.sin(7 * z) / (7 * z) 66 | 67 | cplot.tripcolor(triang, fz) 68 | cplot.tricontour_abs(triang, fz) 69 | # cplot.tricontour_arg(triang, fz) 70 | 71 | plt.gca().set_aspect("equal", "datalim") 72 | plt.savefig("out.png", bbox_inches="tight") 73 | plt.show() 74 | 75 | 76 | if __name__ == "__main__": 77 | test_tricontour() 78 | -------------------------------------------------------------------------------- /src/cplot/benchmark.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | from ._main import plot 5 | 6 | 7 | def show_kovesi_test_image(cmap): 8 | """Visual color map test after Peter Kovesi .""" 9 | n = 300 10 | x = np.arange(n + 1) / n 11 | y = np.arange(n + 1) / n / 3 12 | X, Y = np.meshgrid(x, y) 13 | # From : 14 | # It consists of a sine wave superimposed on a ramp function, this provides a set of 15 | # constant magnitude features presented at different offsets. The spatial frequency 16 | # of the sine wave is chosen to lie in the range at which the human eye is most 17 | # sensitive, and its amplitude is set so that the range from peak to trough 18 | # represents a series of features that are 10% of the total data range. The 19 | # amplitude of the sine wave is modulated from its full value at the top of the 20 | # image to zero at the bottom. 21 | Z = X + (3 * Y) ** 2 * 0.05 * np.sin(100 * np.pi * X) 22 | # Z = X + 0.05 * np.sin(100*np.pi*X*Y) 23 | 24 | plt.imshow( 25 | Z, 26 | extent=(x.min(), x.max(), y.max(), y.min()), 27 | interpolation="nearest", 28 | cmap=cmap, 29 | origin="lower", 30 | aspect="equal", 31 | ) 32 | 33 | plt.xticks([]) 34 | plt.yticks([]) 35 | 36 | plt.show() 37 | 38 | 39 | def show_test_function(variant="a", res=201): 40 | """Visual color map test after Peter Kovesi , 41 | adapted for the complex color map. 42 | """ 43 | 44 | def fa(z): 45 | r = np.abs(z) 46 | alpha = np.angle(z) 47 | # for the radius function 48 | # 49 | # f(r) = r + w * sin(k * pi * r) 50 | # 51 | # to be >= 0 everwhere, the first minimum at 52 | # 53 | # r0 = arccos(-1 / (pi * k * w)) 54 | # r1 = 1 / (pi * k) (pi + (pi - y)) 55 | # = (2 pi - y) / (pi * k) 56 | # 57 | # has to be >= 0, i.e., 58 | # 59 | k = 2 60 | w = 0.7 61 | x0 = np.arccos(-1 / (np.pi * k * w)) 62 | x1 = 2 * np.pi - x0 63 | r1 = x1 / np.pi / k 64 | assert r1 + w * np.sin(k * np.pi * r1) >= 0 65 | return (r + w * np.sin(k * np.pi * r)) * np.exp(1j * alpha) 66 | 67 | def fb(z): 68 | r = np.abs(z) 69 | alpha = np.angle(z) 70 | return r * np.exp(1j * (alpha + 0.8 * np.cos(3 * np.pi * alpha))) 71 | 72 | def fc(z): 73 | return (z.real + 0.5 * np.sin(2 * np.pi * z.real)) + 1j * ( 74 | z.imag + 0.5 * np.sin(2 * np.pi * z.imag) 75 | ) 76 | 77 | f = {"a": fa, "b": fb, "c": fc}[variant] 78 | 79 | plot( 80 | f, 81 | (-5, +5, res), 82 | (-5, +5, res), 83 | contours_abs=None, 84 | contours_arg=None, 85 | ) 86 | plt.show() 87 | -------------------------------------------------------------------------------- /src/cplot/_colors.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Callable 4 | 5 | import npx 6 | import numpy as np 7 | from numpy.typing import ArrayLike 8 | 9 | 10 | # A number of scalings f that map the magnitude [0, infty] to [0, 1] are possible. One 11 | # desirable property is 12 | # 13 | # (1) f(1/r) = 1 - f(r). 14 | # 15 | # This makes sure that the representation of the inverse of a function is exactly as 16 | # light as the original function is dark. The function g_a(r) = 1 - a^r (with some 0 < a 17 | # < 1), as it is sometimes suggested (e.g., on Wikipedia 18 | # ) does _not_ fulfill (1). 19 | # 20 | # A common alternative is 21 | # 22 | # h(r) = r^a / (r^a + 1) 23 | # 24 | # with a configurable parameter a. 25 | # 26 | # * For a=1.21268891, this function is very close to the popular alternative 2/pi * 27 | # arctan(r) (which also fulfills the above property) 28 | # 29 | # * For a=1.21428616 is is close to g_{1/2} (between 0 and 1). 30 | # 31 | # * For a=1.49486991 it is close to x/2 (between 0 and 1). 32 | # 33 | # * For a=2 it is the stereographic projection onto the Riemann sphere. 34 | # For other a, it's the projection onto something else than a sphere. For a=1, for 35 | # example, the projection onto the line f(t) = t-1. 36 | # 37 | # Disadvantage of this choice: 38 | # 39 | # h'(r) = (a * r^{a-1} * (r^a + 1) - r^a * a * r^{a-1}) / (r^a + 1) ** 2 40 | # = a * r^{a-1} / (r^a + 1) ** 2 41 | # 42 | # so h'(r)=0 at r=0 for all a > 1. This means that h(r) has an inflection point in (0, 43 | # 1) for all a > 1. For 0 < alpha < 1, the derivative at 0 is infty. 44 | # 45 | # Only for a=1, the derivative is 1/2. For arctan, it's 1 / pi. 46 | # 47 | # There are other choices of the form f(x) = s(x) / (s(x) + 1). s has to 48 | # fulfill s(x)*s(1/x) = 1, see 49 | # for a characterization of such functions. This leads to the characterization 50 | # 51 | # f(x) = phi(x) / (phi(x) + phi(1/x)) 52 | # 53 | # for _any_ phi(x). For phi(x)=sqrt(x), one gets f(x)=x/(x+1). Ideas here are 54 | # phi = log1p or log1p(log1p) (and so forth). 55 | # 56 | # Another choice that fulfills (1) is 57 | # 58 | # / r / 2 for 0 <= x <= 1, 59 | # f(r) = | 60 | # \ 1 - 1 / (2r) for x > 1, 61 | # 62 | # but its second derivative is discontinuous at 1, and one does actually notice this 63 | # 64 | # / 1/2 for 0 <= x <= 1, 65 | # f'(r) = | 66 | # \ 1/2 / r^2 for x > 1, 67 | # 68 | # / 0 for 0 <= x <= 1, 69 | # f''(r) = | 70 | # \ -1 / r^3 for x > 1, 71 | # 72 | # TODO find parametrized function that is free of inflection points for the param=0 73 | # (or infty) is this last f(r). 74 | # 75 | def get_srgb1( 76 | z: ArrayLike, 77 | abs_scaling: Callable[[np.ndarray], np.ndarray] = lambda x: x / (x + 1), 78 | saturation_adjustment: float = 1.28, 79 | ) -> np.ndarray: 80 | z = np.asarray(z) 81 | 82 | angle = np.arctan2(z.imag, z.real) 83 | absval_scaled = abs_scaling(np.abs(z)) 84 | 85 | # We may have NaNs, so don't be too strict here. 86 | # assert np.all(absval_scaled >= 0) 87 | # assert np.all(absval_scaled <= 1) 88 | 89 | # from .create import find_max_srgb_radius 90 | # r0 = find_max_srgb_radius(oklab, L=0.5) 91 | r0 = 0.08499547839164734 92 | r0 *= saturation_adjustment 93 | 94 | # Rotate the angles such a "green" color represents positive real values. The 95 | # rotation is chosen such that the ratio g/(r+b) (in rgb) is the largest for the 96 | # point 1.0. 97 | offset = 0.8936868 * np.pi 98 | # Map (r, angle) to a point in the color space; bicone mapping similar to what 99 | # HSL looks like . 100 | rd = r0 - r0 * 2 * abs(absval_scaled - 0.5) 101 | ok_coords = np.array( 102 | [ 103 | absval_scaled, 104 | rd * np.cos(angle + offset), 105 | rd * np.sin(angle + offset), 106 | ] 107 | ) 108 | xyz100 = oklab_to_xyz100(ok_coords) 109 | srgb1 = xyz100_to_srgb1(xyz100) 110 | 111 | return np.moveaxis(srgb1, 0, -1) 112 | 113 | 114 | def oklab_to_xyz100(lab: np.ndarray) -> np.ndarray: 115 | M1 = np.array( 116 | [ 117 | [0.8189330101, 0.3618667424, -0.1288597137], 118 | [0.0329845436, 0.9293118715, 0.0361456387], 119 | [0.0482003018, 0.2643662691, 0.6338517070], 120 | ] 121 | ) 122 | M1inv = np.linalg.inv(M1) 123 | M2 = np.array( 124 | [ 125 | [0.2104542553, +0.7936177850, -0.0040720468], 126 | [+1.9779984951, -2.4285922050, +0.4505937099], 127 | [+0.0259040371, +0.7827717662, -0.8086757660], 128 | ] 129 | ) 130 | M2inv = np.linalg.inv(M2) 131 | return npx.dot(M1inv, npx.dot(M2inv, lab) ** 3) * 100 132 | 133 | 134 | def _xyy_to_xyz100(xyy: np.ndarray) -> np.ndarray: 135 | x, y, Y = xyy 136 | return np.array([Y / y * x, Y, Y / y * (1 - x - y)]) * 100 137 | 138 | 139 | def xyz100_to_srgb_linear(xyz: np.ndarray) -> np.ndarray: 140 | primaries_xyy = np.array( 141 | [ 142 | [0.64, 0.33, 0.2126], 143 | [0.30, 0.60, 0.7152], 144 | [0.15, 0.06, 0.0722], 145 | ] 146 | ) 147 | invM = _xyy_to_xyz100(primaries_xyy.T) 148 | whitepoint_correction = True 149 | if whitepoint_correction: 150 | # The above values are given only approximately, resulting in the fact that 151 | # SRGB(1.0, 1.0, 1.0) is only approximately mapped into the reference 152 | # whitepoint D65. Add a correction here. 153 | whitepoints_cie1931_d65 = np.array([95.047, 100, 108.883]) 154 | correction = whitepoints_cie1931_d65 / np.sum(invM, axis=1) 155 | invM = (invM.T * correction).T 156 | invM /= 100 157 | 158 | # https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB) 159 | # https://www.color.org/srgb.pdf 160 | out = npx.solve(invM, xyz) / 100 161 | out = out.clip(0.0, 1.0) 162 | return out 163 | 164 | 165 | def xyz100_to_srgb1(xyz: np.ndarray) -> np.ndarray: 166 | srgb = xyz100_to_srgb_linear(xyz) 167 | # gamma correction: 168 | a = 0.055 169 | is_smaller = srgb <= 0.0031308 170 | srgb[is_smaller] *= 12.92 171 | srgb[~is_smaller] = (1 + a) * srgb[~is_smaller] ** (1 / 2.4) - a 172 | return srgb 173 | -------------------------------------------------------------------------------- /tests/generate-readme-figures.py: -------------------------------------------------------------------------------- 1 | import math 2 | from pathlib import Path 3 | from typing import Callable 4 | 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import scipyx as spx 8 | from mpmath import fp 9 | from scipy.special import ( 10 | airy, 11 | airye, 12 | digamma, 13 | erf, 14 | exp1, 15 | expi, 16 | fresnel, 17 | gamma, 18 | hankel1, 19 | hankel2, 20 | jn, 21 | lambertw, 22 | loggamma, 23 | sici, 24 | wofz, 25 | yv, 26 | ) 27 | 28 | import cplot 29 | 30 | # gray to improve visibility on github's dark background 31 | _gray = "#969696" 32 | style = { 33 | "text.color": _gray, 34 | "axes.labelcolor": _gray, 35 | "axes.edgecolor": _gray, 36 | "xtick.color": _gray, 37 | "ytick.color": _gray, 38 | } 39 | plt.style.use(style) 40 | 41 | plot_dir = Path(__file__).resolve().parent / ".." / "plots" 42 | 43 | 44 | def _wrap(fun: Callable) -> Callable: 45 | def wrapped_fun(z): 46 | z = np.asarray(z) 47 | z_shape = z.shape 48 | out = np.array([fun(complex(val)) for val in z.flatten()]) 49 | return out.reshape(z_shape) 50 | 51 | return wrapped_fun 52 | 53 | 54 | def hurwitz_zeta(s, a): 55 | s = np.asarray(s) 56 | 57 | out = [] 58 | for val in s.flatten(): 59 | try: 60 | val = fp.zeta(complex(val), a) 61 | except Exception: 62 | val = np.nan 63 | out.append(val) 64 | 65 | return np.reshape(out, s.shape) 66 | 67 | 68 | def gudermannian(z): 69 | return 2 * np.arctan(np.tanh(0.5 * z)) 70 | 71 | 72 | def gudermannian_inv(z): 73 | return 2 * np.arctanh(np.tan(0.5 * z)) 74 | 75 | 76 | def hurwitz_zeta_a(s, a): 77 | """ 78 | Like hurwitz_zeta(), but with the vectorization in the second component. 79 | """ 80 | a = np.asarray(a) 81 | 82 | out = [] 83 | for val in a.flatten(): 84 | try: 85 | val = fp.zeta(s, complex(val)) 86 | except Exception: 87 | val = np.nan 88 | out.append(val) 89 | 90 | return np.reshape(out, a.shape) 91 | 92 | 93 | def zeta(z): 94 | return hurwitz_zeta(z, 1) 95 | 96 | 97 | def polygamma(z, n): 98 | """ 99 | Polygamma function for complex arguments 100 | """ 101 | return (-1) ** (n + 1) * math.factorial(n) * hurwitz_zeta_a(n + 1, z) 102 | 103 | 104 | def riemann_xi(z): 105 | # https://en.wikipedia.org/wiki/Riemann_Xi_function 106 | return 0.5 * z * (z - 1) * np.pi ** (-z / 2) * gamma(z / 2) * zeta(z) 107 | 108 | 109 | def dirichlet_eta(z): 110 | """ 111 | https://en.wikipedia.org/wiki/Dirichlet_eta_function 112 | 113 | Also called the _alternating zeta function_. 114 | """ 115 | return (1 - 2 ** (1 - z)) * zeta(z) 116 | 117 | 118 | def f(z): 119 | return (z**2 - 1) * (z - 2 - 1j) ** 2 / (z**2 + 2 + 2j) 120 | 121 | 122 | def lambert_1(z, n=100): 123 | zn = z.copy() 124 | s = np.zeros_like(z) 125 | for _ in range(n): 126 | s += zn / (1 - zn) 127 | zn *= z 128 | 129 | s[np.abs(z) > 1] = np.nan 130 | return s 131 | 132 | 133 | def lambert_phi(z): 134 | return z / (1 - z) ** 2 135 | 136 | 137 | def lambert_von_mangoldt(z, n=1000): 138 | zn = z.copy() 139 | s = np.zeros_like(z) 140 | for _ in range(n): 141 | s += np.log(n) * zn 142 | zn *= z 143 | 144 | s[np.abs(z) > 1] = np.nan 145 | return s 146 | 147 | 148 | def lambert_liouville(z, n=30): 149 | zk2 = z.copy() 150 | s = np.zeros_like(z) 151 | for k in range(n): 152 | s += zk2 153 | # zk2 = z ** (k ** 2) 154 | zk2 *= z ** (2 * k + 1) 155 | 156 | s[np.abs(z) > 1] = np.nan 157 | return s 158 | 159 | 160 | # https://en.wikipedia.org/wiki/Euler_function 161 | def euler_function(z, n=1000): 162 | out = np.ones_like(z) 163 | zk = z.copy() 164 | for _ in range(n): 165 | out *= 1 - zk 166 | zk *= z 167 | 168 | # Explicitly set some values to nan. This avoids contour artifacts near the 169 | # boundary. 170 | out[np.abs(zk) > 1] = np.nan 171 | return out 172 | 173 | 174 | def bernoulli(z): 175 | """ 176 | (11) in https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html 177 | """ 178 | return -z * zeta(1 - z) 179 | 180 | 181 | # First function from the SIAM-100-digit challenge 182 | # 183 | n = 401 184 | cplot.plot( 185 | lambda z: np.cos(np.log(z) / z) / z, (-1, 1, n), (-1, 1, n), abs_scaling=10.0 186 | ) 187 | plt.savefig(plot_dir / "siam.png", transparent=True, bbox_inches="tight") 188 | plt.clf() 189 | 190 | n = 400 191 | cplot.plot_abs(lambda z: np.sin(z**3) / z, (-2, 2, n), (-2, 2, n)) 192 | plt.savefig(plot_dir / "sinz3z-abs.png", bbox_inches="tight") 193 | plt.clf() 194 | 195 | cplot.plot_arg(lambda z: np.sin(z**3) / z, (-2, 2, n), (-2, 2, n)) 196 | plt.savefig(plot_dir / "sinz3z-arg.png", bbox_inches="tight") 197 | plt.clf() 198 | 199 | cplot.plot_contours(lambda z: np.sin(z**3) / z, (-2, 2, n), (-2, 2, n)) 200 | plt.savefig(plot_dir / "sinz3z-contours.png", bbox_inches="tight") 201 | plt.clf() 202 | 203 | cplot.plot(lambda z: np.sin(z**3) / z, (-2, 2, n), (-2, 2, n)) 204 | plt.savefig(plot_dir / "sinz3z.png", transparent=True, bbox_inches="tight") 205 | plt.clf() 206 | 207 | 208 | args = [ 209 | # 210 | ("z1.png", lambda z: z**1, (-2, +2), (-2, +2)), 211 | ("z2.png", lambda z: z**2, (-2, +2), (-2, +2)), 212 | ("z3.png", lambda z: z**3, (-2, +2), (-2, +2)), 213 | # 214 | ("1z.png", lambda z: 1 / z, (-2.0, +2.0), (-2.0, +2.0)), 215 | ("1z2.png", lambda z: 1 / z**2, (-2.0, +2.0), (-2.0, +2.0)), 216 | ("1z3.png", lambda z: 1 / z**3, (-2.0, +2.0), (-2.0, +2.0)), 217 | # möbius 218 | ("moebius1.png", lambda z: (z + 1) / (z - 1), (-5, +5), (-5, +5)), 219 | ( 220 | "moebius2.png", 221 | lambda z: (z + 1.5 - 0.5j) * (1.5 - 0.5j) / (z - 1.5 + 0.5j) * (-1.5 + 0.5j), 222 | (-5, +5), 223 | (-5, +5), 224 | ), 225 | ( 226 | "moebius3.png", 227 | lambda z: (-1.0j * z) / (1.0j * z + 1.5 - 0.5j), 228 | (-5, +5), 229 | (-5, +5), 230 | ), 231 | # 232 | # roots of unity 233 | ("z6+1.png", lambda z: z**6 + 1, (-1.5, 1.5), (-1.5, 1.5)), 234 | ("z6-1.png", lambda z: z**6 - 1, (-1.5, 1.5), (-1.5, 1.5)), 235 | ("z-6+1.png", lambda z: z ** (-6) + 1, (-1.5, 1.5), (-1.5, 1.5)), 236 | # 237 | ("zz.png", lambda z: z**z, (-3, +3), (-3, +3)), 238 | ("1zz.png", lambda z: (1 / z) ** z, (-3, +3), (-3, +3)), 239 | ("z1z.png", lambda z: z ** (1 / z), (-3, +3), (-3, +3)), 240 | # 241 | ("root2.png", np.sqrt, (-2, +2), (-2, +2)), 242 | ("root3.png", lambda x: x ** (1 / 3), (-2, +2), (-2, +2)), 243 | ("root4.png", lambda x: x**0.25, (-2, +2), (-2, +2)), 244 | # 245 | ("log.png", np.log, (-2, +2), (-2, +2)), 246 | ("exp.png", np.exp, (-3, +3), (-3, +3)), 247 | ("exp2.png", np.exp2, (-3, +3), (-3, +3)), 248 | # 249 | # non-analytic functions 250 | ("re.png", np.real, (-2, +2), (-2, +2)), 251 | # ("abs.png", np.abs, (-2, +2), (-2, +2)), 252 | ("z-absz.png", lambda z: z / np.abs(z), (-2, +2), (-2, +2)), 253 | ("conj.png", np.conj, (-2, +2), (-2, +2)), 254 | # 255 | # essential singularities 256 | ("exp1z.png", lambda z: np.exp(1 / z), (-1, +1), (-1, +1)), 257 | ("zsin1z.png", lambda z: z * np.sin(1 / z), (-0.6, +0.6), (-0.6, +0.6)), 258 | ("cos1z.png", lambda z: np.cos(1 / z), (-0.6, +0.6), (-0.6, +0.6)), 259 | # 260 | ("exp-z2.png", lambda z: np.exp(-(z**2)), (-3, +3), (-3, +3)), 261 | ("11z2.png", lambda z: 1 / (1 + z**2), (-3, +3), (-3, +3)), 262 | ("erf.png", erf, (-3, +3), (-3, +3)), 263 | # 264 | ("exp1z1.png", lambda z: np.exp(1 / z) / (1 + np.exp(1 / z)), (-1, 1), (-1, 1)), 265 | # 266 | # generating function of fibonacci sequence 267 | ("fibonacci.png", lambda z: 1 / (1 - z * (1 + z)), (-5.0, +5.0), (-5.0, +5.0)), 268 | # 269 | ("fresnel-s.png", lambda z: fresnel(z)[0], (-4, +4), (-4, +4)), 270 | ("fresnel-c.png", lambda z: fresnel(z)[1], (-4, +4), (-4, +4)), 271 | ("faddeeva.png", wofz, (-4, +4), (-4, +4)), 272 | # 273 | ("sin.png", np.sin, (-5, +5), (-5, +5)), 274 | ("cos.png", np.cos, (-5, +5), (-5, +5)), 275 | ("tan.png", np.tan, (-5, +5), (-5, +5)), 276 | # 277 | ("sec.png", lambda z: 1 / np.cos(z), (-5, +5), (-5, +5)), 278 | ("csc.png", lambda z: 1 / np.sin(z), (-5, +5), (-5, +5)), 279 | ("cot.png", lambda z: 1 / np.tan(z), (-5, +5), (-5, +5)), 280 | # 281 | ("sinh.png", np.sinh, (-5, +5), (-5, +5)), 282 | ("cosh.png", np.cosh, (-5, +5), (-5, +5)), 283 | ("tanh.png", np.tanh, (-5, +5), (-5, +5)), 284 | # 285 | ("sech.png", lambda z: 1 / np.cosh(z), (-5, +5), (-5, +5)), 286 | ("csch.png", lambda z: 1 / np.sinh(z), (-5, +5), (-5, +5)), 287 | ("coth.png", lambda z: 1 / np.tanh(z), (-5, +5), (-5, +5)), 288 | # 289 | ("arcsin.png", np.arcsin, (-2, +2), (-2, +2)), 290 | ("arccos.png", np.arccos, (-2, +2), (-2, +2)), 291 | ("arctan.png", np.arctan, (-2, +2), (-2, +2)), 292 | # 293 | ("arcsinh.png", np.arcsinh, (-2, +2), (-2, +2)), 294 | ("arccosh.png", np.arccosh, (-2, +2), (-2, +2)), 295 | ("arctanh.png", np.arctanh, (-2, +2), (-2, +2)), 296 | # 297 | ("sinz-z.png", lambda z: np.sin(z) / z, (-7, +7), (-7, +7)), 298 | ("cosz-z.png", lambda z: np.cos(z) / z, (-7, +7), (-7, +7)), 299 | ("tanz-z.png", lambda z: np.tan(z) / z, (-7, +7), (-7, +7)), 300 | # 301 | ("si.png", lambda z: sici(z)[0], (-15, +15), (-15, +15)), 302 | ("ci.png", lambda z: sici(z)[1], (-15, +15), (-15, +15)), 303 | ("lambertw.png", lambertw, (-5, +5), (-5, +5)), 304 | # 305 | # 306 | ("gudermannian.png", gudermannian, (-10, 10), (-10, 10)), 307 | # ("gudermannian_inv.png", gudermannian_inv, (-2, 2), (-2, 2)), 308 | ("exp1.png", exp1, (-5, +5), (-5, +5)), 309 | ("expi.png", expi, (-15, +15), (-15, +15)), 310 | # 311 | ("zeta.png", zeta, (-30, +30), (-30, +30)), 312 | ("bernoulli.png", bernoulli, (-30, +30), (-30, +30)), 313 | ("dirichlet-eta.png", dirichlet_eta, (-30, +30), (-30, +30)), 314 | # 315 | ("hurwitz-zeta-1-3.png", lambda z: hurwitz_zeta(z, 1 / 3), (-10, +10), (-10, +10)), 316 | ( 317 | "hurwitz-zeta-24-25.png", 318 | lambda z: hurwitz_zeta(z, 24 / 25), 319 | (-10, +10), 320 | (-10, +10), 321 | ), 322 | ( 323 | "hurwitz-zeta-a-3-4i.png", 324 | lambda z: hurwitz_zeta_a(3 + 4j, z), 325 | (-10, +10), 326 | (-10, +10), 327 | ), 328 | # 329 | ("gamma.png", gamma, (-5, +5), (-5, +5)), 330 | ("reciprocal-gamma.png", lambda z: 1 / gamma(z), (-5, +5), (-5, +5)), 331 | ("loggamma.png", loggamma, (-5, +5), (-5, +5)), 332 | # 333 | ("digamma.png", digamma, (-5, +5), (-5, +5)), 334 | ("polygamma1.png", lambda z: polygamma(z, 1), (-5, +5), (-5, +5)), 335 | ("polygamma2.png", lambda z: polygamma(z, 2), (-5, +5), (-5, +5)), 336 | # 337 | # 338 | ("riemann-xi.png", riemann_xi, (-20, +20), (-20, +20)), 339 | ("riemann-siegel-z.png", _wrap(fp.siegelz), (-20, +20), (-20, +20)), 340 | ("riemann-siegel-theta.png", _wrap(fp.siegeltheta), (-20, +20), (-20, +20)), 341 | # 342 | # jacobi elliptic functions 343 | ("ellipj-sn-06.png", lambda z: spx.ellipj(z, 0.6)[0], (-6, +6), (-6, +6)), 344 | ("ellipj-cn-06.png", lambda z: spx.ellipj(z, 0.6)[1], (-6, +6), (-6, +6)), 345 | ("ellipj-dn-06.png", lambda z: spx.ellipj(z, 0.6)[2], (-6, +6), (-6, +6)), 346 | # jacobi theta 347 | ( 348 | "jtheta1.png", 349 | _wrap(lambda z: fp.jtheta(1, z, complex(0.1 * np.exp(0.1j * np.pi)))), 350 | (-8, +8), 351 | (-8, +8), 352 | ), 353 | ( 354 | "jtheta2.png", 355 | _wrap(lambda z: fp.jtheta(2, z, complex(0.1 * np.exp(0.1j * np.pi)))), 356 | (-8, +8), 357 | (-8, +8), 358 | ), 359 | ( 360 | "jtheta3.png", 361 | _wrap(lambda z: fp.jtheta(3, z, complex(0.1 * np.exp(0.1j * np.pi)))), 362 | (-8, +8), 363 | (-8, +8), 364 | ), 365 | # 366 | # bessel, first kind 367 | ("bessel1-1.png", lambda z: jn(1, z), (-9, +9), (-9, +9)), 368 | ("bessel1-2.png", lambda z: jn(2, z), (-9, +9), (-9, +9)), 369 | ("bessel1-3.png", lambda z: jn(3, z), (-9, +9), (-9, +9)), 370 | # bessel, second kind 371 | ("bessel2-1.png", lambda z: yv(1, z), (-9, +9), (-9, +9)), 372 | ("bessel2-2.png", lambda z: yv(2, z), (-9, +9), (-9, +9)), 373 | ("bessel2-3.png", lambda z: yv(3, z), (-9, +9), (-9, +9)), 374 | # 375 | # airy functions 376 | ("airy-ai.png", lambda z: airy(z)[0], (-6, +6), (-6, +6)), 377 | ("airy-bi.png", lambda z: airy(z)[2], (-6, +6), (-6, +6)), 378 | ("airye-ai.png", lambda z: airye(z)[0], (-6, +6), (-6, +6)), 379 | # 380 | ( 381 | "tanh-sinh.png", 382 | lambda z: np.tanh(np.pi / 2 * np.sinh(z)), 383 | (-2.5, +2.5), 384 | (-2.5, +2.5), 385 | ), 386 | ( 387 | "sinh-sinh.png", 388 | lambda z: np.sinh(np.pi / 2 * np.sinh(z)), 389 | (-2.5, +2.5), 390 | (-2.5, +2.5), 391 | ), 392 | ( 393 | "exp-sinh.png", 394 | lambda z: np.exp(np.pi / 2 * np.sinh(z)), 395 | (-2.5, +2.5), 396 | (-2.5, +2.5), 397 | ), 398 | # 399 | # modular forms 400 | ("kleinj.png", _wrap(fp.kleinj), (-2.0, +2.0), (1.0e-5, +2.0)), 401 | ("dedekind-eta.png", _wrap(fp.eta), (-0.3, +0.3), (1.0e-5, +0.3)), 402 | # Dedekind eta = Ramanujan Delta ** 24; see 403 | # https://www.youtube.com/watch?v=s6sdEbGNdic 404 | # https://en.wikipedia.org/wiki/Ramanujan_tau_function 405 | # 406 | # TODO https://en.wikipedia.org/wiki/Euler_function 407 | # ("euler-function.png", _wrap(fp.eta), (-0.3, +0.3), (1.0e-5, +0.3)), 408 | # 409 | ("hankel1a.png", lambda z: hankel1(1.0, z), (-2, +2), (-2, +2)), 410 | ("hankel1b.png", lambda z: hankel1(3.1, z), (-3, +3), (-3, +3)), 411 | ("hankel2.png", lambda z: hankel2(1.0, z), (-2, +2), (-2, +2)), 412 | # lambert series 413 | ("lambert-1.png", lambert_1, (-1.1, 1.1), (-1.1, 1.1)), 414 | ("lambert-von-mangoldt.png", lambert_von_mangoldt, (-1.1, 1.1), (-1.1, 1.1)), 415 | ("lambert-liouville.png", lambert_liouville, (-1.1, 1.1), (-1.1, 1.1)), 416 | # 417 | # # https://www.dynamicmath.xyz 418 | # ( 419 | # "some-polynomial.png", 420 | # lambda z: 0.926 * (z + 7.3857e-2 * z ** 5 + 4.5458e-3 * z ** 9), 421 | # (-3, 3), 422 | # (-3, 3), 423 | # ), 424 | # # non-analytic 425 | # ( 426 | # "non-analytic.png", 427 | # lambda z: np.imag(np.exp(-1j * np.pi / 4) * z ** n) 428 | # + 1j * np.imag(np.exp(1j * np.pi / 4) * (z - 1) ** 4), 429 | # (-2.0, +3.0), 430 | # (-2.0, +3.0), 431 | # ), 432 | # logistic regression: 433 | ("sigmoid.png", lambda z: 1.0 / (1.0 + np.exp(-z)), (-10, +10), (-10, +10)), 434 | ("euler-function.png", euler_function, (-1.1, 1.1), (-1.1, 1.1)), 435 | ] 436 | 437 | for filename, fun, x, y in args: 438 | diag_length = np.sqrt((x[1] - x[0]) ** 2 + (y[1] - y[0]) ** 2) 439 | m = int(n * (y[1] - y[0]) / (x[1] - x[0])) 440 | cplot.plot( 441 | fun, 442 | (x[0], x[1], n), 443 | (y[0], y[1], m), 444 | add_colorbars=False, 445 | add_axes_labels=False, 446 | min_contour_length=1.0e-2 * diag_length, 447 | ) 448 | plt.savefig(plot_dir / filename, transparent=True, bbox_inches="tight") 449 | plt.clf() 450 | -------------------------------------------------------------------------------- /src/cplot/_main.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Callable 4 | 5 | import matplotlib.pyplot as plt 6 | import matplotx 7 | import numpy as np 8 | from matplotlib import cm, colors 9 | from mpl_toolkits.axes_grid1 import make_axes_locatable 10 | from numpy.typing import ArrayLike 11 | 12 | from ._colors import get_srgb1 13 | 14 | 15 | def _get_z_grid_for_image( 16 | xspec: tuple[float, float, int], yspec: tuple[float, float, int] 17 | ) -> np.ndarray: 18 | xmin, xmax, nx = xspec 19 | ymin, ymax, ny = yspec 20 | assert xmin < xmax 21 | assert ymin < ymax 22 | 23 | hx = (xmax - xmin) / nx 24 | x = np.linspace(xmin + hx / 2, xmax - hx / 2, nx) 25 | hy = (ymax - ymin) / ny 26 | y = np.linspace(ymin + hy / 2, ymax - hy / 2, ny) 27 | 28 | X = np.meshgrid(x, y) 29 | return X[0] + 1j * X[1] 30 | 31 | 32 | def _plot_colors( 33 | fz, 34 | extent, 35 | abs_scaling: Callable[[np.ndarray], np.ndarray] = lambda r: r / (r + 1), 36 | saturation_adjustment: float = 1.28, 37 | ): 38 | rgb_vals = get_srgb1( 39 | fz, 40 | abs_scaling=abs_scaling, 41 | saturation_adjustment=saturation_adjustment, 42 | ) 43 | 44 | # set nan values to white 45 | assert rgb_vals.shape[-1] == 3 46 | is_nan = np.any(np.isnan(rgb_vals), axis=-1) 47 | rgb_vals[is_nan] = [1.0, 1.0, 1.0] 48 | 49 | plt.imshow( 50 | rgb_vals, 51 | extent=extent, 52 | # Don't use "nearest" interpolation, it creates color blocking artifacts: 53 | # 54 | # interpolation="nearest", 55 | origin="lower", 56 | aspect="equal", 57 | ) 58 | 59 | 60 | def _add_colorbar_arg(cax, saturation_adjustment: float): 61 | # arg colorbar 62 | # create new colormap 63 | z = np.exp(1j * np.linspace(-np.pi, np.pi, 256)) 64 | rgb_vals = get_srgb1( 65 | z, 66 | abs_scaling=lambda z: np.full_like(z, 0.5), 67 | saturation_adjustment=saturation_adjustment, 68 | ) 69 | rgba_vals = np.pad(rgb_vals, ((0, 0), (0, 1)), constant_values=1.0) 70 | newcmp = colors.ListedColormap(rgba_vals) 71 | # 72 | norm = colors.Normalize(vmin=-np.pi, vmax=np.pi) 73 | 74 | cb1 = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=newcmp), cax=cax) 75 | 76 | cb1.set_label("arg", rotation=0, ha="center", va="top") 77 | cb1.ax.yaxis.set_label_coords(0.5, -0.03) 78 | cb1.set_ticks([-np.pi, -np.pi / 2, 0, +np.pi / 2, np.pi]) 79 | cb1.set_ticklabels( 80 | [r"$-\pi$", r"$-\dfrac{\pi}{2}$", "$0$", r"$\dfrac{\pi}{2}$", r"$\pi$"] 81 | ) 82 | 83 | 84 | def _add_colorbar_abs(cax, abs_scaling: Callable, abs_contours: float | list[float]): 85 | # abs colorbar 86 | norm = colors.Normalize(vmin=0, vmax=1) 87 | cb0 = plt.colorbar( 88 | cm.ScalarMappable(norm=norm, cmap=cm.gray), 89 | cax=cax, 90 | ) 91 | cb0.set_label("abs", rotation=0, ha="center", va="top") 92 | cb0.ax.yaxis.set_label_coords(0.5, -0.03) 93 | 94 | if isinstance(abs_contours, (int, float)): 95 | a = abs_contours 96 | scaled_vals = abs_scaling( 97 | np.array([1 / a**3, 1 / a**2, 1 / a, 1, a, a**2, a**3]) 98 | ) 99 | cb0.set_ticks([0.0, *scaled_vals, 1.0]) 100 | if isinstance(abs_contours, int) and abs_contours < 4: 101 | cb0.set_ticklabels( 102 | [ 103 | "0", 104 | f"$\\frac{{1}}{{{abs_contours ** 3}}}$", 105 | f"$\\frac{{1}}{{{abs_contours ** 2}}}$", 106 | f"$\\frac{{1}}{{{abs_contours ** 1}}}$", 107 | "$1$", 108 | f"{abs_contours ** 1}", 109 | f"{abs_contours ** 2}", 110 | f"{abs_contours ** 3}", 111 | "$\\infty$", 112 | ] 113 | ) 114 | else: 115 | cb0.set_ticklabels( 116 | [ 117 | "$0$", 118 | f"${a}^{{-3}}$", 119 | f"${a}^{{-2}}$", 120 | f"${a}^{{-1}}$", 121 | "$1$", 122 | f"${a}^1$", 123 | f"${a}^2$", 124 | f"${a}^3$", 125 | "$\\infty$", 126 | ] 127 | ) 128 | else: 129 | scaled_vals = abs_scaling(np.asarray(abs_contours)) 130 | cb0.set_ticks([0.0, *scaled_vals, 1.0]) 131 | cb0.set_ticklabels(["0", *[f"{val}" for val in scaled_vals], "∞"]) 132 | 133 | 134 | def _plot_contour_abs( 135 | Z, 136 | fz, 137 | contours: ArrayLike | float = 2.0, 138 | emphasize_contour_1: bool = True, 139 | alpha: float = 1.0, 140 | # in each direction, positive and negative: 141 | max_num_contours: int = 100, 142 | color: str | None = None, 143 | min_contour_length: float | None = None, 144 | linewidth: float | None = None, 145 | ): 146 | vals = np.abs(fz) 147 | 148 | def _plot_contour(levels, colors, linestyles, alpha): 149 | matplotx.contour( 150 | Z.real, 151 | Z.imag, 152 | vals, 153 | levels=levels, 154 | colors=colors, 155 | linestyles=linestyles, 156 | alpha=alpha, 157 | min_contour_length=min_contour_length, 158 | # choose a minjump above machine precision; avoids 159 | # speckles for functions like `z / abs(z)` 160 | min_jump=1.0e-15, 161 | linewidths=linewidth, 162 | ) 163 | 164 | if isinstance(contours, (float, int)): 165 | base = contours 166 | 167 | minval = np.nanmin(vals) 168 | min_exp = -np.inf if minval == 0.0 else np.log(minval) / np.log(base) 169 | 170 | mx = max(min_exp, -max_num_contours) 171 | min_exp = 0 if np.isnan(mx) else int(mx) 172 | 173 | maxval = np.nanmax(vals) 174 | max_exp = np.log(maxval) / np.log(base) 175 | mn = min(max_exp, max_num_contours) 176 | max_exp = 0 if np.isnan(mn) else int(mn) 177 | 178 | # exclude exponent 0, that's treated separately below 179 | contours_neg = [base**k for k in range(min_exp, 0)] 180 | contours_pos = [base**k for k in range(1, max_exp + 1)] 181 | 182 | _plot_contour(contours_neg, color if color else "0.8", "solid", alpha) 183 | 184 | if emphasize_contour_1: 185 | # subtle emphasize 186 | _plot_contour([1.0], "0.6", "solid", 0.7) 187 | # "dash": 188 | # _plot_contour([1.0], "0.8", [(0, (5, 5))], 0.2) 189 | # _plot_contour([1.0], "0.3", [(5, (5, 5))], 0.2) 190 | else: 191 | _plot_contour([1.0], color if color else "0.8", "solid", alpha) 192 | 193 | _plot_contour(contours_pos, color if color else "0.3", "solid", alpha) 194 | else: 195 | contours = np.asarray(contours) 196 | _plot_contour(contours, color if color else "0.8", "solid", alpha) 197 | 198 | 199 | def _plot_contour_arg( 200 | Z, 201 | fz, 202 | angles: ArrayLike = (-np.pi / 2, 0.0, np.pi / 2, np.pi), 203 | saturation_adjustment: float = 1.28, 204 | max_jump: float = 1.0, 205 | lightness_adjustment: float = 1.0, 206 | alpha: float = 1.0, 207 | min_contour_length: float | None = None, 208 | linewidth: float | None = None, 209 | ): 210 | angles = np.asarray(angles) 211 | 212 | # assert angles in [-pi, pi], like np.angle 213 | angles = np.mod(angles + np.pi, 2 * np.pi) - np.pi 214 | 215 | # Contour contours must be increasing 216 | angles = np.sort(angles) 217 | 218 | # mpl has problems with plotting the contour at +pi because that's where the 219 | # branch cut in np.angle happens. Separate out this case and move the branch cut 220 | # to 0/2*pi there. 221 | is_level1 = (angles > -np.pi + 0.1) & (angles < np.pi - 0.1) 222 | angles1 = angles[is_level1] 223 | angles2 = angles[~is_level1] 224 | angles2 = np.mod(angles2, 2 * np.pi) 225 | 226 | for angles, angle_fun in [ 227 | (angles1, np.angle), 228 | (angles2, lambda z: np.mod(np.angle(z), 2 * np.pi)), 229 | ]: 230 | angles = np.asarray(angles) 231 | 232 | if len(angles) == 0: 233 | continue 234 | 235 | linecolors = get_srgb1( 236 | lightness_adjustment * np.exp(angles * 1j), 237 | abs_scaling=lambda r: r / (r + 1), 238 | saturation_adjustment=saturation_adjustment, 239 | ) 240 | 241 | matplotx.contour( 242 | Z.real, 243 | Z.imag, 244 | angle_fun(fz), 245 | levels=list(angles), 246 | colors=list(linecolors), 247 | min_contour_length=min_contour_length, 248 | alpha=alpha, 249 | max_jump=max_jump, 250 | linewidths=linewidth, 251 | ) 252 | plt.gca().set_aspect("equal") 253 | 254 | 255 | class Plotter: 256 | def __init__( 257 | self, x_range: tuple[float, float, int], y_range: tuple[float, float, int] 258 | ): 259 | self.Z = _get_z_grid_for_image(x_range, y_range) 260 | self.extent = (x_range[0], x_range[1], y_range[0], y_range[1]) 261 | 262 | def plot(self, fz, *args, **kwargs): 263 | return _plot(self.Z, fz, self.extent, *args, **kwargs) 264 | 265 | 266 | def plot( 267 | f: Callable[[np.ndarray], np.ndarray], 268 | x_range: tuple[float, float, int], 269 | y_range: tuple[float, float, int], 270 | *args, 271 | **kwargs, 272 | ): 273 | extent = (x_range[0], x_range[1], y_range[0], y_range[1]) 274 | Z = _get_z_grid_for_image(x_range, y_range) 275 | 276 | # always reshape to vector, makes it easier for f() 277 | Z_shape = Z.shape 278 | fz = f(Z.flatten()).reshape(Z_shape) 279 | 280 | _plot(Z, fz, extent, *args, **kwargs) 281 | return plt 282 | 283 | 284 | def _abs_scaling_from_float(val: float) -> Callable: 285 | assert val > 1 286 | alpha = np.log(2) / np.log(val) 287 | 288 | def alpha_scaling(r): 289 | return r**alpha / (r**alpha + 1) 290 | 291 | return alpha_scaling 292 | 293 | 294 | def _plot( 295 | Z: np.ndarray, 296 | fz: np.ndarray, 297 | extent: tuple[float, float, float, float], 298 | # If you're changing contours_abs to x and want the abs_scaling to follow along, 299 | # you'll have to set it to the same value. 300 | abs_scaling: float | Callable[[np.ndarray], np.ndarray] = 2, 301 | # Literal["auto"] 302 | contours_abs: float | list[float] | None | str = "auto", 303 | contours_arg: ArrayLike | None = (-np.pi / 2, 0, np.pi / 2, np.pi), 304 | contour_arg_max_jump: float = 1.0, 305 | emphasize_abs_contour_1: bool = True, 306 | add_colorbars: bool | tuple[bool, bool] = True, 307 | colorbar_pad: tuple[float, float] = (0.2, 0.5), 308 | add_axes_labels: bool = True, 309 | saturation_adjustment: float = 1.28, 310 | min_contour_length: float | None = None, 311 | linewidth: float | None = None, 312 | ): 313 | assert Z.shape == fz.shape 314 | 315 | asc = abs_scaling if callable(abs_scaling) else _abs_scaling_from_float(abs_scaling) 316 | 317 | _plot_colors( 318 | fz, 319 | extent, 320 | asc, 321 | saturation_adjustment=saturation_adjustment, 322 | ) 323 | 324 | if contours_abs is None: 325 | contours_abs = 2 326 | 327 | elif contours_abs == "auto": 328 | assert isinstance( 329 | abs_scaling, (int, float) 330 | ), f'if contours_abs="auto", abs_scaling must be int or float, not {abs_scaling}' 331 | contours_abs = abs_scaling 332 | 333 | if contours_abs is not None: 334 | _plot_contour_abs( 335 | Z, 336 | fz, 337 | contours=contours_abs, 338 | emphasize_contour_1=emphasize_abs_contour_1, 339 | alpha=0.2, 340 | min_contour_length=min_contour_length, 341 | linewidth=linewidth, 342 | ) 343 | 344 | if contours_arg is not None: 345 | _plot_contour_arg( 346 | Z, 347 | fz, 348 | angles=contours_arg, 349 | saturation_adjustment=saturation_adjustment, 350 | max_jump=contour_arg_max_jump, 351 | alpha=0.4, 352 | # Draw the arg contour lines a little lighter. This way, arg contours which 353 | # dissolve into areas of nearly equal arg remain recognizable. (E.g., tan, 354 | # zeta, erf,...). 355 | lightness_adjustment=1.5, 356 | min_contour_length=min_contour_length, 357 | linewidth=linewidth, 358 | ) 359 | 360 | if add_axes_labels: 361 | plt.xlabel("Re(z)") 362 | # ylabel off-center, 363 | plt.ylabel( 364 | "Im(z)", 365 | rotation="horizontal", 366 | loc="center", 367 | verticalalignment="center", 368 | labelpad=10, 369 | ) 370 | 371 | # colorbars? 372 | if isinstance(add_colorbars, bool): 373 | add_colorbars = (add_colorbars, add_colorbars) 374 | 375 | ax = plt.gca() 376 | divider = make_axes_locatable(ax) 377 | 378 | if add_colorbars[0]: 379 | cax1 = divider.append_axes("right", size="5%", pad=colorbar_pad[0]) 380 | _add_colorbar_abs(cax1, asc, contours_abs) 381 | 382 | if add_colorbars[1]: 383 | cax2 = divider.append_axes("right", size="5%", pad=colorbar_pad[1]) 384 | _add_colorbar_arg(cax2, saturation_adjustment) 385 | return plt 386 | 387 | 388 | # only show the absolute value 389 | def plot_abs( 390 | *args, 391 | add_colorbars: bool = True, 392 | contours_abs: str | float | list[float] | None = None, 393 | **kwargs, 394 | ): 395 | return plot( 396 | *args, 397 | contours_abs=contours_abs, 398 | contours_arg=None, 399 | emphasize_abs_contour_1=False, 400 | add_colorbars=(add_colorbars, False), 401 | saturation_adjustment=0.0, 402 | **kwargs, 403 | ) 404 | 405 | 406 | # only show the phase, with some default value adjustments 407 | def plot_arg(*args, add_colorbars: bool = True, **kwargs): 408 | return plot( 409 | *args, 410 | abs_scaling=lambda r: np.full_like(r, 0.5), 411 | contours_abs=None, 412 | contours_arg=None, 413 | emphasize_abs_contour_1=False, 414 | add_colorbars=(False, add_colorbars), 415 | **kwargs, 416 | ) 417 | 418 | 419 | # "Phase plot" is a common name for this kind of plots 420 | plot_phase = plot_abs 421 | 422 | 423 | # only show the phase, with some default value adjustments 424 | def plot_contours( 425 | f: Callable[[np.ndarray], np.ndarray], 426 | x_range: tuple[float, float, int], 427 | y_range: tuple[float, float, int], 428 | contours_abs: float | ArrayLike | None = 2, 429 | contours_arg: ArrayLike | None = (-np.pi / 2, 0, np.pi / 2, np.pi), 430 | contour_arg_max_jump: float = 1.0, 431 | saturation_adjustment: float = 1.28, 432 | ): 433 | Z = _get_z_grid_for_image(x_range, y_range) 434 | 435 | # always reshape to vector, makes it easier for f() 436 | Z_shape = Z.shape 437 | fz = f(Z.flatten()).reshape(Z_shape) 438 | 439 | if contours_arg is not None: 440 | _plot_contour_arg( 441 | Z, 442 | fz, 443 | angles=contours_arg, 444 | saturation_adjustment=saturation_adjustment, 445 | max_jump=contour_arg_max_jump, 446 | alpha=1.0, 447 | lightness_adjustment=1.5, 448 | ) 449 | 450 | if contours_abs is not None: 451 | _plot_contour_abs( 452 | Z, 453 | fz, 454 | contours=contours_abs, 455 | alpha=0.8, 456 | color="0.7", 457 | emphasize_contour_1=False, 458 | ) 459 | 460 | plt.gca().set_aspect("equal") 461 | return plt 462 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | cplot 3 |

Plot complex-valued functions with style.

4 |

5 | 6 | [![PyPi Version](https://img.shields.io/pypi/v/cplot.svg?style=flat-square)](https://pypi.org/project/cplot) 7 | [![PyPI pyversions](https://img.shields.io/pypi/pyversions/cplot.svg?style=flat-square)](https://pypi.org/pypi/cplot/) 8 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5599493.svg?style=flat-square)](https://doi.org/10.5281/zenodo.5599493) 9 | [![GitHub stars](https://img.shields.io/github/stars/nschloe/cplot.svg?style=flat-square&logo=github&label=Stars&logoColor=white)](https://github.com/nschloe/cplot) 10 | [![Downloads](https://pepy.tech/badge/cplot/month)](https://pepy.tech/project/cplot) 11 | 12 | [![Discord](https://img.shields.io/static/v1?logo=discord&logoColor=white&label=chat&message=on%20discord&color=7289da&style=flat-square)](https://discord.gg/hnTJ5MRX2Y) 13 | 14 | [![gh-actions](https://img.shields.io/github/workflow/status/nschloe/cplot/ci?style=flat-square)](https://github.com/nschloe/cplot/actions?query=workflow%3Aci) 15 | [![codecov](https://img.shields.io/codecov/c/github/nschloe/cplot.svg?style=flat-square)](https://codecov.io/gh/nschloe/cplot) 16 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/psf/black) 17 | 18 | cplot helps plotting complex-valued functions in a visually appealing manner. 19 | 20 | Install with 21 | 22 | ``` 23 | pip install cplot 24 | ``` 25 | 26 | and use as 27 | 28 | ```python 29 | import numpy as np 30 | 31 | import cplot 32 | 33 | 34 | def f(z): 35 | return np.sin(z**3) / z 36 | 37 | 38 | plt = cplot.plot( 39 | f, 40 | (-2.0, +2.0, 400), 41 | (-2.0, +2.0, 400), 42 | # abs_scaling=lambda x: x / (x + 1), # how to scale the lightness in domain coloring 43 | # contours_abs=2.0, 44 | # contours_arg=(-np.pi / 2, 0, np.pi / 2, np.pi), 45 | # emphasize_abs_contour_1: bool = True, 46 | # add_colorbars: bool = True, 47 | # add_axes_labels: bool = True, 48 | # saturation_adjustment: float = 1.28, 49 | # min_contour_length = None, 50 | # linewidth = None, 51 | ) 52 | plt.show() 53 | ``` 54 | 55 | Historically, plotting of complex functions was in one of three ways 56 | 57 | | | | | 58 | | :--------------------------------------------------------------------: | :--------------------------------------------------------------------: | :-------------------------------------------------------------------------: | 59 | | Only show the absolute value; sometimes as a 3D plot | Only show the phase/the argument in a color wheel (phase portrait) | Show contour lines for both arg and abs | 60 | 61 | Combining all three of them gives you a _cplot_: 62 | 63 |

64 | 65 |

66 | 67 | See also [Wikipedia: Domain coloring](https://en.wikipedia.org/wiki/Domain_coloring). 68 | 69 | Features of this software: 70 | 71 | - cplot uses [OKLAB](https://bottosson.github.io/posts/oklab/), a perceptually 72 | uniform color space for the argument colors. 73 | This avoids streaks of colors occurring with other color spaces, e.g., HSL. 74 | - The contour `abs(z) == 1` is emphasized, other abs contours are at 2, 4, 8, etc. and 75 | 1/2, 1/4, 1/8, etc., respectively. This makes it easy to tell the absolte value 76 | precisely. 77 | - For `arg(z) == 0`, the color is green, for `arg(z) == pi/2` it's blue, for `arg(z) = -pi / 2` it's orange, and for `arg(z) = pi` it's pink. 78 | 79 | Other useful functions: 80 | 81 | 82 | 83 | ```python 84 | # There is a tripcolor function as well for triangulated 2D domains 85 | cplot.tripcolor(triang, z) 86 | 87 | # The function get_srgb1 returns the SRGB1 triple for every complex input value. 88 | # (Accepts arrays, too.) 89 | z = 2 + 5j 90 | val = cplot.get_srgb1(z) 91 | ``` 92 | 93 | #### Riemann sphere 94 | 95 |

96 | 97 |

98 | 99 | cplot can also plot functions on the [Riemann 100 | sphere](https://en.wikipedia.org/wiki/Riemann_sphere), a mapping of the complex 101 | plane to the unit ball. 102 | 103 | 104 | 105 | ```python 106 | import cplot 107 | import numpy as np 108 | 109 | cplot.riemann_sphere(np.log) 110 | ``` 111 | 112 | #### Gallery 113 | 114 | All plots are created with default settings. 115 | 116 | | | | | 117 | | :------------------------------------------------------------: | :------------------------------------------------------------: | :------------------------------------------------------------: | 118 | | `z ** 1` | `z ** 2` | `z ** 3` | 119 | 120 |
121 | Many more plots 122 | 123 | | | | | 124 | | :------------------------------------------------------------: | :-------------------------------------------------------------: | :-------------------------------------------------------------: | 125 | | `1 / z` | `1 / z ** 2` | `1 / z ** 3` | 126 | 127 | | | | | 128 | | :------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: | :------------------------------------------------------------------: | 129 | | `(z + 1) / (z - 1)` | Another [Möbius transformation](https://en.wikipedia.org/wiki/M%C3%B6bius_transformation) | A third Möbius transformation | 130 | 131 | | | | | 132 | | :------------------------------------------------------------: | :----------------------------------------------------------------: | :--------------------------------------------------------------: | 133 | | `np.real` | `z / abs(z)` | `np.conj` | 134 | 135 | | | | | 136 | | :--------------------------------------------------------------: | :--------------------------------------------------------------: | :---------------------------------------------------------------: | 137 | | `z ** 6 + 1` | [`z ** 6 - 1`](https://en.wikipedia.org/wiki/Root_of_unity) | `z ** (-6) + 1` | 138 | 139 | | | | | 140 | | :------------------------------------------------------------: | :-------------------------------------------------------------: | :-------------------------------------------------------------: | 141 | | `z ** z` | `(1/z) ** z` | `z ** (1/z)` | 142 | 143 | | | | | 144 | | :---------------------------------------------------------------: | :---------------------------------------------------------------: | :---------------------------------------------------------------: | 145 | | `np.sqrt` | `z**(1/3)` | `z**(1/4)` | 146 | 147 | | | | | 148 | | :-------------------------------------------------------------: | :-------------------------------------------------------------: | :--------------------------------------------------------------: | 149 | | [`np.log`](https://en.wikipedia.org/wiki/Logarithm) | `np.exp` | `np.exp2` | 150 | 151 | | | | | 152 | | :---------------------------------------------------------------: | :----------------------------------------------------------------: | :---------------------------------------------------------------: | 153 | | `np.exp(1 / z)` | `z * np.sin(1 / z)` | `np.cos(1 / z)` | 154 | 155 | | | | | 156 | | :----------------------------------------------------------------: | :----------------------------------------------------------------------: | :-------------------------------------------------------------: | 157 | | `exp(- z ** 2)` | [`1 / (1 + z ** 2)`](https://en.wikipedia.org/wiki/Runge%27s_phenomenon) | [Error function](https://en.wikipedia.org/wiki/Error_function) | 158 | 159 | | | | | 160 | | :-------------------------------------------------------------: | :-------------------------------------------------------------: | :-------------------------------------------------------------: | 161 | | `np.sin` | `np.cos` | `np.tan` | 162 | 163 | | | | | 164 | | :-------------------------------------------------------------: | :-------------------------------------------------------------: | :-------------------------------------------------------------: | 165 | | `sec` | `csc` | `cot` | 166 | 167 | | | | | 168 | | :--------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------: | 169 | | [`np.sinh`](https://en.wikipedia.org/wiki/Hyperbolic_functions) | `np.cosh` | `np.tanh` | 170 | 171 | | | | | 172 | | :--------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------: | 173 | | secans hyperbolicus | cosecans hyperbolicus | cotangent hyperbolicus | 174 | 175 | | | | | 176 | | :----------------------------------------------------------------: | :----------------------------------------------------------------: | :----------------------------------------------------------------: | 177 | | `np.arcsin` | `np.arccos` | `np.arctan` | 178 | 179 | | | | | 180 | | :-----------------------------------------------------------------: | :-----------------------------------------------------------------: | :-----------------------------------------------------------------: | 181 | | `np.arcsinh` | `np.arccosh` | `np.arctanh` | 182 | 183 | | | | | 184 | | :----------------------------------------------------------------: | :----------------------------------------------------------------: | :----------------------------------------------------------------: | 185 | | [Sinc, `sin(z) / z`](https://en.wikipedia.org/wiki/Sinc_function) | `cos(z) / z` | `tan(z) / z` | 186 | 187 | | | | | 188 | | :------------------------------------------------------------------------: | :------------------------------------------------------------: | :--------------------------------------------------------------------: | 189 | | [Integral sine _Si_](https://en.wikipedia.org/wiki/Trigonometric_integral) | Integral cosine _Ci_ | [Lambert W function](https://en.wikipedia.org/wiki/Lambert_W_function) | 190 | 191 | | | | | 192 | | :--------------------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------: | 193 | | [Gudermannian function](https://en.wikipedia.org/wiki/Gudermannian_function) | Exponential integral E1 | Exponential integral Ei | 194 | 195 | | | | | 196 | | :------------------------------------------------------------------: | :-------------------------------------------------------------------: | :----------------------------------------------------------------------------: | 197 | | [`mpmath.zeta`](https://en.wikipedia.org/wiki/Riemann_zeta_function) | Bernoulli function | [Dirichlet eta function](https://en.wikipedia.org/wiki/Dirichlet_eta_function) | 198 | 199 | | | | | 200 | | :-----------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: | 201 | | [Hurwitz zeta function](https://en.wikipedia.org/wiki/Hurwitz_zeta_function) with `a = 1/3` | Hurwitz zeta function with `a = 24/25` | Hurwitz zeta function with `s = 3 + 4i` | 202 | 203 | | | | | 204 | | :-------------------------------------------------------------------: | :--------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------: | 205 | | [`scipy.special.gamma`](https://en.wikipedia.org/wiki/Gamma_function) | [reciprocal Gamma](https://en.wikipedia.org/wiki/Reciprocal_gamma_function) | [`scipy.special.loggamma`](https://en.wikipedia.org/wiki/Gamma_function#The_log-gamma_function) | 206 | 207 | | | | | 208 | | :-----------------------------------------------------------------------: | :--------------------------------------------------------------------: | :--------------------------------------------------------------------: | 209 | | [`scipy.special.digamma`](https://en.wikipedia.org/wiki/Digamma_function) | [Polygamma 1](https://en.wikipedia.org/wiki/Polygamma_function) | [Polygamma 2](https://en.wikipedia.org/wiki/Polygamma_function) | 210 | 211 | | | | | 212 | | :--------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------: | :--------------------------------------------------------------------: | 213 | | [Riemann-Siegel theta function](https://en.wikipedia.org/wiki/Riemann%E2%80%93Siegel_theta_function) | [Z-function](https://en.wikipedia.org/wiki/Z_function) | [Riemann-Xi](https://en.wikipedia.org/wiki/Riemann_Xi_function) | 214 | 215 | | | | | 216 | | :-------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------: | :----------------------------------------------------------------------: | 217 | | [Jacobi elliptic function](https://en.wikipedia.org/wiki/Jacobi_elliptic_functions) `sn(0.6)` | `cn(0.6)` | `dn(0.6)` | 218 | 219 | | | | | 220 | | :----------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------: | :-----------------------------------------------------------------: | 221 | | [Jacobi theta](https://en.wikipedia.org/wiki/Theta_function) 1 with `q=0.1 * exp(0.1j * np.pi))` | Jacobi theta 2 with the same `q` | Jacobi theta 3 with the same `q` | 222 | 223 | | | | | 224 | | :-----------------------------------------------------------------------------------: | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | 225 | | [Bessel function](https://en.wikipedia.org/wiki/Bessel_function), first kind, order 1 | Bessel function, first kind, order 2 | Bessel function, first kind, order 3 | 226 | 227 | | | | | 228 | | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | 229 | | Bessel function, second kind, order 1 | Bessel function, second kind, order 2 | Bessel function, second kind, order 3 | 230 | 231 | | | | | 232 | | :------------------------------------------------------------------: | :------------------------------------------------------------------: | :-----------------------------------------------------------------: | 233 | | Hankel function of first kind (n=1.0) | Hankel function of first kind (n=3.1) | Hankel function of second kind (n=1.0) | 234 | 235 | | | | | 236 | | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | :------------------------------------------------------------------: | 237 | | [Fresnel S](https://en.wikipedia.org/wiki/Fresnel_integral) | [Fresnel C](https://en.wikipedia.org/wiki/Fresnel_integral) | [Faddeeva function](https://en.wikipedia.org/wiki/Faddeeva_function) | 238 | 239 | | | | | 240 | | :-----------------------------------------------------------------: | :-----------------------------------------------------------------: | :---------------------------------------------------------------------: | 241 | | [Airy function Ai](https://en.wikipedia.org/wiki/Airy_function) | [Bi](https://en.wikipedia.org/wiki/Airy_function) | [Exponentially scaled eAi](https://en.wikipedia.org/wiki/Airy_function) | 242 | 243 | | | | | 244 | | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | :------------------------------------------------------------------: | 245 | | `tanh(pi / 2 * sinh(z))` | `sinh(pi / 2 * sinh(z))` | `exp(pi / 2 * sinh(z))` | 246 | 247 | | | | 248 | | :----------------------------------------------------------------: | :--------------------------------------------------------------------------: | 249 | | [Klein's _j_-invariant](https://en.wikipedia.org/wiki/J-invariant) | [Dedekind eta function](https://en.wikipedia.org/wiki/Dedekind_eta_function) | 250 | 251 | | | | | 252 | | :--------------------------------------------------------------------: | :------------------------------------------------------------------------------: | :---------------------------------------------------------------------------: | 253 | | [Lambert series](https://en.wikipedia.org/wiki/Lambert_series) with 1s | Lambert series with von-Mangoldt-coefficients | Lambert series with Liouville-coefficients | 254 | 255 |
256 | 257 | ### Testing 258 | 259 | To run the cplot unit tests, check out this repository and run 260 | 261 | ``` 262 | tox 263 | ``` 264 | 265 | ### Similar projects and further reading 266 | 267 | - [Tristan Needham, _Visual Complex 268 | Analysis_, 1997](https://umv.science.upjs.sk/hutnik/NeedhamVCA.pdf) 269 | - [François Labelle, _A Gallery of Complex 270 | Functions_, 2002](http://wismuth.com/complex/gallery.html) 271 | - [Douglas Arnold and Jonathan Rogness, _Möbius transformations 272 | revealed_, 2008](https://youtu.be/0z1fIsUNhO4) 273 | - [Konstantin Poelke and Konrad Polthier, _Lifted Domain Coloring_, 274 | 2009](https://doi.org/10.1111/j.1467-8659.2009.01479.x) 275 | - [Elias Wegert and Gunter Semmler, _Phase Plots of Complex Functions: 276 | a Journey in Illustration_, 2011](https://www.ams.org/notices/201106/rtx110600768p.pdf) 277 | - [Elias Wegert, 278 | Calendars _Complex Beauties_, 2011-](https://tu-freiberg.de/en/fakult1/ana/institute/institute-of-applied-analysis/organisation/complex-beauties) 279 | - [Elias Wegert, _Visual Complex 280 | Functions_, 2012](https://www.springer.com/gp/book/9783034801799) 281 | - [empet, _Visualizing complex-valued functions with Matplotlib and Mayavi, Domain coloring method_, 2014](https://nbviewer.org/github/empet/Math/blob/master/DomainColoring.ipynb) 282 | - [John D. Cook, _Visualizing complex 283 | functions_, 2017](https://www.johndcook.com/blog/2017/11/09/visualizing-complex-functions/) 284 | - [endolith, _complex-colormap_, 2017](https://github.com/endolith/complex_colormap) 285 | - [Anthony Hernandez, _dcolor_, 2017](https://github.com/hernanat/dcolor) 286 | - [Juan Carlos Ponce Campuzano, _DC 287 | gallery_, 2018](https://www.dynamicmath.xyz/domain-coloring/dcgallery.html) 288 | - [3Blue1Brown, _Winding numbers and domain coloring_, 2018](https://youtu.be/b7FxPsqfkOY) 289 | - [Ricky Reusser, _Domain Coloring with Adaptive 290 | Contouring_, 2019](https://observablehq.com/@rreusser/adaptive-domain-coloring) 291 | - [Ricky Reusser, _Locally Scaled Domain Coloring, Part 1: Contour 292 | Plots_, 2020](https://observablehq.com/@rreusser/locally-scaled-domain-coloring-part-1-contour-plots) 293 | - [David Lowry-Duda, _Visualizing modular forms_, 2020](https://arxiv.org/abs/2002.05234) 294 | 295 | ### License 296 | 297 | This software is published under the [GPL-3.0 license](LICENSE). In cases where the 298 | constraints of the GPL prevent you from using this software, feel free contact the 299 | author. 300 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------