colorcat 0.1.0__tar.gz
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.
- colorcat-0.1.0/LICENSE +21 -0
- colorcat-0.1.0/PKG-INFO +158 -0
- colorcat-0.1.0/README.md +135 -0
- colorcat-0.1.0/pyproject.toml +71 -0
- colorcat-0.1.0/pyproject.toml.orig +58 -0
- colorcat-0.1.0/src/colorcat/__init__.py +5 -0
- colorcat-0.1.0/src/colorcat/__main__.py +5 -0
- colorcat-0.1.0/src/colorcat/_constraints.py +125 -0
- colorcat-0.1.0/src/colorcat/_cvd.py +96 -0
- colorcat-0.1.0/src/colorcat/_distance.py +81 -0
- colorcat-0.1.0/src/colorcat/_energy.py +233 -0
- colorcat-0.1.0/src/colorcat/_feasible.py +126 -0
- colorcat-0.1.0/src/colorcat/_format.py +90 -0
- colorcat-0.1.0/src/colorcat/_oklab.py +137 -0
- colorcat-0.1.0/src/colorcat/cli.py +58 -0
- colorcat-0.1.0/src/colorcat/palette.py +143 -0
- colorcat-0.1.0/src/colorcat/py.typed +0 -0
colorcat-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Devin McCabe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
colorcat-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: colorcat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Generate maximally distinct colors for categorical data palettes.
|
|
5
|
+
Keywords: color,palette,categorical,visualization,oklab,colorblind
|
|
6
|
+
Author: Devin McCabe
|
|
7
|
+
Author-email: Devin McCabe <dmccabe@broadinstitute.org>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Dist: numpy>=1.26
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Project-URL: Homepage, https://github.com/dpmccabe/colorcat
|
|
20
|
+
Project-URL: Source, https://github.com/dpmccabe/colorcat
|
|
21
|
+
Project-URL: Changelog, https://github.com/dpmccabe/colorcat/blob/main/CHANGELOG.md
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# colorcat
|
|
25
|
+
|
|
26
|
+
Generate **maximally distinct colors** for categorical data palettes (chart series,
|
|
27
|
+
legend entries, cluster labels).
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
>>> from colorcat import palette
|
|
31
|
+
>>> palette(5)
|
|
32
|
+
['#d001ff', '#00ad01', '#680000', '#0000ce', '#ff4100']
|
|
33
|
+
>>> palette(8, background="black")
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+

