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,313 @@
1
+ """Optimisation of a colour-map curve: a long path that does not come near
2
+ itself.
3
+
4
+ The curve is represented by M points x_1 ... x_M in sRGB, with CAM16-UCS
5
+ coordinates u_i under the path's viewing conditions, and a_ij denotes the
6
+ length of the polyline between points i and j. Its conditions are
7
+
8
+ |u_{i+1} - u_i| = l equal steps (uniform contrast),
9
+ (1 - b) l_o <= |u_{i+1} - u_i|_o <= (1 + b) l_o, l_o >= q_o l
10
+ steps for the other
11
+ observers, (2)
12
+ |u_i - u_j|_o >= p_o rho s(a_ij / rho) for |i - j| >= 2 and every
13
+ observer o (thickness), (1)
14
+
15
+ with s(x) = sin(min(x, pi / 2)), together with the lightness floor and
16
+ ceiling of an image and the sRGB cube. The right side of (1) is the chord
17
+ of a circle of diameter rho spanning the arc a_ij, up to a quarter turn,
18
+ and rho beyond. Parts of the curve far apart along it must therefore stay
19
+ rho apart, and nearby parts may approach no closer than they would on that
20
+ circle, so that the curve cannot turn more sharply than the circle. This is
21
+ a discrete form of the thickness of a curve (Gonzalez and Maddocks 1999).
22
+ Without the second part the curve folds back on itself between samples,
23
+ and the map then reverses over a step or two, as an oscillating map does at
24
+ its peaks.
25
+
26
+ The steps are equal in normal vision only. An observer with a colour vision
27
+ deficiency sees the same curve projected, and steps along a direction that
28
+ the deficiency removes are short for that observer, so that the map is slow
29
+ there. Condition (2) limits this. Each other observer o has a step l_o of
30
+ its own, a free variable, and its steps must lie within the fraction b of
31
+ it, so that its speed varies by no more than (1 + b) / (1 - b); l_o must be
32
+ at least q_o l, so that the map is not merely uniform but also long enough
33
+ in that observer's view. Without b (the default), only the lower limit
34
+ |u_{i+1} - u_i|_o >= l_o >= q_o l applies, and q_o = 0 (the default)
35
+ leaves the observer's steps free. Equal steps for every observer at once
36
+ cannot be had in general: a direction has two degrees of freedom, and fixed
37
+ ratios of speed for three other observers are three conditions on it.
38
+
39
+ Either rho is maximised at a given step l (a given total length), or l is
40
+ maximised at a given rho. The method is sequential linear programming in a
41
+ trust region, as in the max-min polish of MCCP (mccp.optimise.polish_maxmin).
42
+ """
43
+
44
+ import numpy as np
45
+
46
+ from ..space import Observer, Space
47
+ from .paths import PATH_VIEW
48
+
49
+
50
+ class CurveProblem:
51
+ def __init__(self, m, view=PATH_VIEW, observers=(), bounds=None):
52
+ self.m = m
53
+ obs = (Observer(),) + tuple(observers)
54
+ self.space = Space(view, obs)
55
+ self.prio = np.array([o.priority for o in obs])
56
+ self.k_l = self.space.ucs.K_L
57
+ self.bounds = bounds
58
+
59
+ def coords(self, x):
60
+ return self.space.coords(x) # (k, m, 3)
61
+
62
+ def steps(self, u0):
63
+ return np.linalg.norm(np.diff(u0, axis=0), axis=1)
64
+
65
+
66
+ def _pairs(m):
67
+ return np.triu_indices(m, 2)
68
+
69
+
70
+ def pair_limits(d, a):
71
+ """For pairs at distance d and arc a, the largest rho that satisfies
72
+ (1) for each pair. The right side of (1) increases with rho, so the
73
+ thickness of the curve is the least of these."""
74
+ d, a = np.broadcast_arrays(np.asarray(d, float), np.asarray(a, float))
75
+ out = np.full(d.shape, np.inf)
76
+ near = d <= 2 * a / np.pi # bound at rho <= 2 a / pi: rho = d
77
+ out[near] = d[near]
78
+ mid = ~near & (d < a) # solve sin(x) / x = d / a, rho = a / x
79
+ if mid.any():
80
+ r = d[mid] / a[mid]
81
+ lo, hi = np.zeros(r.shape), np.full(r.shape, np.pi / 2)
82
+ for _ in range(50):
83
+ x = 0.5 * (lo + hi)
84
+ big = np.sinc(x / np.pi) > r # sin(x)/x decreases on (0, pi/2]
85
+ lo, hi = np.where(big, x, lo), np.where(big, hi, x)
86
+ out[mid] = a[mid] / hi
87
+ return out
88
+
89
+
90
+ def thickness(u, priority=1.0, arc=None):
91
+ """Largest rho for which a sampled curve u (M, 3) satisfies (1), for an
92
+ observer of the given priority. The arcs are measured along u unless
93
+ given (the optimiser measures them in normal vision for every
94
+ observer)."""
95
+ m = len(u)
96
+ if m < 3:
97
+ return np.inf
98
+ if arc is None:
99
+ arc = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(u, axis=0), axis=1))])
100
+ i, j = _pairs(m)
101
+ d = np.linalg.norm(u[i] - u[j], axis=1) / priority
102
+ return float(pair_limits(d, arc[j] - arc[i]).min())
103
+
104
+
105
+ def _other_steps(st_o, ref, q, band):
106
+ """Shortfall in condition (2) for one observer's steps st_o: the gap
107
+ between the least and greatest l_o that it allows."""
108
+ upper = st_o.min() / (1.0 if band is None else 1.0 - band)
109
+ lower = q * ref if band is None else max(q * ref, st_o.max() / (1.0 + band))
110
+ return max(0.0, float(lower - upper))
111
+
112
+
113
+ def _state(prob, x, step, rho, bounds, q, band=None):
114
+ """Objective and violations of a curve: (objective, step deviation,
115
+ bound violation, thickness shortfall, thickness, steps, shortfall in
116
+ condition (2))."""
117
+ u = prob.coords(x)
118
+ k = len(prob.prio)
119
+ st = prob.steps(u[0])
120
+ arc = np.concatenate([[0], np.cumsum(st)])
121
+ rho_now = min(thickness(u[o], prob.prio[o], arc) for o in range(k))
122
+ viol = 0.0
123
+ if bounds is not None:
124
+ viol = max(0.0, -float(bounds.slack(u[0], prob.k_l, np.ones(len(x))).min()))
125
+ ref = step if step is not None else float(st.mean())
126
+ slow = max([0.0] + [_other_steps(prob.steps(u[o]), ref, q[o], band) for o in range(1, k)
127
+ if q[o] > 0 or band is not None])
128
+ if step is not None:
129
+ return rho_now, float(np.abs(st - step).max()), viol, 0.0, rho_now, st, slow
130
+ return float(st.min()), float(np.ptp(st)), viol, max(0.0, rho - rho_now), rho_now, st, slow
131
+
132
+
133
+ def optimise(x, step=None, rho=None, observers=(), bounds=None, view=PATH_VIEW, iters=300,
134
+ radius=0.01, active_margin=4.0, penalty=20.0, least_step=0.0, band=None,
135
+ verbose=False):
136
+ """Improve a curve x (M, 3) in sRGB.
137
+
138
+ Give `step` to maximise the thickness at that step length, or `rho` to
139
+ maximise the step at that thickness. least_step is q_o of (2), one value
140
+ for all the observers or one for each, and band is b of (2), or None for
141
+ a lower limit only. The conditions are elastic: each
142
+ linear programme may violate them at a cost `penalty` per unit, so that a
143
+ start that does not meet them exactly can still move. Returns (x, info)."""
144
+ from scipy.optimize import linprog
145
+
146
+ if (step is None) == (rho is None):
147
+ raise ValueError("Give exactly one of step and rho.")
148
+ x = np.clip(np.asarray(x, float), 0, 1)
149
+ m = len(x)
150
+ prob = CurveProblem(m, view, observers, bounds)
151
+ k = len(prob.prio)
152
+ q = np.concatenate([[0.0], np.broadcast_to(np.asarray(least_step, float), (k - 1,))])
153
+ # Variables: the moves dx, then Z (the thickness or the step), the
154
+ # elastic slacks of the equal steps, the bounds, the thickness and the
155
+ # other observers' steps, each its own so that violating one condition
156
+ # does not make the others free, then l_o of (2) for observers 1 ... k - 1.
157
+ ne = 5 + (k - 1)
158
+ nv = 3 * m + ne
159
+ Z, ES, EB, ET, EO = 3 * m, 3 * m + 1, 3 * m + 2, 3 * m + 3, 3 * m + 4
160
+ LO = 3 * m + 5
161
+ i_all, j_all = _pairs(m)
162
+
163
+ def merit(st):
164
+ return st[0] - penalty * (st[1] + st[2] + st[3] + st[6])
165
+
166
+ cur = _state(prob, x, step, rho, bounds, q, band)
167
+ history = [dict(it=0, objective=cur[0], dev=cur[1], viol=cur[2], short=cur[3],
168
+ slow=cur[6], rho=cur[4], radius=radius)]
169
+ for it in range(1, iters + 1):
170
+ u, jac = prob.space.jacobian(x)
171
+ rows, rhs = [], []
172
+ # Equal steps (normal vision), elastic: |lin_i - s| <= e_s.
173
+ e = u[0, 1:] - u[0, :-1]
174
+ L = np.linalg.norm(e, axis=1)
175
+ nvec = e / L[:, None]
176
+ G = np.zeros((m - 1, nv))
177
+ idx = np.arange(m - 1)
178
+ gi = -np.einsum("nc,ncd->nd", nvec, jac[0, :-1])
179
+ gj = np.einsum("nc,ncd->nd", nvec, jac[0, 1:])
180
+ for c in range(3):
181
+ G[idx, 3 * idx + c] = gi[:, c]
182
+ G[idx, 3 * (idx + 1) + c] = gj[:, c]
183
+ if step is None:
184
+ G[:, Z] = -1.0
185
+ off = L
186
+ else:
187
+ off = L - step
188
+ for sign in (1.0, -1.0):
189
+ g = sign * G
190
+ g[:, ES] = -1.0
191
+ rows.append(g)
192
+ rhs.append(-sign * off)
193
+ # Steps (2) for the other observers, elastic in e_o:
194
+ # (1 - b) l_o - e_o <= L_o + lin_o <= (1 + b) l_o + e_o, l_o >= q_o l,
195
+ # with l the step or the free variable Z.
196
+ lo_f = 1.0 if band is None else 1.0 - band
197
+ for o in range(1, k):
198
+ if q[o] <= 0 and band is None:
199
+ continue
200
+ eo = u[o, 1:] - u[o, :-1]
201
+ Lo = np.linalg.norm(eo, axis=1)
202
+ no = eo / np.maximum(Lo, 1e-12)[:, None]
203
+ H = np.zeros((m - 1, nv))
204
+ hi_ = np.einsum("nc,ncd->nd", no, jac[o, :-1])
205
+ hj_ = np.einsum("nc,ncd->nd", no, jac[o, 1:])
206
+ for c in range(3):
207
+ H[idx, 3 * idx + c] = hi_[:, c]
208
+ H[idx, 3 * (idx + 1) + c] = -hj_[:, c]
209
+ H[:, EO] = -1.0
210
+ H[:, LO + o - 1] = lo_f
211
+ rows.append(H)
212
+ rhs.append(Lo)
213
+ if band is not None:
214
+ Hu = -H
215
+ Hu[:, EO] = -1.0
216
+ Hu[:, LO + o - 1] = -(1.0 + band)
217
+ rows.append(Hu)
218
+ rhs.append(-Lo)
219
+ g = np.zeros((1, nv))
220
+ g[0, LO + o - 1] = -1.0
221
+ if step is None:
222
+ g[0, Z] = q[o]
223
+ rhs.append([0.0])
224
+ else:
225
+ rhs.append([-q[o] * step])
226
+ rows.append(g)
227
+ # Thickness (1), every observer, pairs near the bound only. The right
228
+ # side p rho s(a / rho) is linearised in the free variable Z, the
229
+ # thickness or the step (on which the arcs depend), as c1 Z + c0:
230
+ # d + n.(J_i dx_i - J_j dx_j) >= p (c1 Z + c0) - e_t.
231
+ arc = np.concatenate([[0], np.cumsum(L)])
232
+ a = arc[j_all] - arc[i_all]
233
+ if rho is None:
234
+ xc = np.minimum(a / cur[4], np.pi / 2)
235
+ c1, c0 = np.sin(xc) - xc * np.cos(xc), a * np.cos(xc)
236
+ else:
237
+ xc = np.minimum(a / rho, np.pi / 2)
238
+ c1 = a / L.mean() * np.cos(xc)
239
+ c0 = rho * np.sin(xc) - a * np.cos(xc)
240
+ z0 = cur[4] if rho is None else L.mean()
241
+ for o in range(k):
242
+ diff = u[o, i_all] - u[o, j_all]
243
+ d = np.linalg.norm(diff, axis=1)
244
+ p = prob.prio[o]
245
+ act = np.flatnonzero(d < p * (c1 * z0 + c0) + active_margin)
246
+ if not len(act):
247
+ continue
248
+ ii, jj, dd = i_all[act], j_all[act], d[act]
249
+ nn = diff[act] / dd[:, None]
250
+ T = np.zeros((len(act), nv))
251
+ ti = -np.einsum("nc,ncd->nd", nn, jac[o, ii])
252
+ tj = np.einsum("nc,ncd->nd", nn, jac[o, jj])
253
+ r = np.arange(len(act))
254
+ for c in range(3):
255
+ T[r, 3 * ii + c] = ti[:, c]
256
+ T[r, 3 * jj + c] = tj[:, c]
257
+ T[:, ET] = -1.0
258
+ T[:, Z] = p * c1[act]
259
+ rows.append(T)
260
+ rhs.append(dd - p * c0[act])
261
+ # Lightness floor and ceiling (normal vision): slack + grad.dx >= -e_b.
262
+ if bounds is not None:
263
+ sl = bounds.slack(u[0], prob.k_l, np.ones(m)) # (2, m)
264
+ sg = bounds.slack_grad(u[0], prob.k_l, np.ones(m)) # (2, m, 3)
265
+ for c2 in range(2):
266
+ Bm = np.zeros((m, nv))
267
+ gb = -np.einsum("nc,ncd->nd", sg[c2], jac[0])
268
+ for c in range(3):
269
+ Bm[np.arange(m), 3 * np.arange(m) + c] = gb[:, c]
270
+ Bm[:, EB] = -1.0
271
+ rows.append(Bm)
272
+ rhs.append(sl[c2])
273
+ lo = list(np.maximum(-radius, -x.ravel())) + [0.0] * ne
274
+ hi = list(np.minimum(radius, 1 - x.ravel())) + [None] * ne
275
+ cvec = np.zeros(nv)
276
+ cvec[Z] = -1.0
277
+ cvec[ES] = cvec[EB] = cvec[ET] = cvec[EO] = penalty
278
+ res = linprog(cvec, A_ub=np.vstack(rows), b_ub=np.concatenate(rhs),
279
+ bounds=list(zip(lo, hi)), method="highs")
280
+ if res.status != 0:
281
+ radius *= 0.5
282
+ if radius < 1e-6:
283
+ break
284
+ continue
285
+ x_new = np.clip(x + res.x[:3 * m].reshape(m, 3), 0, 1)
286
+ new = _state(prob, x_new, step, rho, bounds, q, band)
287
+ if merit(new) > merit(cur) + 1e-9:
288
+ x, cur = x_new, new
289
+ history.append(dict(it=it, objective=cur[0], dev=cur[1], viol=cur[2],
290
+ short=cur[3], slow=cur[6], rho=cur[4], radius=radius))
291
+ if verbose and len(history) % 10 == 0:
292
+ print(f"{it}: objective {cur[0]:.3f} rho {cur[4]:.2f} step dev {cur[1]:.3f} "
293
+ f"bound viol {cur[2]:.3f} r {radius:.4f}", flush=True)
294
+ radius = min(radius * 1.5, 0.05)
295
+ else:
296
+ radius *= 0.5
297
+ if radius < 1e-6:
298
+ break
299
+ info = dict(history=history, rho=cur[4], step=float(np.mean(cur[5])),
300
+ length=float(cur[5].sum()), step_dev=cur[1], bound_violation=cur[2],
301
+ slow=cur[6])
302
+ return x, info
303
+
304
+
305
+ def resample_equal(rgb, m, view=PATH_VIEW):
306
+ """m points at equal arc length along the polyline through rgb, in sRGB."""
307
+ from ..space import CAM16UCS, linear_to_srgb
308
+ ucs = CAM16UCS(view)
309
+ u = ucs(np.asarray(rgb, float))
310
+ arc = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(u, axis=0), axis=1))])
311
+ t = np.linspace(0, arc[-1], m)
312
+ us = np.stack([np.interp(t, arc, u[:, k]) for k in range(3)], -1)
313
+ return linear_to_srgb(ucs.to_linear(us))