cmapkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,130 @@
1
+ """The colour maps shipped with hdrmaps, and images rendered through them.
2
+
3
+ Each map is stored as the points of an optimised curve in sRGB
4
+ (data/maps.json, made by tools/make_hdrmaps.py), with the measures of
5
+ cmapkit.hdrmaps.measure taken when it was made. The map itself is the
6
+ polyline through the points, sampled at equal steps of colour difference
7
+ in normal vision (paths.PathMap).
8
+ """
9
+
10
+ import copy
11
+ import json
12
+ from functools import lru_cache
13
+ from importlib.resources import files
14
+
15
+ import numpy as np
16
+
17
+ from .noise import blur_for_length, noise_sd, scale
18
+ from .paths import PathMap
19
+
20
+
21
+ @lru_cache(maxsize=1)
22
+ def _data():
23
+ return json.loads(files(__package__).joinpath("data/maps.json").read_text())
24
+
25
+
26
+ def names():
27
+ """Names of the shipped maps, shortest first."""
28
+ return list(_data()["maps"])
29
+
30
+
31
+ def info(name):
32
+ """What is recorded of a shipped map: its measures for each observer
33
+ (length, speed ratios and separation), its thickness and sharpest turn
34
+ in normal vision, the palette and observers it was made with, and the
35
+ settings of its construction."""
36
+ d = {k: v for k, v in _data()["maps"][name].items() if k != "points"}
37
+ return copy.deepcopy(d)
38
+
39
+
40
+ @lru_cache(maxsize=None)
41
+ def path_map(name):
42
+ """The shipped map `name` as a PathMap."""
43
+ return PathMap(np.asarray(_data()["maps"][name]["points"], float), "linear")
44
+
45
+
46
+ def colormap(name, n=1024):
47
+ """The shipped map `name` as a matplotlib colormap of n entries."""
48
+ from matplotlib.colors import ListedColormap
49
+ m = path_map(name)
50
+ return ListedColormap(m(np.linspace(0, 1, n)), name=f"cmapkit.hdrmaps.{name}")
51
+
52
+
53
+ def _lut(cmap):
54
+ """sRGB table (n, 3) of a shipped map name, a matplotlib colormap or its
55
+ name, or an array of sRGB values."""
56
+ if isinstance(cmap, str):
57
+ if cmap in _data()["maps"]:
58
+ return path_map(cmap).lut
59
+ import matplotlib
60
+ try:
61
+ cmap = matplotlib.colormaps[cmap]
62
+ except KeyError:
63
+ raise ValueError(f"{cmap!r} is neither a shipped map ({', '.join(names())}) "
64
+ "nor a matplotlib colormap") from None
65
+ if hasattr(cmap, "N") and callable(cmap):
66
+ return np.asarray(cmap(np.linspace(0, 1, max(cmap.N, 256))), float)[:, :3]
67
+ lut = np.asarray(cmap, float)
68
+ if lut.ndim != 2 or lut.shape[1] not in (3, 4) or len(lut) < 2:
69
+ raise ValueError(f"A colour table must be (n, 3) sRGB values; got shape {lut.shape}")
70
+ return lut[:, :3]
71
+
72
+
73
+ def render(image, cmap="path20", kind="sqrt", blur=0.0, threshold=3.0, low=0.1,
74
+ high=99.9):
75
+ """An image in colour, through a shipped map or a table of sRGB colours.
76
+
77
+ image: raw values (H, W). They are clipped at the percentiles low and
78
+ high and scaled to [0, 1] by `kind` (maps.scale); 'sqrt' makes shot
79
+ noise equal at every level, as the noise model assumes.
80
+ cmap: the name of a shipped map, a matplotlib colormap or its name, or
81
+ sRGB values (n, 3) in [0, 1] at equal steps of the data.
82
+ blur: the standard deviation of a Gaussian blur in pixels, 0 (the
83
+ default) for none, or 'matched' for the blur at which the map shows
84
+ the noise at `threshold` colour differences per noise standard
85
+ deviation in normal vision (noise.py, equation (2)). A blur changes
86
+ the image, and in a scientific image the change can be taken for
87
+ structure; without it the eye averages neighbouring pixels, and the
88
+ map still serves when single pixels are not resolved.
89
+
90
+ Returns (rgb, details): rgb is (H, W, 3) in [0, 1], and details gives
91
+ the noise sigma0 of the scaled image (nan if it cannot be estimated),
92
+ the blur applied, the map's length L in normal vision, and the colour
93
+ difference per noise standard deviation shown, in normal vision, after
94
+ the blur. Observers for whom the map is longer (path20 for tritan
95
+ vision) see the noise in proportion to their length."""
96
+ from scipy.ndimage import gaussian_filter
97
+ from .noise import kernel_gain, map_length
98
+
99
+ image = np.asarray(image, float)
100
+ if image.ndim != 2:
101
+ raise ValueError(f"render needs a grey image (H, W), not shape {image.shape}; "
102
+ "for an RGB file of a grey image, pass image[..., 0]")
103
+ if not np.isfinite(image).all():
104
+ raise ValueError("The image has values that are not finite; fill or crop them first")
105
+ if np.ptp(image) == 0:
106
+ raise ValueError("The image is constant")
107
+ if isinstance(cmap, str) and cmap in _data()["maps"]:
108
+ m = path_map(cmap)
109
+ lut, length = m.lut, m.length
110
+ else:
111
+ lut = _lut(cmap)
112
+ length = map_length(lut)[0]
113
+ t = scale(image, kind, low, high)
114
+ if isinstance(blur, str):
115
+ if blur != "matched":
116
+ raise ValueError(f"blur must be 'matched' or a number of pixels, not {blur!r}")
117
+ sigma0 = noise_sd(t)
118
+ s = blur_for_length(sigma0, length, threshold)
119
+ else:
120
+ s = float(blur)
121
+ try:
122
+ sigma0 = noise_sd(t)
123
+ except ValueError: # no noise to measure, and none is needed
124
+ sigma0 = float("nan")
125
+ if s > 0:
126
+ t = gaussian_filter(t, s)
127
+ idx = np.clip(np.round(t * (len(lut) - 1)), 0, len(lut) - 1).astype(int)
128
+ details = dict(sigma0=sigma0, blur=s, length=length,
129
+ noise_shown=length * sigma0 * kernel_gain(s))
130
+ return lut[idx], details
@@ -0,0 +1,62 @@
1
+ """Measures of a colour map for observers of normal and deficient colour vision.
2
+
3
+ A map is given as sRGB samples at equal steps of the data. For each
4
+ observer the samples are simulated (Machado et al. 2009, at full severity)
5
+ and placed in CAM16-UCS under PATH_VIEW, and the following are found.
6
+
7
+ - Length L, the sum of the colour differences between successive samples.
8
+ - Speed, the colour difference per unit of data, averaged over windows of
9
+ 1/64 of the range so that the quantisation of a table does not show as
10
+ speed. Its ratios max/min and p95/p5 (the 95th to the 5th percentile)
11
+ measure the uniformity of contrast; a perfectly uniform map has 1.
12
+ - Separation, the least colour difference between two parts of the map at
13
+ least 10 % of the data range apart. A map whose separation is near zero
14
+ shows two distinct data values in the same colour.
15
+ """
16
+
17
+ import numpy as np
18
+
19
+ from ..space import Observer, Space
20
+ from .paths import PATH_VIEW
21
+
22
+ OBSERVERS = {"normal": Observer(), "protan": Observer("protan"),
23
+ "deutan": Observer("deutan"), "tritan": Observer("tritan")}
24
+
25
+
26
+ def _resample(rgb, m):
27
+ rgb = np.asarray(rgb, float)
28
+ s = np.linspace(0, len(rgb) - 1, m)
29
+ return np.stack([np.interp(s, np.arange(len(rgb)), rgb[:, k]) for k in range(3)], -1)
30
+
31
+
32
+ def _separation(u, apart, chunk=500):
33
+ """Least distance between rows of u more than apart * len(u) apart."""
34
+ m = len(u)
35
+ best = np.inf
36
+ for a in range(0, m, chunk):
37
+ rows = np.arange(a, min(a + chunk, m))
38
+ d = np.linalg.norm(u[rows, None] - u[None], axis=-1)
39
+ far = np.abs(rows[:, None] - np.arange(m)[None]) > apart * m
40
+ if far.any():
41
+ best = min(best, float(d[far].min()))
42
+ return best
43
+
44
+
45
+ def assess(rgb, view=PATH_VIEW, samples=1024, window=1 / 64, apart=0.1, sep_samples=3000):
46
+ """Measures of the map rgb (n, 3) for each observer in OBSERVERS.
47
+
48
+ Returns a dict observer -> dict(length, speed_max_min, speed_p95_p5,
49
+ separation)."""
50
+ space = Space(view, tuple(OBSERVERS.values()))
51
+ u = space.coords(_resample(rgb, samples))
52
+ us = space.coords(_resample(rgb, sep_samples))
53
+ w = max(1, int(round(window * (samples - 1))))
54
+ out = {}
55
+ for k, name in enumerate(OBSERVERS):
56
+ d = np.linalg.norm(np.diff(u[k], axis=0), axis=1)
57
+ v = np.convolve(d, np.ones(w) / w, mode="valid") * len(d)
58
+ p5, p95 = np.percentile(v, [5, 95])
59
+ sep = _separation(us[k], apart)
60
+ out[name] = dict(length=float(d.sum()), speed_max_min=float(v.max() / v.min()),
61
+ speed_p95_p5=float(p95 / p5), separation=float(sep))
62
+ return out
@@ -0,0 +1,176 @@
1
+ """Noise of an image, and the length of colour map that it supports.
2
+
3
+ 1. Quantities. Let t in [0, 1] be the image after scaling (the square-root
4
+ scale makes shot noise equal at every level), and let sigma(s) be the
5
+ standard deviation of the noise in t after a Gaussian blur of s pixels. The
6
+ dynamic range in units of the noise is
7
+
8
+ D(s) = 1 / sigma(s), (1)
9
+
10
+ the number of noise standard deviations that fit across the range of the
11
+ data. A colour map of length L (colour difference in CAM16-UCS under the
12
+ map's viewing conditions) traversed at uniform speed shows a change dt in
13
+ the data as a colour difference L dt, and so shows the noise as a colour
14
+ fluctuation of standard deviation L sigma(s). We ask that this fluctuation
15
+ equal a threshold T (colour difference per noise standard deviation): below
16
+ it the map wastes some of the detail in the data, above it the noise grain
17
+ is plainly visible. The length the image supports is therefore
18
+
19
+ L = T D(s), (2)
20
+
21
+ and L / T is the number of noise steps the map shows across its range.
22
+ Equation (2) is read in either direction: for an image and a blur it gives
23
+ the length; for a map of given length it gives the blur.
24
+
25
+ 2. Estimate of the noise. sigma(0) is found from the image by the method of
26
+ Immerkaer (1996): the image is filtered with the 3 x 3 mask that is the outer
27
+ product of (1, -2, 1) with itself, which removes planes and nearly removes
28
+ smooth signal, and the median absolute response gives the noise robustly
29
+ against edges. Regions without noise would pull the median to zero, so
30
+ pixels whose 3 x 3 neighbourhood is constant, or touches the least or
31
+ greatest value of the image (as clipped regions do after scaling), are left
32
+ out. For white noise, sigma(s) = sigma(0) |k_s|, where |k_s| is the
33
+ root sum of squares of the blur kernel. The noise of the test images is close
34
+ to white; it is slightly correlated along the scan line, which this
35
+ estimate does not account for.
36
+
37
+ 3. Length available. A curve that keeps a distance rho between its distant
38
+ parts (curve.thickness) is a tube of diameter rho. In a volume V large in
39
+ every direction compared with rho, the length of such a tube is about
40
+ c V / rho^2. Within the lightness limits of an image the volume is a shell
41
+ whose thickness h in lightness is comparable with the rho of interest, and
42
+ the tube then lies in it as a curve in a surface, so that
43
+
44
+ L rho = K, (3)
45
+
46
+ with K about V / h. For the limits of bounds.image_bounds and curves optimised for
47
+ normal vision only, K is about 13 600 for rho from 7 to 27 (N from 20 to
48
+ 200). Curves that must also be uniform and thick for colour-deficient
49
+ observers lie in a smaller effective space: the shipped maps have L rho
50
+ near 5 000.
51
+ Equations (2) and (3) together give the thickness that a map of the
52
+ required length can have, rho = K / (T D), and the largest D for which a
53
+ chosen least thickness can be kept.
54
+
55
+ Reference: J. Immerkaer, Fast noise variance estimation, Computer Vision and
56
+ Image Understanding 64 (1996) 300-302.
57
+ """
58
+
59
+ import numpy as np
60
+
61
+
62
+ def scale(image, kind="log", low=0.1, high=99.9):
63
+ """Values in [0, 1] from a raw image: clipped at the given percentiles,
64
+ then scaled linearly, by square root, or logarithmically. The square root
65
+ makes shot noise (variance proportional to the signal) equal at every
66
+ level."""
67
+ v = np.asarray(image, float)
68
+ lo, hi = np.percentile(v, [low, high])
69
+ v = np.clip(v, lo, hi)
70
+ if kind == "sqrt":
71
+ lo, v, hi = (np.sqrt(np.maximum(x, 0)) for x in (lo, v, hi))
72
+ return (v - lo) / (hi - lo)
73
+ if kind == "log":
74
+ off = 1.0 - min(lo, 0.0)
75
+ return (np.log(v + off) - np.log(lo + off)) / (np.log(hi + off) - np.log(lo + off))
76
+ if kind == "linear":
77
+ return (v - lo) / (hi - lo)
78
+ raise ValueError(f"Unknown scale {kind!r}")
79
+
80
+ from .paths import PATH_VIEW
81
+
82
+
83
+ def noise_sd(t, min_pixels=100):
84
+ """Standard deviation of white noise in an image t, by the method of
85
+ Immerkaer (1996) with a median in place of the mean, over the pixels
86
+ whose 3 x 3 neighbourhood is neither constant nor touches the least or
87
+ greatest value of t. Raises ValueError if fewer than min_pixels remain."""
88
+ from scipy.ndimage import convolve, maximum_filter, minimum_filter
89
+ t = np.asarray(t, float)
90
+ if t.ndim != 2:
91
+ raise ValueError(f"noise_sd needs a grey image (H, W), not shape {t.shape}")
92
+ l = np.array([1.0, -2.0, 1.0])
93
+ r = convolve(t, np.outer(l, l))[2:-2, 2:-2]
94
+ hi, lo = maximum_filter(t, 3)[2:-2, 2:-2], minimum_filter(t, 3)[2:-2, 2:-2]
95
+ keep = (hi > lo) & (hi < t.max()) & (lo > t.min())
96
+ if keep.sum() < min_pixels:
97
+ raise ValueError("Too few pixels with noise to estimate it (the image is flat or "
98
+ "clipped nearly everywhere); give the blur explicitly.")
99
+ # The mask's root sum of squares is 6; median |x| = 0.6745 sd for a normal.
100
+ return float(np.median(np.abs(r[keep])) / (0.6745 * 6.0))
101
+
102
+
103
+ def kernel_gain(s):
104
+ """|k_s|: factor by which a Gaussian blur of s pixels (scipy's
105
+ gaussian_filter) reduces the standard deviation of white noise."""
106
+ if s <= 0:
107
+ return 1.0
108
+ from scipy.ndimage import gaussian_filter
109
+ n = 2 * int(np.ceil(4 * s)) + 1
110
+ d = np.zeros((n, n))
111
+ d[n // 2, n // 2] = 1.0
112
+ return float(np.sqrt((gaussian_filter(d, s) ** 2).sum()))
113
+
114
+
115
+ def noise_range(t, blur=0.0, sigma0=None):
116
+ """D(s), equation (1): the range of t in units of its noise after a blur
117
+ of `blur` pixels."""
118
+ sigma0 = noise_sd(t) if sigma0 is None else sigma0
119
+ return 1.0 / (sigma0 * kernel_gain(blur))
120
+
121
+
122
+ def required_length(D, threshold=3.0):
123
+ """L = T D, equation (2)."""
124
+ return threshold * D
125
+
126
+
127
+ def blur_for_length(sigma0, length, threshold=3.0, top=20.0):
128
+ """Blur s (pixels) at which a map of the given length shows the noise at
129
+ the threshold. Zero if the map is short enough without blur; `top`, with
130
+ a warning, if even that blur is not enough."""
131
+ if length * sigma0 <= threshold:
132
+ return 0.0
133
+ if length * sigma0 * kernel_gain(top) > threshold:
134
+ import warnings
135
+ warnings.warn(f"A blur of {top:g} pixels is not enough for a map of length "
136
+ f"{length:.0f} to show this noise at {threshold:g}; using {top:g}.",
137
+ stacklevel=2)
138
+ return float(top)
139
+ lo, hi = 0.0, top
140
+ for _ in range(40):
141
+ mid = 0.5 * (lo + hi)
142
+ if length * sigma0 * kernel_gain(mid) > threshold:
143
+ lo = mid
144
+ else:
145
+ hi = mid
146
+ return hi
147
+
148
+
149
+ def map_length(rgb, view=PATH_VIEW, smooth=1 / 64):
150
+ """Length and speed of a colour map given as sRGB samples (n, 3) at equal
151
+ steps of the data. Returns (L, v): L the total length, v the speed (colour
152
+ difference per unit of data) averaged over windows of `smooth` of the
153
+ range, so that the quantisation of a table does not show as speed."""
154
+ from ..space import CAM16UCS
155
+ u = CAM16UCS(view)(np.asarray(rgb, float))
156
+ d = np.linalg.norm(np.diff(u, axis=0), axis=1)
157
+ L = float(d.sum())
158
+ w = max(1, int(round(smooth * len(d))))
159
+ v = np.convolve(d, np.ones(w) / w, mode="valid") * len(d)
160
+ return L, v
161
+
162
+
163
+ def volume(bounds=None, view=PATH_VIEW, n=200_000, seed=0):
164
+ """Volume of the sRGB gamut in CAM16-UCS under `view`, within `bounds`
165
+ (a BandBounds, as from bounds.image_bounds) if given; by Monte Carlo
166
+ over the cube, weighting each sample by the Jacobian determinant."""
167
+ from ..space import Observer, Space
168
+ rng = np.random.default_rng(seed)
169
+ x = rng.random((n, 3))
170
+ space = Space(view, (Observer(),))
171
+ u, jac = space.jacobian(x)
172
+ det = np.abs(np.linalg.det(jac[0]))
173
+ keep = np.ones(n, bool)
174
+ if bounds is not None:
175
+ keep = (bounds.slack(u[0], space.ucs.K_L, np.ones(n)) >= 0).all(0)
176
+ return float((det * keep).mean())
@@ -0,0 +1,143 @@
1
+ """Colour maps along a path through a set of colours.
2
+
3
+ The colours (for example a large MCCP palette) are put in the order of a
4
+ short open path, joined by a curve in CAM16-UCS, and the curve is sampled at
5
+ equal arc length, so that equal steps in the data give equal colour
6
+ differences. Three joins are offered:
7
+
8
+ - 'linear': straight segments, with a corner at every colour;
9
+ - 'spline': the natural cubic spline through the colours, the interpolating
10
+ curve of least bending energy (the integral of the squared second
11
+ derivative);
12
+ - 'catmull-rom': the centripetal Catmull-Rom spline, which bends less
13
+ sharply than straight segments but, unlike the natural spline, cannot
14
+ overshoot into loops or cusps.
15
+
16
+ Samples that fall outside the sRGB gamut are clipped, and reported.
17
+ """
18
+
19
+ import numpy as np
20
+
21
+ from dataclasses import replace
22
+
23
+ from ..space import PRESETS, CAM16UCS, Viewing, linear_to_srgb
24
+
25
+ # An image fills most of the screen, so the adapting field is taken as a
26
+ # mid grey (Y_b = 20) rather than a plot background.
27
+ IMAGE_VIEW = Viewing(background_y=20.0, **PRESETS["screen"])
28
+
29
+ # Steps are measured with the lightness weight of MCCP's calibrated modes, so
30
+ # that the path is uniform in the measure its colours were spaced in.
31
+ PATH_VIEW = replace(IMAGE_VIEW, lightness_weight=0.77)
32
+
33
+
34
+ def short_path(d, starts=12):
35
+ """Order of a short open path through points with distance matrix d:
36
+ nearest-neighbour construction from several starts, then 2-opt."""
37
+ from ..mccp.order import _path_length, _two_opt
38
+ n = len(d)
39
+ if n < 3:
40
+ return list(range(n))
41
+ best, best_len = None, np.inf
42
+ for s in np.unique(np.linspace(0, n - 1, min(starts, n)).astype(int)):
43
+ order, left = [int(s)], set(range(n)) - {int(s)}
44
+ while left:
45
+ nxt = min(left, key=lambda k: d[order[-1], k])
46
+ order.append(nxt)
47
+ left.remove(nxt)
48
+ order = _two_opt(d, order, 1.0)
49
+ length = _path_length(d, order)
50
+ if length < best_len:
51
+ best, best_len = order, length
52
+ return best
53
+
54
+
55
+ def _catmull_rom(u, per=32, alpha=0.5):
56
+ """Centripetal Catmull-Rom through the rows of u, `per` samples per span."""
57
+ p = np.vstack([2 * u[0] - u[1], u, 2 * u[-1] - u[-2]])
58
+ out = []
59
+ for i in range(1, len(p) - 2):
60
+ p0, p1, p2, p3 = p[i - 1], p[i], p[i + 1], p[i + 2]
61
+ t0 = 0.0
62
+ t1 = t0 + np.linalg.norm(p1 - p0) ** alpha
63
+ t2 = t1 + np.linalg.norm(p2 - p1) ** alpha
64
+ t3 = t2 + np.linalg.norm(p3 - p2) ** alpha
65
+ t = np.linspace(t1, t2, per, endpoint=False)[:, None]
66
+ a1 = (t1 - t) / (t1 - t0) * p0 + (t - t0) / (t1 - t0) * p1
67
+ a2 = (t2 - t) / (t2 - t1) * p1 + (t - t1) / (t2 - t1) * p2
68
+ a3 = (t3 - t) / (t3 - t2) * p2 + (t - t2) / (t3 - t2) * p3
69
+ b1 = (t2 - t) / (t2 - t0) * a1 + (t - t0) / (t2 - t0) * a2
70
+ b2 = (t3 - t) / (t3 - t1) * a2 + (t - t1) / (t3 - t1) * a3
71
+ out.append((t2 - t) / (t2 - t1) * b1 + (t - t1) / (t2 - t1) * b2)
72
+ out.append(u[-1:])
73
+ return np.vstack(out)
74
+
75
+
76
+ def _dense_curve(u, join, per=32):
77
+ if join == "linear":
78
+ s = np.linspace(0, len(u) - 1, (len(u) - 1) * per + 1)
79
+ return np.stack([np.interp(s, np.arange(len(u)), u[:, k]) for k in range(3)], -1)
80
+ if join == "spline":
81
+ from scipy.interpolate import CubicSpline
82
+ chord = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(u, axis=0), axis=1))])
83
+ cs = CubicSpline(chord, u, bc_type="natural")
84
+ return cs(np.linspace(0, chord[-1], (len(u) - 1) * per + 1))
85
+ if join == "catmull-rom":
86
+ return _catmull_rom(u, per)
87
+ raise ValueError(f"Unknown join {join!r}")
88
+
89
+
90
+ class PathMap:
91
+ """A colour map along a path through `rgb` (n, 3), in the order given.
92
+
93
+ join: 'linear', 'spline' or 'catmull-rom'. The map has n_lut entries at
94
+ equal arc length in CAM16-UCS under `view`."""
95
+
96
+ def __init__(self, rgb, join="linear", view=PATH_VIEW, n_lut=4096):
97
+ self.ucs = CAM16UCS(view)
98
+ dense = _dense_curve(self.ucs(np.asarray(rgb, float)), join)
99
+ arc = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(dense, axis=0), axis=1))])
100
+ t = np.linspace(0, arc[-1], n_lut)
101
+ self.u = np.stack([np.interp(t, arc, dense[:, k]) for k in range(3)], -1)
102
+ lin = self.ucs.to_linear(self.u)
103
+ self.out_of_gamut = float(np.mean(np.any((lin < -1e-6) | (lin > 1 + 1e-6), axis=1)))
104
+ self.lut = linear_to_srgb(lin)
105
+ # Length of the colours actually shown, after clipping.
106
+ shown = self.ucs(self.lut)
107
+ self.length = float(np.linalg.norm(np.diff(shown, axis=0), axis=1).sum())
108
+ self.join = join
109
+
110
+ def __call__(self, t):
111
+ idx = np.clip(np.round(np.asarray(t, float) * (len(self.lut) - 1)), 0,
112
+ len(self.lut) - 1).astype(int)
113
+ return self.lut[idx]
114
+
115
+
116
+ def from_palette(rgb, join="linear", view=PATH_VIEW, dark_first=True):
117
+ """PathMap through the colours of a palette, put in the order of a short
118
+ path, starting from the darker end."""
119
+ ucs = CAM16UCS(view)
120
+ u = ucs(np.asarray(rgb, float))
121
+ order = short_path(np.linalg.norm(u[:, None] - u[None], axis=-1))
122
+ if dark_first and u[order[0], 0] > u[order[-1], 0]:
123
+ order = order[::-1]
124
+ return PathMap(np.asarray(rgb, float)[order], join, view)
125
+
126
+
127
+ def turning(u):
128
+ """Angle in degrees between successive steps of a sampled curve u (n, 3):
129
+ large values are corners."""
130
+ d = np.diff(u, axis=0)
131
+ d /= np.linalg.norm(d, axis=1, keepdims=True)
132
+ return np.degrees(np.arccos(np.clip((d[:-1] * d[1:]).sum(1), -1, 1)))
133
+
134
+
135
+ def self_approach(u, window=0.05, stride=8):
136
+ """For each sample of a curve u (n, 3), the least distance to any part of
137
+ the curve more than `window` (a fraction of the data range) away."""
138
+ sub = u[::stride]
139
+ m = len(sub)
140
+ d = np.linalg.norm(sub[:, None] - sub[None], axis=-1)
141
+ idx = np.arange(m)
142
+ far = np.abs(idx[:, None] - idx[None]) > window * m
143
+ return np.where(far, d, np.inf).min(1)
@@ -0,0 +1,6 @@
1
+ """MCCP: maximum contrast colour picking, for categorical palettes."""
2
+
3
+ from . import optimise
4
+ from .optimise import Anchor, Palette, default_anchors, palette
5
+
6
+ __all__ = ["Anchor", "Palette", "default_anchors", "optimise", "palette"]