|
|
37
|
+
|
|
38
|
+
- Colors are chosen to maximize the smallest perceptual distance between any two of
|
|
39
|
+
them **and** between each of them and the background **and its opposite** (black on white,
|
|
40
|
+
white on black), so nothing blends into plot lines or text.
|
|
41
|
+
- Deterministic: the same arguments and `seed` always give the same palette.
|
|
42
|
+
- NumPy is the only dependency. Python 3.12+.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
uv add colorcat # once published; from a checkout: uv sync
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from colorcat import palette, min_distance
|
|
54
|
+
|
|
55
|
+
palette(6) # on a white background (the default)
|
|
56
|
+
palette(6, background="black") # lighter colors for dark backgrounds
|
|
57
|
+
palette(6, min_contrast=4.5) # WCAG AA contrast with the background
|
|
58
|
+
palette(4, fixed=["#e41a1c", "#377eb8"]) # 4 NEW colors that extend two you already use
|
|
59
|
+
palette(4, exclude=["#00aa00"]) # keep clear of a color used elsewhere
|
|
60
|
+
palette(6, cvd=["deutan", "protan"]) # also distinct for red-green color blindness
|
|
61
|
+
palette(6, color_format="rgb") # (r, g, b) tuples; also "oklab" and "oklch"
|
|
62
|
+
palette(6, seed=3) # a different, similarly good palette
|
|
63
|
+
|
|
64
|
+
min_distance(palette(6)) # distance between the closest pair
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### `palette(n, *, background, min_contrast, restart_count, exclude, fixed, cvd, color_format, seed)`
|
|
68
|
+
|
|
69
|
+
| Argument | Default | Meaning |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `n` | | Number of colors, `>= 0`. |
|
|
72
|
+
| `background` | `"white"` | `"white"` or `"black"`, the color the palette is drawn on. Other values raise `ValueError`. |
|
|
73
|
+
| `min_contrast` | `3` | Minimum [WCAG contrast ratio](https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio) (1 to 15) between every color and the background. 3 is the WCAG minimum for graphical objects such as chart marks; use 4.5 for text. Higher values leave fewer colors to choose from, so the closest-pair distance drops. |
|
|
74
|
+
| `restart_count` | `4` | Independent optimizer runs (each followed by 16 basin-hopping moves); the best is kept. More is never worse, just slower (roughly 1-3.5 s for 4 at `n` up to 30). |
|
|
75
|
+
| `exclude` | `()` | Hex colors the new colors must stay distinct from. Not returned. |
|
|
76
|
+
| `fixed` | `()` | Hex colors already in use; the `n` new colors extend them. Never moved or returned, and exempt from the built-in ranges. |
|
|
77
|
+
| `cvd` | `()` | One or more of `"protan"`, `"deutan"`, `"tritan"` (or a single name). Every pair must then be distinct to normal vision *and* as seen with each deficiency (full dichromacy, Machado et al. 2009 simulation). The closest-pair distance drops as views are added, more so for larger `n`. |
|
|
78
|
+
| `color_format` | `"hex"` | `"hex"` (`"#rrggbb"`), `"rgb"` (0-255 ints), `"oklab"` (L, a, b) or `"oklch"` (L, C, h in degrees). |
|
|
79
|
+
| `seed` | `0` | Seed for the random starting points; `None` uses fresh entropy. |
|
|
80
|
+
|
|
81
|
+
Colors come back ordered so that the first is the most distant from the background and its
|
|
82
|
+
opposite, and each next one is the farthest from those before it. Each `n` is optimized separately, so
|
|
83
|
+
`palette(4)` is **not** the first four colors of `palette(5)`.
|
|
84
|
+
|
|
85
|
+
`palette` warns (it does not fail) if the closest pair differs by less than ΔE_OK 0.03,
|
|
86
|
+
which happens only for very large `n`.
|
|
87
|
+
|
|
88
|
+
### `min_distance(colors, *, cvd=())`
|
|
89
|
+
|
|
90
|
+
ΔE_OK between the two closest colors of a list of hex strings (`inf` for fewer than two).
|
|
91
|
+
With `cvd`, the closest pair over normal vision and each listed deficiency.
|
|
92
|
+
|
|
93
|
+
### Command line
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
colorcat 8 --background black
|
|
97
|
+
colorcat 4 --fixed '#e41a1c' '#377eb8' --format rgb
|
|
98
|
+
python -m colorcat 6 --seed 3
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## How it works
|
|
102
|
+
|
|
103
|
+
- **Color space:** [OKLab](https://bottosson.github.io/posts/oklab/), where Euclidean
|
|
104
|
+
distance (ΔE_OK) approximates perceived difference. The conversions are implemented
|
|
105
|
+
directly in NumPy.
|
|
106
|
+
- **Constraints:** every color must have at least `min_contrast` WCAG contrast with the
|
|
107
|
+
background, `(Y_light + 0.05) / (Y_dark + 0.05)` on relative luminance `Y`. This is a
|
|
108
|
+
one-sided bound on `Y` (on white, `Y <= 0.30` at the default 3:1). Chroma and hue have
|
|
109
|
+
no bounds of their own; the sRGB gamut is the only other limit. The opposite of the
|
|
110
|
+
background (black on white, white on black: where lines and text are drawn) is not a
|
|
111
|
+
constraint but a fixed point the colors are repelled from, like the background itself.
|
|
112
|
+
- **Optimization:** colors are particles repelled from each other and from fixed anchors
|
|
113
|
+
(the background, its opposite, `fixed` and `exclude`) by the Riesz energy
|
|
114
|
+
`E_p = (1/p) log Σ d_ij^-p`, which tends to the max-min distance as `p` grows.
|
|
115
|
+
Projected gradient descent with a `p` schedule of 4, 8, 16, 32 minimizes it,
|
|
116
|
+
restricted to the feasible region. The landscape has local optima, so it is restarted
|
|
117
|
+
from `restart_count` random starts (each with its own child of `SeedSequence(seed)`).
|
|
118
|
+
After its first descent, each restart does 16 basin-hopping moves: re-seed one of the
|
|
119
|
+
colors in the closest pair at the roomiest spot, re-descend (`p` = 16, 32), and keep the
|
|
120
|
+
result only if the closest-pair distance improved.
|
|
121
|
+
- **Quantization:** the best restart is chosen after snapping to 8-bit sRGB, so the
|
|
122
|
+
reported distances are those of the colors you actually get.
|
|
123
|
+
|
|
124
|
+
### Quality
|
|
125
|
+
|
|
126
|
+
`benchmarks/benchmark.py` compares `palette` with random feasible colors, greedy
|
|
127
|
+
farthest-point sampling and Okabe-Ito / Tableau 10 / Set1. On white, the smallest
|
|
128
|
+
pairwise ΔE_OK (including the background and its opposite) is:
|
|
129
|
+
|
|
130
|
+
| n | colorcat | farthest-point | random | best named palette |
|
|
131
|
+
|---|---|---|---|---|
|
|
132
|
+
| 5 | 0.33 | 0.31 | 0.07 | 0.17 |
|
|
133
|
+
| 10 | 0.22 | 0.19 | 0.04 | 0.08 |
|
|
134
|
+
| 20 | 0.17 | 0.13 | 0.02 | |
|
|
135
|
+
| 30 | 0.14 | 0.11 | 0.02 | |
|
|
136
|
+
|
|
137
|
+
Results vary by about 5% across seeds at small `n`.
|
|
138
|
+
|
|
139
|
+
## Not in v1
|
|
140
|
+
|
|
141
|
+
Planned for later: user-set lightness, chroma and hue ranges; arbitrary backgrounds
|
|
142
|
+
(the "opposite" color repelled alongside the background would need defining);
|
|
143
|
+
partial-severity CVD (`cvd=` simulates full dichromacy); and alternative methods (farthest-point,
|
|
144
|
+
which gives prefix-stable palettes).
|
|
145
|
+
|
|
146
|
+
## Development
|
|
147
|
+
|
|
148
|
+
```sh
|
|
149
|
+
uv sync
|
|
150
|
+
uv run pytest # ~30 s
|
|
151
|
+
uv run python benchmarks/benchmark.py # quality vs. baselines
|
|
152
|
+
uv run python benchmarks/make_gallery.py # regenerate docs/gallery.svg
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Layout: `_oklab.py` (conversions), `_distance.py` (the single distance definition),
|
|
156
|
+
`_constraints.py` (built-in ranges), `_feasible.py` (gamut and projection),
|
|
157
|
+
`_energy.py` (optimizer), `_format.py` (parsing, quantization, formats),
|
|
158
|
+
`palette.py` (public API), `cli.py`. See [`plan.md`](https://github.com/dpmccabe/colorcat/blob/main/plan.md) for the design.
|
colorcat-0.1.0/README.md
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# colorcat
|
|
2
|
+
|
|
3
|
+
Generate **maximally distinct colors** for categorical data palettes (chart series,
|
|
4
|
+
legend entries, cluster labels).
|
|
5
|
+
|
|
6
|
+
```python
|
|
7
|
+
>>> from colorcat import palette
|
|
8
|
+
>>> palette(5)
|
|
9
|
+
['#d001ff', '#00ad01', '#680000', '#0000ce', '#ff4100']
|
|
10
|
+
>>> palette(8, background="black")
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
- Colors are chosen to maximize the smallest perceptual distance between any two of
|
|
16
|
+
them **and** between each of them and the background **and its opposite** (black on white,
|
|
17
|
+
white on black), so nothing blends into plot lines or text.
|
|
18
|
+
- Deterministic: the same arguments and `seed` always give the same palette.
|
|
19
|
+
- NumPy is the only dependency. Python 3.12+.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
uv add colorcat # once published; from a checkout: uv sync
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from colorcat import palette, min_distance
|
|
31
|
+
|
|
32
|
+
palette(6) # on a white background (the default)
|
|
33
|
+
palette(6, background="black") # lighter colors for dark backgrounds
|
|
34
|
+
palette(6, min_contrast=4.5) # WCAG AA contrast with the background
|
|
35
|
+
palette(4, fixed=["#e41a1c", "#377eb8"]) # 4 NEW colors that extend two you already use
|
|
36
|
+
palette(4, exclude=["#00aa00"]) # keep clear of a color used elsewhere
|
|
37
|
+
palette(6, cvd=["deutan", "protan"]) # also distinct for red-green color blindness
|
|
38
|
+
palette(6, color_format="rgb") # (r, g, b) tuples; also "oklab" and "oklch"
|
|
39
|
+
palette(6, seed=3) # a different, similarly good palette
|
|
40
|
+
|
|
41
|
+
min_distance(palette(6)) # distance between the closest pair
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### `palette(n, *, background, min_contrast, restart_count, exclude, fixed, cvd, color_format, seed)`
|
|
45
|
+
|
|
46
|
+
| Argument | Default | Meaning |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| `n` | | Number of colors, `>= 0`. |
|
|
49
|
+
| `background` | `"white"` | `"white"` or `"black"`, the color the palette is drawn on. Other values raise `ValueError`. |
|
|
50
|
+
| `min_contrast` | `3` | Minimum [WCAG contrast ratio](https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio) (1 to 15) between every color and the background. 3 is the WCAG minimum for graphical objects such as chart marks; use 4.5 for text. Higher values leave fewer colors to choose from, so the closest-pair distance drops. |
|
|
51
|
+
| `restart_count` | `4` | Independent optimizer runs (each followed by 16 basin-hopping moves); the best is kept. More is never worse, just slower (roughly 1-3.5 s for 4 at `n` up to 30). |
|
|
52
|
+
| `exclude` | `()` | Hex colors the new colors must stay distinct from. Not returned. |
|
|
53
|
+
| `fixed` | `()` | Hex colors already in use; the `n` new colors extend them. Never moved or returned, and exempt from the built-in ranges. |
|
|
54
|
+
| `cvd` | `()` | One or more of `"protan"`, `"deutan"`, `"tritan"` (or a single name). Every pair must then be distinct to normal vision *and* as seen with each deficiency (full dichromacy, Machado et al. 2009 simulation). The closest-pair distance drops as views are added, more so for larger `n`. |
|
|
55
|
+
| `color_format` | `"hex"` | `"hex"` (`"#rrggbb"`), `"rgb"` (0-255 ints), `"oklab"` (L, a, b) or `"oklch"` (L, C, h in degrees). |
|
|
56
|
+
| `seed` | `0` | Seed for the random starting points; `None` uses fresh entropy. |
|
|
57
|
+
|
|
58
|
+
Colors come back ordered so that the first is the most distant from the background and its
|
|
59
|
+
opposite, and each next one is the farthest from those before it. Each `n` is optimized separately, so
|
|
60
|
+
`palette(4)` is **not** the first four colors of `palette(5)`.
|
|
61
|
+
|
|
62
|
+
`palette` warns (it does not fail) if the closest pair differs by less than ΔE_OK 0.03,
|
|
63
|
+
which happens only for very large `n`.
|
|
64
|
+
|
|
65
|
+
### `min_distance(colors, *, cvd=())`
|
|
66
|
+
|
|
67
|
+
ΔE_OK between the two closest colors of a list of hex strings (`inf` for fewer than two).
|
|
68
|
+
With `cvd`, the closest pair over normal vision and each listed deficiency.
|
|
69
|
+
|
|
70
|
+
### Command line
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
colorcat 8 --background black
|
|
74
|
+
colorcat 4 --fixed '#e41a1c' '#377eb8' --format rgb
|
|
75
|
+
python -m colorcat 6 --seed 3
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## How it works
|
|
79
|
+
|
|
80
|
+
- **Color space:** [OKLab](https://bottosson.github.io/posts/oklab/), where Euclidean
|
|
81
|
+
distance (ΔE_OK) approximates perceived difference. The conversions are implemented
|
|
82
|
+
directly in NumPy.
|
|
83
|
+
- **Constraints:** every color must have at least `min_contrast` WCAG contrast with the
|
|
84
|
+
background, `(Y_light + 0.05) / (Y_dark + 0.05)` on relative luminance `Y`. This is a
|
|
85
|
+
one-sided bound on `Y` (on white, `Y <= 0.30` at the default 3:1). Chroma and hue have
|
|
86
|
+
no bounds of their own; the sRGB gamut is the only other limit. The opposite of the
|
|
87
|
+
background (black on white, white on black: where lines and text are drawn) is not a
|
|
88
|
+
constraint but a fixed point the colors are repelled from, like the background itself.
|
|
89
|
+
- **Optimization:** colors are particles repelled from each other and from fixed anchors
|
|
90
|
+
(the background, its opposite, `fixed` and `exclude`) by the Riesz energy
|
|
91
|
+
`E_p = (1/p) log Σ d_ij^-p`, which tends to the max-min distance as `p` grows.
|
|
92
|
+
Projected gradient descent with a `p` schedule of 4, 8, 16, 32 minimizes it,
|
|
93
|
+
restricted to the feasible region. The landscape has local optima, so it is restarted
|
|
94
|
+
from `restart_count` random starts (each with its own child of `SeedSequence(seed)`).
|
|
95
|
+
After its first descent, each restart does 16 basin-hopping moves: re-seed one of the
|
|
96
|
+
colors in the closest pair at the roomiest spot, re-descend (`p` = 16, 32), and keep the
|
|
97
|
+
result only if the closest-pair distance improved.
|
|
98
|
+
- **Quantization:** the best restart is chosen after snapping to 8-bit sRGB, so the
|
|
99
|
+
reported distances are those of the colors you actually get.
|
|
100
|
+
|
|
101
|
+
### Quality
|
|
102
|
+
|
|
103
|
+
`benchmarks/benchmark.py` compares `palette` with random feasible colors, greedy
|
|
104
|
+
farthest-point sampling and Okabe-Ito / Tableau 10 / Set1. On white, the smallest
|
|
105
|
+
pairwise ΔE_OK (including the background and its opposite) is:
|
|
106
|
+
|
|
107
|
+
| n | colorcat | farthest-point | random | best named palette |
|
|
108
|
+
|---|---|---|---|---|
|
|
109
|
+
| 5 | 0.33 | 0.31 | 0.07 | 0.17 |
|
|
110
|
+
| 10 | 0.22 | 0.19 | 0.04 | 0.08 |
|
|
111
|
+
| 20 | 0.17 | 0.13 | 0.02 | |
|
|
112
|
+
| 30 | 0.14 | 0.11 | 0.02 | |
|
|
113
|
+
|
|
114
|
+
Results vary by about 5% across seeds at small `n`.
|
|
115
|
+
|
|
116
|
+
## Not in v1
|
|
117
|
+
|
|
118
|
+
Planned for later: user-set lightness, chroma and hue ranges; arbitrary backgrounds
|
|
119
|
+
(the "opposite" color repelled alongside the background would need defining);
|
|
120
|
+
partial-severity CVD (`cvd=` simulates full dichromacy); and alternative methods (farthest-point,
|
|
121
|
+
which gives prefix-stable palettes).
|
|
122
|
+
|
|
123
|
+
## Development
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
uv sync
|
|
127
|
+
uv run pytest # ~30 s
|
|
128
|
+
uv run python benchmarks/benchmark.py # quality vs. baselines
|
|
129
|
+
uv run python benchmarks/make_gallery.py # regenerate docs/gallery.svg
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Layout: `_oklab.py` (conversions), `_distance.py` (the single distance definition),
|
|
133
|
+
`_constraints.py` (built-in ranges), `_feasible.py` (gamut and projection),
|
|
134
|
+
`_energy.py` (optimizer), `_format.py` (parsing, quantization, formats),
|
|
135
|
+
`palette.py` (public API), `cli.py`. See [`plan.md`](https://github.com/dpmccabe/colorcat/blob/main/plan.md) for the design.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "colorcat"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Generate maximally distinct colors for categorical data palettes."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = [
|
|
9
|
+
"color",
|
|
10
|
+
"palette",
|
|
11
|
+
"categorical",
|
|
12
|
+
"visualization",
|
|
13
|
+
"oklab",
|
|
14
|
+
"colorblind",
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Topic :: Scientific/Engineering :: Visualization",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
requires-python = ">=3.12"
|
|
26
|
+
dependencies = ["numpy>=1.26"]
|
|
27
|
+
|
|
28
|
+
[[project.authors]]
|
|
29
|
+
name = "Devin McCabe"
|
|
30
|
+
email = "dmccabe@broadinstitute.org"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/dpmccabe/colorcat"
|
|
34
|
+
Source = "https://github.com/dpmccabe/colorcat"
|
|
35
|
+
Changelog = "https://github.com/dpmccabe/colorcat/blob/main/CHANGELOG.md"
|
|
36
|
+
|
|
37
|
+
[project.scripts]
|
|
38
|
+
colorcat = "colorcat.cli:main"
|
|
39
|
+
|
|
40
|
+
[build-system]
|
|
41
|
+
requires = ["uv_build>=0.12.7,<0.13.0"]
|
|
42
|
+
build-backend = "uv_build"
|
|
43
|
+
|
|
44
|
+
[dependency-groups]
|
|
45
|
+
dev = [
|
|
46
|
+
"pyrefly>=1.4.1",
|
|
47
|
+
"pytest>=9.2.0",
|
|
48
|
+
"ruff>=0.17.4",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.pyrefly]
|
|
52
|
+
project-includes = [
|
|
53
|
+
"src",
|
|
54
|
+
"tests",
|
|
55
|
+
"benchmarks",
|
|
56
|
+
]
|
|
57
|
+
search-path = [
|
|
58
|
+
"src",
|
|
59
|
+
"benchmarks",
|
|
60
|
+
]
|
|
61
|
+
python-version = "3.12"
|
|
62
|
+
|
|
63
|
+
[tool.ruff]
|
|
64
|
+
target-version = "py312"
|
|
65
|
+
line-length = 100
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
extend-select = ["I"]
|
|
69
|
+
|
|
70
|
+
[tool.ruff.lint.isort]
|
|
71
|
+
known-first-party = ["colorcat"]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "colorcat"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Generate maximally distinct colors for categorical data palettes."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = ["color", "palette", "categorical", "visualization", "oklab", "colorblind"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Intended Audience :: Science/Research",
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Programming Language :: Python :: 3.12",
|
|
14
|
+
"Programming Language :: Python :: 3.13",
|
|
15
|
+
"Topic :: Scientific/Engineering :: Visualization",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
authors = [
|
|
19
|
+
{ name = "Devin McCabe", email = "dmccabe@broadinstitute.org" }
|
|
20
|
+
]
|
|
21
|
+
requires-python = ">=3.12"
|
|
22
|
+
dependencies = [
|
|
23
|
+
"numpy>=1.26",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/dpmccabe/colorcat"
|
|
28
|
+
Source = "https://github.com/dpmccabe/colorcat"
|
|
29
|
+
Changelog = "https://github.com/dpmccabe/colorcat/blob/main/CHANGELOG.md"
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
colorcat = "colorcat.cli:main"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["uv_build>=0.12.7,<0.13.0"]
|
|
36
|
+
build-backend = "uv_build"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"pyrefly>=1.4.1",
|
|
41
|
+
"pytest>=9.2.0",
|
|
42
|
+
"ruff>=0.17.4",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[tool.pyrefly]
|
|
46
|
+
project-includes = ["src", "tests", "benchmarks"]
|
|
47
|
+
search-path = ["src", "benchmarks"]
|
|
48
|
+
python-version = "3.12"
|
|
49
|
+
|
|
50
|
+
[tool.ruff]
|
|
51
|
+
target-version = "py312"
|
|
52
|
+
line-length = 100
|
|
53
|
+
|
|
54
|
+
[tool.ruff.lint]
|
|
55
|
+
extend-select = ["I"]
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint.isort]
|
|
58
|
+
known-first-party = ["colorcat"]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Built-in color constraints for each supported background.
|
|
2
|
+
|
|
3
|
+
v1 supports exactly two backgrounds, ``"white"`` and ``"black"``. A color is
|
|
4
|
+
allowed when it has at least ``min_contrast`` WCAG contrast against the
|
|
5
|
+
background (``(Y_light + 0.05) / (Y_dark + 0.05)`` on relative luminance ``Y``),
|
|
6
|
+
which is a one-sided bound on ``Y``: colors must be darker than the background
|
|
7
|
+
or lighter than it. Chroma and hue have no bounds: the sRGB gamut is the only
|
|
8
|
+
limit. The opposite of the background (where lines and text are drawn) is
|
|
9
|
+
handled by the optimizer as a repelling anchor, not as a constraint.
|
|
10
|
+
|
|
11
|
+
The constraint set is a plain data object so that v2 can build one from an
|
|
12
|
+
arbitrary background without changing the consumers.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Literal
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from ._oklab import Array, relative_luminance, srgb_to_linear, srgb_to_oklab
|
|
23
|
+
|
|
24
|
+
Background = Literal["white", "black"]
|
|
25
|
+
|
|
26
|
+
# WCAG 2.x requires 3:1 for graphical objects such as chart marks (SC 1.4.11) and
|
|
27
|
+
# 4.5:1 for text (SC 1.4.3, AA) or 7:1 (AAA).
|
|
28
|
+
DEFAULT_MIN_CONTRAST = 3.0
|
|
29
|
+
|
|
30
|
+
# The contrast ratio above which the feasible set is too small to optimize over.
|
|
31
|
+
# (The maximum possible, 21:1, allows only pure black on white.)
|
|
32
|
+
MAX_MIN_CONTRAST = 15.0
|
|
33
|
+
|
|
34
|
+
# Margin kept inside the luminance bound, so colors still satisfy the contrast
|
|
35
|
+
# requirement after 8-bit quantization.
|
|
36
|
+
FEASIBLE_INSET = 0.002
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class Constraints:
|
|
41
|
+
"""The feasible color range for one background.
|
|
42
|
+
|
|
43
|
+
``min_contrast`` is the WCAG contrast ratio every color must have against the
|
|
44
|
+
background. Chroma is limited only by the sRGB gamut, applied elsewhere.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
background: str
|
|
48
|
+
background_srgb: tuple[float, float, float]
|
|
49
|
+
min_contrast: float = DEFAULT_MIN_CONTRAST
|
|
50
|
+
inset: float = FEASIBLE_INSET
|
|
51
|
+
|
|
52
|
+
def __post_init__(self) -> None:
|
|
53
|
+
if not 1.0 <= self.min_contrast <= MAX_MIN_CONTRAST:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"min_contrast must be between 1 and {MAX_MIN_CONTRAST:g}, got {self.min_contrast!r}"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def background_lab(self) -> Array:
|
|
60
|
+
"""The background color in OKLab (a fixed anchor in the objective)."""
|
|
61
|
+
return srgb_to_oklab(np.asarray(self.background_srgb))
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def opposite_lab(self) -> Array:
|
|
65
|
+
"""The opposite of the background (black on white, white on black) in OKLab.
|
|
66
|
+
|
|
67
|
+
Marks such as plot lines, axes and text are drawn in it, so colors must stay
|
|
68
|
+
distinct from it just as from the background.
|
|
69
|
+
"""
|
|
70
|
+
return srgb_to_oklab(1.0 - np.asarray(self.background_srgb))
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def reference_labs(self) -> Array:
|
|
74
|
+
"""``(2, 3)`` OKLab array: the background and its opposite, the fixed anchors."""
|
|
75
|
+
return np.stack([self.background_lab, self.opposite_lab])
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def background_luminance(self) -> float:
|
|
79
|
+
return float(relative_luminance(srgb_to_linear(np.asarray(self.background_srgb))))
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def luminance_range(self) -> tuple[float, float]:
|
|
83
|
+
"""Exact ``(low, high)`` bounds on relative luminance ``Y`` for the contrast ratio.
|
|
84
|
+
|
|
85
|
+
Colors on a light background must be darker (``Y <= (Yb + 0.05) / r - 0.05``);
|
|
86
|
+
colors on a dark one lighter (``Y >= r * (Yb + 0.05) - 0.05``).
|
|
87
|
+
"""
|
|
88
|
+
yb, r = self.background_luminance, self.min_contrast
|
|
89
|
+
if yb > 0.179: # the luminance where white and black text contrast equally
|
|
90
|
+
return 0.0, (yb + 0.05) / r - 0.05
|
|
91
|
+
return r * (yb + 0.05) - 0.05, 1.0
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def luminance_bounds(self) -> tuple[float, float]:
|
|
95
|
+
""":attr:`luminance_range` tightened by the inset margin."""
|
|
96
|
+
lo, hi = self.luminance_range
|
|
97
|
+
if lo > 0.0:
|
|
98
|
+
lo += self.inset
|
|
99
|
+
if hi < 1.0:
|
|
100
|
+
hi -= self.inset
|
|
101
|
+
return max(lo, 0.0), min(hi, 1.0)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
_WHITE = Constraints(background="white", background_srgb=(1.0, 1.0, 1.0))
|
|
105
|
+
_BLACK = Constraints(background="black", background_srgb=(0.0, 0.0, 0.0))
|
|
106
|
+
|
|
107
|
+
_BUILTIN: dict[str, Constraints] = {"white": _WHITE, "black": _BLACK}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def get_constraints(background: str, min_contrast: float = DEFAULT_MIN_CONTRAST) -> Constraints:
|
|
111
|
+
"""Return the constraints for ``background`` (``"white"`` or ``"black"``)."""
|
|
112
|
+
try:
|
|
113
|
+
base = _BUILTIN[background]
|
|
114
|
+
except (KeyError, TypeError):
|
|
115
|
+
allowed = ", ".join(repr(k) for k in _BUILTIN)
|
|
116
|
+
raise ValueError(f"background must be one of {allowed}; got {background!r}") from None
|
|
117
|
+
if isinstance(min_contrast, bool) or not isinstance(min_contrast, (int, float)):
|
|
118
|
+
raise TypeError(f"min_contrast must be a number, got {min_contrast!r}")
|
|
119
|
+
if min_contrast == base.min_contrast:
|
|
120
|
+
return base
|
|
121
|
+
return Constraints(
|
|
122
|
+
background=base.background,
|
|
123
|
+
background_srgb=base.background_srgb,
|
|
124
|
+
min_contrast=float(min_contrast),
|
|
125
|
+
)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Color-vision-deficiency (CVD) simulation.
|
|
2
|
+
|
|
3
|
+
Each deficiency is simulated by a 3x3 matrix applied in linear sRGB (Machado,
|
|
4
|
+
Oliveira & Fernandes 2009, severity 1.0, i.e. full dichromacy). The simulated
|
|
5
|
+
color is then compared in OKLab like any other, so a CVD "view" of a palette is
|
|
6
|
+
just a different map from OKLab to OKLab. Where a view's Jacobian is needed (for
|
|
7
|
+
the optimizer's gradients) it is computed analytically.
|
|
8
|
+
|
|
9
|
+
- ``protan``: missing L (red) cones.
|
|
10
|
+
- ``deutan``: missing M (green) cones.
|
|
11
|
+
- ``tritan``: missing S (blue) cones.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Literal, cast, overload
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
from numpy.typing import ArrayLike
|
|
20
|
+
|
|
21
|
+
from ._oklab import _M1, _M1_INV, _M2, _M2_INV, Array
|
|
22
|
+
|
|
23
|
+
CvdType = Literal["protan", "deutan", "tritan"]
|
|
24
|
+
|
|
25
|
+
_MATRICES: dict[str, Array] = {
|
|
26
|
+
"protan": np.array(
|
|
27
|
+
[
|
|
28
|
+
[0.152286, 1.052583, -0.204868],
|
|
29
|
+
[0.114503, 0.786281, 0.099216],
|
|
30
|
+
[-0.003882, -0.048116, 1.051998],
|
|
31
|
+
]
|
|
32
|
+
),
|
|
33
|
+
"deutan": np.array(
|
|
34
|
+
[
|
|
35
|
+
[0.367322, 0.860646, -0.227968],
|
|
36
|
+
[0.280085, 0.672501, 0.047413],
|
|
37
|
+
[-0.011820, 0.042940, 0.968881],
|
|
38
|
+
]
|
|
39
|
+
),
|
|
40
|
+
"tritan": np.array(
|
|
41
|
+
[
|
|
42
|
+
[1.255528, -0.076749, -0.178779],
|
|
43
|
+
[-0.078411, 0.930809, 0.147602],
|
|
44
|
+
[0.004733, 0.691367, 0.303900],
|
|
45
|
+
]
|
|
46
|
+
),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
CVD_TYPES: tuple[CvdType, ...] = cast("tuple[CvdType, ...]", tuple(_MATRICES))
|
|
50
|
+
|
|
51
|
+
# The simulation as a linear map on LMS, so only cube roots are nonlinear.
|
|
52
|
+
_LMS_MAPS = {k: _M1 @ m @ _M1_INV for k, m in _MATRICES.items()}
|
|
53
|
+
|
|
54
|
+
_MIN_CBRT_SQ = 1e-8 # keeps the cube-root derivative finite near black
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def normalize_cvd(cvd: str | None | ArrayLike) -> tuple[CvdType, ...]:
|
|
58
|
+
"""Validate ``cvd`` (a name or a sequence of names) into a tuple without repeats."""
|
|
59
|
+
if cvd is None:
|
|
60
|
+
return ()
|
|
61
|
+
if isinstance(cvd, str):
|
|
62
|
+
cvd = (cvd,)
|
|
63
|
+
try:
|
|
64
|
+
names = tuple(cvd) # type: ignore[arg-type]
|
|
65
|
+
except TypeError:
|
|
66
|
+
raise TypeError(f"cvd must be a sequence of names, got {cvd!r}") from None
|
|
67
|
+
for name in names:
|
|
68
|
+
if name not in CVD_TYPES:
|
|
69
|
+
allowed = ", ".join(repr(k) for k in CVD_TYPES)
|
|
70
|
+
raise ValueError(f"cvd entries must be one of {allowed}; got {name!r}")
|
|
71
|
+
return cast("tuple[CvdType, ...]", tuple(dict.fromkeys(names)))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@overload
|
|
75
|
+
def simulate(lab: ArrayLike, kind: str, jacobian: Literal[False] = False) -> Array: ...
|
|
76
|
+
@overload
|
|
77
|
+
def simulate(lab: ArrayLike, kind: str, jacobian: Literal[True]) -> tuple[Array, Array]: ...
|
|
78
|
+
def simulate(lab: ArrayLike, kind: str, jacobian: bool = False) -> Array | tuple[Array, Array]:
|
|
79
|
+
"""The OKLab colors ``lab`` ``(..., 3)`` as seen with deficiency ``kind``.
|
|
80
|
+
|
|
81
|
+
With ``jacobian=True`` also returns ``J`` ``(..., 3, 3)`` with
|
|
82
|
+
``J[..., k, l] = d simulated_k / d lab_l``.
|
|
83
|
+
"""
|
|
84
|
+
lab = np.asarray(lab, dtype=np.float64)
|
|
85
|
+
a_map = _LMS_MAPS[kind]
|
|
86
|
+
root = lab @ _M2_INV.T # cube-rooted LMS
|
|
87
|
+
seen = (root**3) @ a_map.T
|
|
88
|
+
seen_root = np.cbrt(seen)
|
|
89
|
+
out = seen_root @ _M2.T
|
|
90
|
+
if not jacobian:
|
|
91
|
+
return out
|
|
92
|
+
inner = 3.0 * root**2
|
|
93
|
+
outer = 1.0 / (3.0 * np.maximum(seen_root**2, _MIN_CBRT_SQ))
|
|
94
|
+
# J = M2 . diag(outer) . A . diag(inner) . M2^-1
|
|
95
|
+
jac = _M2 @ (outer[..., :, None] * (a_map @ (inner[..., :, None] * _M2_INV)))
|
|
96
|
+
return out, jac
|