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,914 @@
1
+ """Choice of N colours by maximising the least scaled distance.
2
+
3
+ Stages (docs/design.md, Section 6):
4
+ 1. starting sets: farthest-point selection on a candidate grid followed by a
5
+ swap search, plus seeded random draws;
6
+ 2. refinement: L-BFGS-B on a soft minimum of the scaled distances, with
7
+ penalties for the anchor and background conditions, at increasing
8
+ sharpness;
9
+ 3. polish: sequential linear programming on a trust region, maximising the
10
+ exact minimum over all pairs and observers;
11
+ 4. spreading: sequential linear programming on the sum of each colour's
12
+ soft minimum, with the exact minimum held.
13
+ """
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+ from scipy.optimize import linprog, minimize
19
+ from scipy.sparse import coo_matrix
20
+
21
+ from ..bounds import _lstar
22
+ from ..space import Observer, Space, hex_to_rgb, relative_luminance, rgb_to_hex, to_hex, viewing
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Anchor:
27
+ """A fixed colour that chosen colours must keep clear of.
28
+
29
+ clearance: least distance in CAM16-UCS units, multiplied by the radius.
30
+ lightness: least lightness difference, for the background; None otherwise.
31
+ """
32
+
33
+ colour: str
34
+ clearance: float
35
+ lightness: float | None = None
36
+
37
+ @property
38
+ def rgb(self):
39
+ return hex_to_rgb(self.colour)[0]
40
+
41
+
42
+ @dataclass
43
+ class Eval:
44
+ u: np.ndarray # (k, n, 3) coordinates of chosen colours
45
+ jac: np.ndarray # (k, n, 3, 3)
46
+ q: np.ndarray # (k, P) scaled pair distances
47
+ diff: np.ndarray # (k, P, 3)
48
+ dist: np.ndarray # (k, P)
49
+ aslack: np.ndarray # (k, n, M) anchor slack
50
+ adiff: np.ndarray
51
+ adist: np.ndarray
52
+ lslack: np.ndarray # (k, n) background lightness slack (one-sided)
53
+ bslack: np.ndarray = None # (2, n) hue-dependent lightness bounds, normal vision
54
+ bgrad: np.ndarray = None # (2, n, 3) derivative of bslack with respect to u
55
+
56
+
57
+ @dataclass
58
+ class Problem:
59
+ n: int
60
+ space: Space
61
+ anchors: list
62
+ radii: np.ndarray
63
+ fixed_rgb: np.ndarray = field(default_factory=lambda: np.zeros((0, 3)))
64
+ fixed_radii: np.ndarray = field(default_factory=lambda: np.zeros(0))
65
+ bounds: object = None # HueBounds, or None
66
+
67
+ def __post_init__(self):
68
+ self.radii = np.asarray(self.radii, dtype=float)
69
+ k = len(self.space.observers)
70
+ m = len(self.anchors)
71
+ self.anchor_d = np.array([a.clearance for a in self.anchors], dtype=float)
72
+ self.anchor_coords = (self.space.coords(np.array([a.rgb for a in self.anchors]))
73
+ if m else np.zeros((k, 0, 3)))
74
+ bg = [i for i, a in enumerate(self.anchors) if a.lightness is not None]
75
+ self.bg_index = bg[0] if bg else None
76
+ # The lightness condition is stated in ordinary J' units. Coordinates
77
+ # carry J'/K_L, so the requirement is scaled to match.
78
+ self.bg_dj = self.anchors[bg[0]].lightness / self.space.ucs.K_L if bg else 0.0
79
+ # side[i] = +1 if colour i must be lighter than the background, -1 darker.
80
+ self.side = np.full(self.n, -1.0)
81
+ self.fixed_coords = (self.space.coords(self.fixed_rgb) if len(self.fixed_rgb)
82
+ else np.zeros((k, 0, 3)))
83
+ n, f = self.n, len(self.fixed_rgb)
84
+ i, j = np.triu_indices(n, 1)
85
+ fi, fj = np.meshgrid(np.arange(n), np.arange(f), indexing="ij")
86
+ self.pi = np.concatenate([i, fi.ravel()]).astype(int)
87
+ self.pj = np.concatenate([j, n + fj.ravel()]).astype(int)
88
+ allr = np.concatenate([self.radii, np.asarray(self.fixed_radii, dtype=float)])
89
+ self.prr = allr[self.pi] + allr[self.pj]
90
+ # Per observer: the required spacing of a pair is s * (r_i + r_j) * f_o.
91
+ f = np.array([o.priority for o in self.space.observers], dtype=float)
92
+ if np.any(f <= 0) or np.any(f > 1):
93
+ raise ValueError("Observer priorities must lie in (0, 1].")
94
+ self.prrk = f[:, None] * self.prr[None, :]
95
+ self.priority = f
96
+
97
+ def set_sides(self, rgb):
98
+ if self.bounds is not None:
99
+ self.side = self.bounds.side_of(self.space.coords(rgb)[0], self.space.ucs.K_L)
100
+ return
101
+ if self.bg_index is None:
102
+ return
103
+ u = self.space.coords(rgb)[0]
104
+ jb = self.anchor_coords[0, self.bg_index, 0]
105
+ self.side = np.where(u[:, 0] >= jb, 1.0, -1.0)
106
+
107
+ def evaluate(self, rgb, with_jac=True):
108
+ if with_jac:
109
+ u, jac = self.space.jacobian(rgb)
110
+ else:
111
+ u, jac = self.space.coords(rgb), None
112
+ ua = np.concatenate([u, self.fixed_coords], axis=1)
113
+ diff = ua[:, self.pi] - ua[:, self.pj]
114
+ dist = np.linalg.norm(diff, axis=-1)
115
+ q = dist / self.prrk
116
+ adiff = u[:, :, None, :] - self.anchor_coords[:, None, :, :]
117
+ adist = np.linalg.norm(adiff, axis=-1)
118
+ aslack = adist - self.anchor_d[None, None, :] * self.radii[None, :, None]
119
+ if self.bg_index is not None:
120
+ dj = u[..., 0] - self.anchor_coords[:, self.bg_index, None, 0]
121
+ lslack = self.side[None, :] * dj - self.bg_dj * self.radii[None, :]
122
+ else:
123
+ lslack = np.zeros(u.shape[:2])
124
+ bslack = bgrad = None
125
+ if self.bounds is not None:
126
+ k_l = self.space.ucs.K_L
127
+ bslack = self.bounds.slack(u[0], k_l, self.side)
128
+ bgrad = self.bounds.slack_grad(u[0], k_l, self.side) if with_jac else None
129
+ return Eval(u, jac, q, diff, dist, aslack, adiff, adist, lslack, bslack, bgrad)
130
+
131
+ def score(self, ev):
132
+ return ev.q.min() if ev.q.size else np.inf
133
+
134
+ def violation(self, ev):
135
+ v = 0.0
136
+ if ev.aslack.size:
137
+ v = max(v, -ev.aslack.min())
138
+ if self.bg_index is not None:
139
+ v = max(v, -ev.lslack.min())
140
+ if ev.bslack is not None and ev.bslack.size:
141
+ v = max(v, -ev.bslack.min())
142
+ return max(v, 0.0)
143
+
144
+
145
+ # --- gradients -------------------------------------------------------------
146
+
147
+
148
+ def _pair_grad(prob, ev, coef):
149
+ """Gradient wrt chosen sRGB of sum(coef * q), coef of shape (k, P)."""
150
+ n = prob.n
151
+ g = np.zeros((n, 3))
152
+ unit = ev.diff / np.maximum(ev.dist, 1e-12)[..., None] * (coef / prob.prrk)[..., None]
153
+ gi = np.einsum("kpa,kpab->pb", unit, ev.jac[:, prob.pi])
154
+ np.add.at(g, prob.pi, gi)
155
+ free = prob.pj < n
156
+ gj = np.einsum("kpa,kpab->pb", unit[:, free], ev.jac[:, prob.pj[free]])
157
+ np.add.at(g, prob.pj[free], -gj)
158
+ return g
159
+
160
+
161
+ def _softmin(q, beta):
162
+ m = q.min()
163
+ w = np.exp(-beta * (q - m))
164
+ s = w.sum()
165
+ return m - np.log(s) / beta, w / s
166
+
167
+
168
+ def _penalty(prob, ev, mu):
169
+ val = 0.0
170
+ g = np.zeros((prob.n, 3))
171
+ if ev.aslack.size:
172
+ v = np.minimum(ev.aslack, 0.0)
173
+ val += mu * np.sum(v ** 2)
174
+ coef = 2 * mu * v / np.maximum(ev.adist, 1e-12)
175
+ gu = np.sum(coef[..., None] * ev.adiff, axis=2)
176
+ g += np.einsum("kna,knab->nb", gu, ev.jac)
177
+ if prob.bg_index is not None:
178
+ v = np.minimum(ev.lslack, 0.0)
179
+ val += mu * np.sum(v ** 2)
180
+ g += np.einsum("kn,knb->nb", 2 * mu * v * prob.side[None, :], ev.jac[:, :, 0, :])
181
+ if ev.bslack is not None:
182
+ v = np.minimum(ev.bslack, 0.0)
183
+ val += mu * np.sum(v ** 2)
184
+ g += np.einsum("sn,sna,nab->nb", 2 * mu * v, ev.bgrad, ev.jac[0])
185
+ return val, g
186
+
187
+
188
+ # --- stage 1: starting sets --------------------------------------------------
189
+
190
+
191
+ def candidate_grid(steps=24):
192
+ g = np.linspace(0, 1, steps)
193
+ return np.stack(np.meshgrid(g, g, g, indexing="ij"), -1).reshape(-1, 3)
194
+
195
+
196
+ def _capacity(prob, u):
197
+ """Largest radius each candidate can carry under the anchor and
198
+ background conditions, for every observer: (C,)."""
199
+ cap = np.full(u.shape[1], np.inf)
200
+ if prob.anchor_coords.shape[1]:
201
+ d = np.linalg.norm(u[:, :, None, :] - prob.anchor_coords[:, None], axis=-1)
202
+ with np.errstate(divide="ignore"):
203
+ ratio = np.where(prob.anchor_d > 0, d / prob.anchor_d, np.inf)
204
+ cap = np.minimum(cap, ratio.min(axis=(0, 2)))
205
+ if prob.bg_index is not None and prob.bg_dj > 0:
206
+ dj = np.abs(u[..., 0] - prob.anchor_coords[:, prob.bg_index, None, 0])
207
+ cap = np.minimum(cap, (dj / prob.bg_dj).min(axis=0))
208
+ if prob.bounds is not None:
209
+ # The hue-dependent bounds do not scale with the radius.
210
+ inside = prob.bounds.feasible(u[0], prob.space.ucs.K_L)
211
+ cap = np.where(inside, cap, 0.0)
212
+ return cap
213
+
214
+
215
+ def _feasible_candidates(prob, cand):
216
+ """Candidates admissible for at least the smallest radius, their
217
+ coordinates, and their capacities. Raises if some colour has none."""
218
+ u = prob.space.coords(cand)
219
+ cap = _capacity(prob, u)
220
+ for r in np.unique(prob.radii):
221
+ if not np.any(cap >= r):
222
+ raise ValueError(
223
+ f"No admissible colour for radius {r:g}: the anchors "
224
+ f"({', '.join(a.colour for a in prob.anchors)}) with their clearances "
225
+ "exclude every colour on the candidate grid.")
226
+ ok = cap >= (prob.radii.min() if prob.n else 0.0)
227
+ return cand[ok], u[:, ok], cap[ok]
228
+
229
+
230
+ def _nearest_to_set(u_cand, u_set, r_cand, r_set, f=None):
231
+ """Least scaled distance from each candidate to a set: (C,). f holds the
232
+ observer priorities."""
233
+ if u_set.shape[1] == 0:
234
+ return np.full(u_cand.shape[1], np.inf)
235
+ d = np.linalg.norm(u_cand[:, :, None, :] - u_set[:, None, :, :], axis=-1)
236
+ d = d / (r_cand + r_set[None, None, :])
237
+ if f is not None:
238
+ d = d / f[:, None, None]
239
+ return d.min(axis=(0, 2))
240
+
241
+
242
+ def farthest_point(prob, uc, cap):
243
+ """Greedy farthest-point selection; returns candidate indices.
244
+
245
+ Colour i may only take candidates whose capacity covers its radius. The
246
+ first colour, when there are no fixed members, is the candidate farthest
247
+ from the anchors relative to their clearances."""
248
+ fr = np.asarray(prob.fixed_radii, float)
249
+ chosen = []
250
+ taken = np.zeros(uc.shape[1], bool)
251
+ for i in range(prob.n):
252
+ r = prob.radii[i]
253
+ u_set = np.concatenate([uc[:, chosen], prob.fixed_coords], axis=1)
254
+ r_set = np.concatenate([prob.radii[:i], fr])
255
+ score = _nearest_to_set(uc, u_set, r, r_set, prob.priority)
256
+ if np.all(np.isinf(score)):
257
+ score = cap.copy()
258
+ score[(cap < r) | taken] = -np.inf
259
+ k = int(np.argmax(score))
260
+ chosen.append(k)
261
+ taken[k] = True
262
+ return np.array(chosen)
263
+
264
+
265
+ def swap_search(prob, uc, cap, idx, sweeps=20):
266
+ """Move each colour in turn to the admissible candidate farthest from
267
+ the rest, until a sweep brings no gain."""
268
+ idx = idx.copy()
269
+ fr = np.asarray(prob.fixed_radii, float)
270
+ for _ in range(sweeps):
271
+ improved = False
272
+ for i in range(prob.n):
273
+ others = np.delete(idx, i)
274
+ u_set = np.concatenate([uc[:, others], prob.fixed_coords], axis=1)
275
+ r_set = np.concatenate([np.delete(prob.radii, i), fr])
276
+ near = _nearest_to_set(uc, u_set, prob.radii[i], r_set, prob.priority)
277
+ near[others] = -np.inf
278
+ near[cap < prob.radii[i]] = -np.inf
279
+ cur = near[idx[i]]
280
+ k = int(np.argmax(near))
281
+ if near[k] > cur * (1 + 1e-9):
282
+ idx[i] = k
283
+ improved = True
284
+ if not improved:
285
+ break
286
+ return idx
287
+
288
+
289
+ def random_start(prob, cap, rng):
290
+ idx = []
291
+ for r in prob.radii:
292
+ pool = np.flatnonzero(cap >= r)
293
+ idx.append(int(rng.choice(pool)))
294
+ return np.array(idx)
295
+
296
+
297
+ # --- stage 2: soft-minimum refinement ----------------------------------------
298
+
299
+
300
+ def refine_softmin(prob, x0, rel_betas=(4.0, 16.0, 64.0), mu=10.0, maxiter=200):
301
+ x = x0.ravel().copy()
302
+ for b in rel_betas:
303
+ s0 = max(prob.score(prob.evaluate(x.reshape(-1, 3), with_jac=False)), 1e-3)
304
+ beta = b / s0
305
+
306
+ def f(xf):
307
+ ev = prob.evaluate(xf.reshape(-1, 3))
308
+ sm, w = _softmin(ev.q, beta)
309
+ pv, pg = _penalty(prob, ev, mu)
310
+ return -sm + pv, (-_pair_grad(prob, ev, w) + pg).ravel()
311
+
312
+ x = minimize(f, x, jac=True, method="L-BFGS-B", bounds=[(0, 1)] * x.size,
313
+ options=dict(maxiter=maxiter)).x
314
+ return x.reshape(-1, 3)
315
+
316
+
317
+ # --- linearised constraints --------------------------------------------------
318
+
319
+
320
+ def _linear_rows(prob, ev, pair_mask, anchor_mask, light_mask, bound_mask=None):
321
+ """Sparse rows a such that each constraint value changes by a @ dx."""
322
+ n = prob.n
323
+ rows, cols, vals = [], [], []
324
+ vals_c = []
325
+ r = 0
326
+ o_idx, p_idx = np.nonzero(pair_mask)
327
+ if len(o_idx):
328
+ unit = (ev.diff[o_idx, p_idx] / np.maximum(ev.dist[o_idx, p_idx], 1e-12)[:, None]
329
+ / prob.prrk[o_idx, p_idx][:, None])
330
+ i = prob.pi[p_idx]
331
+ j = prob.pj[p_idx]
332
+ gi = np.einsum("sa,sab->sb", unit, ev.jac[o_idx, i])
333
+ rr = r + np.arange(len(o_idx))
334
+ for b in range(3):
335
+ rows.append(rr); cols.append(3 * i + b); vals.append(gi[:, b])
336
+ free = j < n
337
+ gj = np.einsum("sa,sab->sb", unit[free], ev.jac[o_idx[free], j[free]])
338
+ for b in range(3):
339
+ rows.append(rr[free]); cols.append(3 * j[free] + b); vals.append(-gj[:, b])
340
+ vals_c.append(ev.q[o_idx, p_idx])
341
+ r += len(o_idx)
342
+ n_pair = r
343
+ o_idx, i_idx, m_idx = np.nonzero(anchor_mask)
344
+ if len(o_idx):
345
+ unit = (ev.adiff[o_idx, i_idx, m_idx]
346
+ / np.maximum(ev.adist[o_idx, i_idx, m_idx], 1e-12)[:, None])
347
+ g = np.einsum("sa,sab->sb", unit, ev.jac[o_idx, i_idx])
348
+ rr = r + np.arange(len(o_idx))
349
+ for b in range(3):
350
+ rows.append(rr); cols.append(3 * i_idx + b); vals.append(g[:, b])
351
+ vals_c.append(ev.aslack[o_idx, i_idx, m_idx])
352
+ r += len(o_idx)
353
+ o_idx, i_idx = np.nonzero(light_mask)
354
+ if len(o_idx):
355
+ g = prob.side[i_idx][:, None] * ev.jac[o_idx, i_idx, 0, :]
356
+ rr = r + np.arange(len(o_idx))
357
+ for b in range(3):
358
+ rows.append(rr); cols.append(3 * i_idx + b); vals.append(g[:, b])
359
+ vals_c.append(ev.lslack[o_idx, i_idx])
360
+ r += len(o_idx)
361
+ if bound_mask is not None:
362
+ s_idx, i_idx = np.nonzero(bound_mask)
363
+ if len(s_idx):
364
+ g = np.einsum("sa,sab->sb", ev.bgrad[s_idx, i_idx], ev.jac[0, i_idx])
365
+ rr = r + np.arange(len(s_idx))
366
+ for b in range(3):
367
+ rows.append(rr); cols.append(3 * i_idx + b); vals.append(g[:, b])
368
+ vals_c.append(ev.bslack[s_idx, i_idx])
369
+ r += len(s_idx)
370
+ A = coo_matrix((np.concatenate(vals) if vals else [],
371
+ (np.concatenate(rows) if rows else [], np.concatenate(cols) if cols else [])),
372
+ shape=(r, 3 * n)).tocsr()
373
+ c = np.concatenate(vals_c) if vals_c else np.zeros(0)
374
+ return A, c, n_pair
375
+
376
+
377
+ def _masks(prob, ev, q_limit, slack_limit):
378
+ pair = ev.q < q_limit
379
+ anchor = ev.aslack < slack_limit if ev.aslack.size else np.zeros(ev.aslack.shape, bool)
380
+ light = (ev.lslack < slack_limit if prob.bg_index is not None
381
+ else np.zeros(ev.lslack.shape, bool))
382
+ bound = ev.bslack < slack_limit if ev.bslack is not None else None
383
+ return pair, anchor, light, bound
384
+
385
+
386
+ # --- stage 3: exact max-min by sequential linear programming -----------------
387
+
388
+
389
+ def polish_maxmin(prob, rgb, radius=0.05, min_radius=1e-5, max_iter=300, elastic=100.0):
390
+ x = rgb.ravel().copy()
391
+ ev = prob.evaluate(x.reshape(-1, 3))
392
+ merit = prob.score(ev) - elastic * prob.violation(ev)
393
+ for _ in range(max_iter):
394
+ if radius < min_radius:
395
+ break
396
+ s = prob.score(ev)
397
+ jmax = np.abs(ev.jac).max()
398
+ reach = 2 * np.sqrt(3) * jmax * radius # largest change of a distance
399
+ pm, am, lm, bm = _masks(prob, ev, s + reach / prob.prrk.min(), reach)
400
+ A, c, n_pair = _linear_rows(prob, ev, pm, am, lm, bm)
401
+ n_var = 3 * prob.n
402
+ # Variables: dx (n_var), t, e (elastic violation of anchor/light rows).
403
+ # Pair rows: q + a dx >= t -> -a dx + t <= q
404
+ # Other rows: slack + a dx >= -e -> -a dx - e <= slack
405
+ A_ub = np.zeros((A.shape[0], n_var + 2))
406
+ A_ub[:, :n_var] = -A.toarray()
407
+ A_ub[:n_pair, n_var] = 1.0
408
+ A_ub[n_pair:, n_var + 1] = -1.0
409
+ lo = np.maximum(-radius, -x)
410
+ hi = np.minimum(radius, 1 - x)
411
+ bounds = list(zip(lo, hi)) + [(None, None), (0, None)]
412
+ cost = np.zeros(n_var + 2)
413
+ cost[n_var] = -1.0
414
+ cost[n_var + 1] = elastic
415
+ res = linprog(cost, A_ub=A_ub, b_ub=c, bounds=bounds, method="highs")
416
+ if res.status != 0:
417
+ radius *= 0.5
418
+ continue
419
+ x_new = np.clip(x + res.x[:n_var], 0, 1)
420
+ ev_new = prob.evaluate(x_new.reshape(-1, 3))
421
+ merit_new = prob.score(ev_new) - elastic * prob.violation(ev_new)
422
+ if merit_new > merit + 1e-10:
423
+ gain = merit_new - merit
424
+ x, ev, merit = x_new, ev_new, merit_new
425
+ radius = min(radius * 1.5, 0.2)
426
+ if gain < 1e-7:
427
+ break
428
+ else:
429
+ radius *= 0.5
430
+ return x.reshape(-1, 3)
431
+
432
+
433
+ # --- stage 4: spreading the colours that are not binding ---------------------
434
+
435
+
436
+ def _spread_objective(prob, ev, beta):
437
+ """Sum over observers and colours of each colour's soft minimum."""
438
+ n = prob.n
439
+ total = 0.0
440
+ coef = np.zeros_like(ev.q)
441
+ for o in range(ev.q.shape[0]):
442
+ q = ev.q[o]
443
+ m = q.min()
444
+ e = np.exp(-beta * (q - m))
445
+ z = np.zeros(n)
446
+ np.add.at(z, prob.pi, e)
447
+ free = prob.pj < n
448
+ np.add.at(z, prob.pj[free], e[free])
449
+ z = np.maximum(z, 1e-300)
450
+ total += np.sum(m - np.log(z) / beta)
451
+ c = e / z[prob.pi]
452
+ c[free] += e[free] / z[prob.pj[free]]
453
+ coef[o] = c
454
+ return total, coef
455
+
456
+
457
+ def spread(prob, rgb, s_star, beta_rel=3.0, radius=0.02, min_radius=1e-5, max_iter=200):
458
+ x = rgb.ravel().copy()
459
+ beta = beta_rel / max(s_star, 1e-6)
460
+ floor = s_star * (1 - 1e-6)
461
+ ev = prob.evaluate(x.reshape(-1, 3))
462
+ obj, coef = _spread_objective(prob, ev, beta)
463
+ for _ in range(max_iter):
464
+ if radius < min_radius:
465
+ break
466
+ jmax = np.abs(ev.jac).max()
467
+ reach = 2 * np.sqrt(3) * jmax * radius
468
+ pm, am, lm, bm = _masks(prob, ev, floor + reach / prob.prrk.min(), reach)
469
+ A, c, n_pair = _linear_rows(prob, ev, pm, am, lm, bm)
470
+ g = _pair_grad(prob, ev, coef).ravel()
471
+ b_ub = c.copy()
472
+ b_ub[:n_pair] -= floor
473
+ lo = np.maximum(-radius, -x)
474
+ hi = np.minimum(radius, 1 - x)
475
+ res = linprog(-g, A_ub=-A.toarray() if A.shape[0] else None,
476
+ b_ub=b_ub if A.shape[0] else None,
477
+ bounds=list(zip(lo, hi)), method="highs")
478
+ if res.status != 0:
479
+ radius *= 0.5
480
+ continue
481
+ x_new = np.clip(x + res.x, 0, 1)
482
+ ev_new = prob.evaluate(x_new.reshape(-1, 3))
483
+ obj_new, coef_new = _spread_objective(prob, ev_new, beta)
484
+ ok = prob.score(ev_new) >= floor and prob.violation(ev_new) <= prob.violation(ev) + 1e-9
485
+ if ok and obj_new > obj + 1e-9:
486
+ x, ev, obj, coef = x_new, ev_new, obj_new, coef_new
487
+ radius = min(radius * 1.5, 0.1)
488
+ else:
489
+ radius *= 0.5
490
+ return x.reshape(-1, 3)
491
+
492
+
493
+ # --- driver ------------------------------------------------------------------
494
+
495
+
496
+ def power_mean(q, p):
497
+ """Power mean of the scaled distances with exponent -p, and its
498
+ derivative with respect to q. p = inf gives the minimum."""
499
+ if q.size == 0:
500
+ return np.inf, np.zeros_like(q)
501
+ q = np.maximum(q, 1e-9)
502
+ m = q.min()
503
+ if not np.isfinite(p):
504
+ return m, None
505
+ r = m / q # in (0, 1]
506
+ a = np.mean(r ** p)
507
+ value = m * a ** (-1.0 / p)
508
+ grad = (a ** (-1.0 / p - 1.0)) * (r ** (p + 1.0)) / q.size
509
+ return value, grad
510
+
511
+
512
+ def refine_power(prob, x0, p, mus=(10.0, 100.0, 1000.0), maxiter=300):
513
+ """L-BFGS-B on the power mean, with penalties raised in turn until the
514
+ anchor, background and bound conditions hold."""
515
+ x = x0.ravel().copy()
516
+ for mu in mus:
517
+ def f(xf):
518
+ ev = prob.evaluate(xf.reshape(-1, 3))
519
+ val, gq = power_mean(ev.q, p)
520
+ pv, pg = _penalty(prob, ev, mu)
521
+ return -val + pv, (-_pair_grad(prob, ev, gq) + pg).ravel()
522
+
523
+ x = minimize(f, x, jac=True, method="L-BFGS-B", bounds=[(0, 1)] * x.size,
524
+ options=dict(maxiter=maxiter)).x
525
+ if prob.violation(prob.evaluate(x.reshape(-1, 3), with_jac=False)) < FEAS_TOL:
526
+ break
527
+ return x.reshape(-1, 3)
528
+
529
+
530
+ def solve_power(prob, p, starts=8, seed=0, grid=24):
531
+ """Maximise the power mean of the scaled distances (exponent -p)."""
532
+ cand, uc, cap = _feasible_candidates(prob, candidate_grid(grid))
533
+ rng = np.random.default_rng(seed)
534
+ swapped = swap_search(prob, uc, cap, farthest_point(prob, uc, cap))
535
+ inits = [("swap", cand[swapped])]
536
+ for k in range(starts - 1):
537
+ inits.append((f"random {k + 1}", cand[random_start(prob, cap, rng)]))
538
+ best = cand[swapped]
539
+ prob.set_sides(best)
540
+ best_side = prob.side.copy()
541
+ ev = prob.evaluate(best, False)
542
+ best_v = power_mean(ev.q, p)[0] if prob.violation(ev) < FEAS_TOL else -np.inf
543
+ log = dict(starts=[])
544
+ for name, x0 in inits:
545
+ prob.set_sides(x0)
546
+ x = refine_power(prob, x0, p)
547
+ ev = prob.evaluate(x, False)
548
+ v = power_mean(ev.q, p)[0] if prob.violation(ev) < FEAS_TOL else -np.inf
549
+ log["starts"].append(dict(start=name, value=v))
550
+ if v > best_v:
551
+ best, best_v, best_side = x, v, prob.side.copy()
552
+ prob.side = best_side
553
+ return best, log
554
+
555
+
556
+ def round_repair(prob, rgb, sweeps=100, p=np.inf):
557
+ """Round to 8-bit values, then move single colours by one step in each
558
+ channel while this reduces the violation or raises the least distance,
559
+ sweeping until a sweep brings no gain."""
560
+ x = np.round(np.clip(rgb, 0, 1) * 255)
561
+ steps = np.array([(a, b, c) for a in (-1, 0, 1) for b in (-1, 0, 1) for c in (-1, 0, 1)
562
+ if (a, b, c) != (0, 0, 0)])
563
+
564
+ def merit(xx):
565
+ ev = prob.evaluate(xx / 255, with_jac=False)
566
+ v = prob.violation(ev)
567
+ return (-v if v > FEAS_TOL else 0.0, power_mean(ev.q, p)[0])
568
+
569
+ cur = merit(x)
570
+ for _ in range(sweeps):
571
+ improved = False
572
+ for i in range(prob.n):
573
+ best_step, best_m = None, cur
574
+ for s in steps:
575
+ y = x.copy()
576
+ y[i] = np.clip(y[i] + s, 0, 255)
577
+ m = merit(y)
578
+ if m > best_m:
579
+ best_step, best_m = y, m
580
+ if best_step is not None:
581
+ x, cur = best_step, best_m
582
+ improved = True
583
+ if not improved:
584
+ break
585
+ if cur[0] < 0:
586
+ import warnings
587
+ warnings.warn(f"Rounding to 8-bit values left a violation of {-cur[0]:.3g} "
588
+ "(CAM16-UCS units).", stacklevel=3)
589
+ return x / 255
590
+
591
+
592
+ def solve(prob, starts=8, polish_top=3, seed=0, grid=24, do_spread=True):
593
+ """Return the best sRGB array (n, 3) found, and a log of the stages."""
594
+ cand, uc, cap = _feasible_candidates(prob, candidate_grid(grid))
595
+ if len(cand) < prob.n:
596
+ raise ValueError(f"Only {len(cand)} admissible candidates for {prob.n} colours; "
597
+ "use a finer grid or looser anchors.")
598
+ rng = np.random.default_rng(seed)
599
+ greedy = farthest_point(prob, uc, cap)
600
+ swapped = swap_search(prob, uc, cap, greedy)
601
+ inits = [("swap", cand[swapped])]
602
+ for k in range(starts - 1):
603
+ inits.append((f"random {k + 1}", cand[random_start(prob, cap, rng)]))
604
+ log = dict(greedy=prob.score(prob.evaluate(cand[greedy], False)),
605
+ swap=prob.score(prob.evaluate(cand[swapped], False)), starts=[])
606
+ refined = []
607
+ for name, x0 in inits:
608
+ prob.set_sides(x0)
609
+ x = refine_softmin(prob, x0)
610
+ ev = prob.evaluate(x, False)
611
+ refined.append((prob.score(ev) - 100 * prob.violation(ev), name, x, prob.side.copy()))
612
+ refined.sort(key=lambda r: -r[0])
613
+ # The swap-search start lies on grid points admissible for each colour's
614
+ # radius, so it is a feasible answer to fall back on.
615
+ x_swap = cand[swapped]
616
+ prob.set_sides(x_swap)
617
+ ev = prob.evaluate(x_swap, False)
618
+ best, best_side = x_swap, prob.side.copy()
619
+ best_s = prob.score(ev) if prob.violation(ev) < FEAS_TOL else -np.inf
620
+ for merit, name, x, side in refined[:polish_top]:
621
+ prob.side = side
622
+ x = polish_maxmin(prob, x)
623
+ ev = prob.evaluate(x, False)
624
+ s = prob.score(ev) if prob.violation(ev) < FEAS_TOL else -np.inf
625
+ log["starts"].append(dict(start=name, refined=merit, polished=s))
626
+ if s > best_s:
627
+ best, best_s, best_side = x, s, side
628
+ if not np.isfinite(best_s):
629
+ raise RuntimeError("No start satisfied the anchor and background conditions.")
630
+ prob.side = best_side
631
+ if do_spread and prob.n > 2:
632
+ best = spread(prob, best, best_s)
633
+ log["continuous_scale"] = float(prob.score(prob.evaluate(best, False)))
634
+ return best, log
635
+
636
+
637
+ # --- public interface --------------------------------------------------------
638
+
639
+
640
+ DEFAULT_BACKGROUND = "#ffffff"
641
+ FEAS_TOL = 1e-4 # CAM16-UCS units; far below the 8-bit quantisation step
642
+
643
+
644
+ def default_anchors(background=DEFAULT_BACKGROUND, text=None, background_clearance=20.0,
645
+ background_lightness=25.0, text_clearance=15.0):
646
+ """White (or given) background and a text colour of opposite lightness.
647
+
648
+ background_lightness=25 matches the lightest colour of matplotlib's tab10
649
+ on white (contrast ratio about 2:1). WCAG 2.1 asks 3:1 for graphical
650
+ objects, which corresponds to about 37 on white."""
651
+ background = to_hex(background)
652
+ if text is None:
653
+ text = "#000000" if relative_luminance(hex_to_rgb(background))[0] > 0.18 else "#ffffff"
654
+ return [Anchor(background, background_clearance, background_lightness),
655
+ Anchor(to_hex(text), text_clearance)]
656
+
657
+
658
+ @dataclass
659
+ class Palette:
660
+ hex: list
661
+ rgb: np.ndarray
662
+ min_distance: float
663
+ scale: float
664
+ diagnostics: dict
665
+
666
+ def __len__(self):
667
+ return len(self.hex)
668
+
669
+ def __iter__(self):
670
+ return iter(self.hex)
671
+
672
+
673
+ # Default simulated observers of the 'srgb' mode: deuteranopia and protanopia
674
+ # guaranteed 0.6 of the common spacing, tritanopia 0.2. At N = 10 this keeps
675
+ # about 0.88 of the normal-vision spacing.
676
+ SRGB_OBSERVERS = (Observer("deutan", 1.0, 0.6), Observer("protan", 1.0, 0.6),
677
+ Observer("tritan", 1.0, 0.2))
678
+ # Clearances of the 'srgb' mode's default anchors: background, then text.
679
+ SRGB_CLEARANCE = (20.0, 15.0)
680
+
681
+
682
+ def make_problem(n, background=DEFAULT_BACKGROUND, anchors=None, radii=None, observers=None,
683
+ preset="screen", fixed=(), fixed_radii=None, ucs="UCS", lightness_weight=None,
684
+ mode=None, text=None, replace_anchors=False):
685
+ if n < 0:
686
+ raise ValueError("n must be non-negative")
687
+ background = to_hex(background)
688
+ if text is None:
689
+ text = "#000000" if relative_luminance(hex_to_rgb(background))[0] > 0.18 else "#ffffff"
690
+ text = to_hex(text)
691
+ bounds = None
692
+ if mode == "srgb":
693
+ # Calibrated mode: lightness weighted, and lightness bounds by hue in
694
+ # place of the single background lightness condition.
695
+ lightness_weight = 0.77 if lightness_weight is None else lightness_weight
696
+ bounds = "srgb"
697
+ defaults = [Anchor(background, SRGB_CLEARANCE[0]), Anchor(text, SRGB_CLEARANCE[1])]
698
+ if observers is None:
699
+ observers = SRGB_OBSERVERS
700
+ elif mode == "image":
701
+ # Colours for an image: calibrated floor and ceiling by hue, no
702
+ # background margin and no anchors. The background sets only the
703
+ # viewing conditions; a mid grey suits most images.
704
+ lightness_weight = 0.77 if lightness_weight is None else lightness_weight
705
+ bounds = "image"
706
+ defaults = []
707
+ if observers is None:
708
+ observers = SRGB_OBSERVERS
709
+ elif mode is not None:
710
+ raise ValueError(f"Unknown mode {mode!r}")
711
+ else:
712
+ defaults = default_anchors(background, text)
713
+ if anchors is None:
714
+ anchors = defaults
715
+ elif not replace_anchors:
716
+ anchors = defaults + list(anchors)
717
+ observers = () if observers is None else observers
718
+ view = viewing(preset, background, ucs=ucs, lightness_weight=lightness_weight)
719
+ obs = (Observer(),) + tuple(Observer(*o) if isinstance(o, tuple) else o for o in observers)
720
+ space = Space(view, obs)
721
+ anchors = [Anchor(to_hex(a.colour), a.clearance, a.lightness) for a in anchors]
722
+ for a in anchors:
723
+ if a.clearance < 0 or (a.lightness is not None and a.lightness < 0):
724
+ raise ValueError("Anchor clearances must be non-negative.")
725
+ radii = np.ones(n) if radii is None else np.asarray(radii, float)
726
+ if radii.shape != (n,) or np.any(radii <= 0):
727
+ raise ValueError("radii must be n positive numbers.")
728
+ fixed = [to_hex(c) for c in fixed]
729
+ fixed_rgb = hex_to_rgb(fixed) if fixed else np.zeros((0, 3))
730
+ fixed_radii = (np.ones(len(fixed)) if fixed_radii is None
731
+ else np.asarray(fixed_radii, float))
732
+ if fixed_radii.shape != (len(fixed),) or np.any(fixed_radii <= 0):
733
+ raise ValueError("fixed_radii must be positive, one per fixed colour.")
734
+ if bounds == "srgb":
735
+ from ..bounds import bounds_for
736
+ j_bg = float(space.ucs(hex_to_rgb(background))[0, 0]) * space.ucs.K_L
737
+ bounds = bounds_for(background, j_bg)
738
+ if "interpolated" in bounds.source and 25 < _lstar(background) < 90:
739
+ import warnings
740
+ warnings.warn(f"The lightness limits for background {background} are "
741
+ "interpolated between calibrated backgrounds and have not been "
742
+ "checked by eye; see docs/calibration.md.", stacklevel=3)
743
+ if bounds == "image":
744
+ from ..bounds import image_bounds
745
+ bounds = image_bounds(viewing(preset, background))
746
+ return Problem(n, space, anchors, radii, fixed_rgb, fixed_radii, bounds)
747
+
748
+
749
+ def palette(n, background=DEFAULT_BACKGROUND, anchors=None, radii=None, observers=None,
750
+ preset="screen", fixed=(), fixed_radii=None, starts=8, seed=0, grid=24,
751
+ order=None, ucs="UCS", lightness_weight=None, mode="auto", power=np.inf,
752
+ use_cache=True, text=None, replace_anchors=False):
753
+ """Choose n colours. The formulation is given in docs/design.md.
754
+
755
+ anchors are added to the default anchors (the background with clearance
756
+ 20, and the text colour with clearance 15); with replace_anchors=True
757
+ they replace them. text is the colour of text and axes (default black on
758
+ light backgrounds, white on dark ones).
759
+
760
+ mode: 'srgb' (calibrated lightness bounds by hue, lightness weighted,
761
+ deutan and protan guaranteed 0.6 of the spacing and tritan 0.2),
762
+ 'image' (for colour maps of images: the calibrated floor and ceiling by
763
+ hue, no anchors, and the observers of 'srgb'), 'standard' (single
764
+ background lightness condition, normal vision only unless observers are
765
+ given), or 'auto' (the default, currently 'srgb').
766
+ The hue bounds of 'srgb' are calibrated on white, black and #333333 and
767
+ interpolated in background L* elsewhere; diagnostics['bounds'] says which.
768
+
769
+ Colours are returned as 8-bit sRGB, and all diagnostics refer to the
770
+ colours as returned."""
771
+ if mode == "auto":
772
+ mode = "srgb"
773
+ if np.isfinite(power) or ucs != "UCS":
774
+ import warnings
775
+ warnings.warn("power= and ucs= are experimental options.", stacklevel=2)
776
+ if use_cache:
777
+ cached = (None if text is not None or replace_anchors else
778
+ _from_cache(n, background, anchors, radii, observers, preset, fixed,
779
+ fixed_radii, starts, seed, grid, ucs, lightness_weight, mode,
780
+ power))
781
+ if cached is not None:
782
+ prob = make_problem(n, background, None, None, None, preset, (), None, ucs,
783
+ lightness_weight, mode)
784
+ rgb = hex_to_rgb(cached)
785
+ if order is not None:
786
+ from .order import order_indices
787
+ rgb = rgb[order_indices(rgb, prob.space, order)]
788
+ prob.set_sides(rgb)
789
+ diag = diagnose(prob, rgb)
790
+ diag["log"] = {"source": "precomputed"}
791
+ return Palette(rgb_to_hex(rgb), rgb, diag["min_distance"], diag["scale"], diag)
792
+ prob = make_problem(n, background, anchors, radii, observers, preset, fixed, fixed_radii,
793
+ ucs, lightness_weight, None if mode == "standard" else mode, text,
794
+ replace_anchors)
795
+ if n == 0:
796
+ return Palette([], np.zeros((0, 3)), np.inf, np.inf, {})
797
+ if order is not None and np.ptp(prob.radii) > 0:
798
+ raise ValueError("order= would separate colours from their radii; "
799
+ "when radii differ, the series must be put in order before the call.")
800
+ if n == 1 and not len(prob.fixed_rgb):
801
+ cand, uc, cap = _feasible_candidates(prob, candidate_grid(grid))
802
+ rgb, log = cand[farthest_point(prob, uc, cap)], {}
803
+ prob.set_sides(rgb)
804
+ elif np.isfinite(power):
805
+ rgb, log = solve_power(prob, power, starts=starts, seed=seed, grid=grid)
806
+ else:
807
+ rgb, log = solve(prob, starts=starts, seed=seed, grid=grid)
808
+ rgb = round_repair(prob, rgb, p=power)
809
+ if order is not None:
810
+ from .order import order_indices
811
+ rgb = rgb[order_indices(rgb, prob.space, order)]
812
+ prob.set_sides(rgb)
813
+ diag = diagnose(prob, rgb)
814
+ diag["log"] = log
815
+ return Palette(rgb_to_hex(rgb), rgb, diag["min_distance"], diag["scale"], diag)
816
+
817
+
818
+ def diagnose(prob, rgb):
819
+ ev = prob.evaluate(rgb, with_jac=False)
820
+ out = {}
821
+ if ev.q.size:
822
+ s = ev.q.min()
823
+ out["scale"] = float(s)
824
+ # Least distance for normal vision; by observer below.
825
+ out["min_distance"] = float(ev.dist[0].min())
826
+ out["min_distance_by_observer"] = {str(o): float(v) for o, v in
827
+ zip(prob.space.observers, ev.dist.min(axis=1))}
828
+ bind = np.argwhere(ev.q <= s * (1 + 1e-3))
829
+ out["binding_pairs"] = [(int(prob.pi[p]), int(prob.pj[p]), str(prob.space.observers[o]))
830
+ for o, p in bind]
831
+ out["scale_by_observer"] = {str(o): float(v)
832
+ for o, v in zip(prob.space.observers, ev.q.min(axis=1))}
833
+ else:
834
+ out["scale"] = out["min_distance"] = float("inf")
835
+ if ev.aslack.size:
836
+ out["anchor_distance"] = {a.colour: ev.adist[0, :, m].round(2).tolist()
837
+ for m, a in enumerate(prob.anchors)}
838
+ if prob.bg_index is not None:
839
+ jb = prob.anchor_coords[0, prob.bg_index, 0]
840
+ k_l = prob.space.ucs.K_L
841
+ out["background_lightness_difference"] = (k_l * np.abs(ev.u[0, :, 0] - jb)).round(2).tolist()
842
+ if prob.bounds is not None:
843
+ out["bounds"] = prob.bounds.source
844
+ if ev.bslack is not None:
845
+ out["lightness_bound_slack"] = ev.bslack.min(axis=0).round(2).tolist()
846
+ out["max_violation"] = float(prob.violation(ev))
847
+ return out
848
+
849
+
850
+ # --- precomputed palettes ------------------------------------------------------
851
+
852
+ _CACHE = None
853
+
854
+
855
+ def cache_settings():
856
+ """The default arguments that precomputed palettes assume."""
857
+ return dict(mode="srgb", preset="screen", starts=8, seed=0, grid=24, ucs="UCS",
858
+ lightness_weight=None, power="inf")
859
+
860
+
861
+ # Raise when a change to the optimiser alters the palettes it produces.
862
+ ALGORITHM_REVISION = 2
863
+
864
+
865
+ def cache_fingerprint():
866
+ """Hash of everything that determines a precomputed palette."""
867
+ import dataclasses
868
+ import hashlib
869
+ import json
870
+ from ..bounds import SRGB_BOUNDS
871
+ from ..space import PRESETS
872
+ payload = dict(revision=ALGORITHM_REVISION, settings=cache_settings(),
873
+ bounds={k: dataclasses.asdict(v) for k, v in sorted(SRGB_BOUNDS.items())},
874
+ observers=[dataclasses.asdict(o) for o in SRGB_OBSERVERS],
875
+ clearance=SRGB_CLEARANCE, preset=PRESETS["screen"], feas_tol=FEAS_TOL)
876
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:16]
877
+
878
+
879
+ def _load_cache():
880
+ global _CACHE
881
+ if _CACHE is None:
882
+ import json
883
+ import os
884
+ import warnings
885
+ path = os.path.join(os.path.dirname(__file__), "data", "palettes.json")
886
+ _CACHE = {}
887
+ try:
888
+ with open(path) as f:
889
+ data = json.load(f)
890
+ except FileNotFoundError:
891
+ return _CACHE
892
+ except (OSError, ValueError) as exc:
893
+ warnings.warn(f"Precomputed palettes could not be read ({exc}); "
894
+ "palettes will be computed.", stacklevel=3)
895
+ return _CACHE
896
+ if data.get("fingerprint") != cache_fingerprint():
897
+ warnings.warn("Precomputed palettes are out of date and will not be used; "
898
+ "palettes will be computed.", stacklevel=3)
899
+ return _CACHE
900
+ _CACHE = data
901
+ return _CACHE
902
+
903
+
904
+ def _from_cache(n, background, anchors, radii, observers, preset, fixed, fixed_radii, starts,
905
+ seed, grid, ucs, lightness_weight, mode, power):
906
+ """Hex colours of a precomputed palette, or None if the arguments are not
907
+ all at the defaults for which palettes were precomputed."""
908
+ if (anchors is not None or radii is not None or observers is not None or fixed
909
+ or fixed_radii is not None or preset != "screen" or starts != 8 or seed != 0
910
+ or grid != 24 or ucs != "UCS" or lightness_weight is not None or mode != "srgb"
911
+ or np.isfinite(power)):
912
+ return None
913
+ entry = _load_cache().get("palettes", {}).get(to_hex(background), {}).get(str(n))
914
+ return entry["hex"] if entry else None