sphericolor 0.2.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.
- sphericolor/__init__.py +8 -0
- sphericolor/api.py +257 -0
- sphericolor/colors.py +47 -0
- sphericolor/data/__init__.py +0 -0
- sphericolor/data/srgb_cam16ucs.ply +6443 -0
- sphericolor/diagnostics.py +24 -0
- sphericolor/distances.py +24 -0
- sphericolor/embedding.py +31 -0
- sphericolor/gamut.py +42 -0
- sphericolor/methods/__init__.py +0 -0
- sphericolor/methods/bivariate.py +38 -0
- sphericolor/methods/hsluv.py +18 -0
- sphericolor/methods/ray.py +77 -0
- sphericolor/methods/simplex.py +93 -0
- sphericolor/result.py +50 -0
- sphericolor/validation.py +108 -0
- sphericolor-0.2.0.dist-info/METADATA +214 -0
- sphericolor-0.2.0.dist-info/RECORD +20 -0
- sphericolor-0.2.0.dist-info/WHEEL +4 -0
- sphericolor-0.2.0.dist-info/licenses/LICENSE +22 -0
sphericolor/__init__.py
ADDED
sphericolor/api.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Public generation API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike, NDArray
|
|
10
|
+
from scipy.spatial import ConvexHull, QhullError
|
|
11
|
+
from scipy.spatial.distance import pdist, squareform
|
|
12
|
+
|
|
13
|
+
from .colors import cam16ucs_to_rgb, rgb_to_cam16ucs, rgb_to_hex
|
|
14
|
+
from .diagnostics import build_diagnostics
|
|
15
|
+
from .distances import great_circle_matrix
|
|
16
|
+
from .embedding import metric_mds
|
|
17
|
+
from .gamut import srgb_hull
|
|
18
|
+
from .methods.bivariate import bivariate_colors
|
|
19
|
+
from .methods.hsluv import hsluv_colors
|
|
20
|
+
from .methods.ray import project_directions_to_gamut
|
|
21
|
+
from .methods.simplex import fit_embedding_to_gamut
|
|
22
|
+
from .result import ColorMapping, Diagnostics, immutable_metadata, readonly
|
|
23
|
+
from .validation import (
|
|
24
|
+
DISTANCE_METHODS,
|
|
25
|
+
validate_bivariate_map,
|
|
26
|
+
validate_colors,
|
|
27
|
+
validate_coordinates,
|
|
28
|
+
validate_distance_matrix,
|
|
29
|
+
validate_labels,
|
|
30
|
+
validate_method,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _mapping(
|
|
35
|
+
*,
|
|
36
|
+
labels: tuple[Any, ...],
|
|
37
|
+
rgb: NDArray[np.float64],
|
|
38
|
+
method: str,
|
|
39
|
+
metadata: dict[str, Any],
|
|
40
|
+
diagnostics: Diagnostics | None,
|
|
41
|
+
) -> ColorMapping:
|
|
42
|
+
checked_rgb = validate_colors(rgb, len(labels))
|
|
43
|
+
cam16ucs = rgb_to_cam16ucs(checked_rgb)
|
|
44
|
+
return ColorMapping(
|
|
45
|
+
labels=labels,
|
|
46
|
+
rgb=readonly(checked_rgb),
|
|
47
|
+
hex=readonly(rgb_to_hex(checked_rgb)),
|
|
48
|
+
cam16ucs=readonly(cam16ucs),
|
|
49
|
+
method=method,
|
|
50
|
+
metadata=immutable_metadata(metadata),
|
|
51
|
+
diagnostics=diagnostics,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _distance_mapping(
|
|
56
|
+
distances: NDArray[np.float64],
|
|
57
|
+
labels: tuple[Any, ...],
|
|
58
|
+
method: str,
|
|
59
|
+
random_state: int | None,
|
|
60
|
+
mds_seed_trials: int,
|
|
61
|
+
diagnostics: bool,
|
|
62
|
+
metadata: dict[str, Any],
|
|
63
|
+
) -> ColorMapping:
|
|
64
|
+
seeds = _mds_seed_candidates(random_state, mds_seed_trials)
|
|
65
|
+
input_distances = squareform(distances, checks=False)
|
|
66
|
+
gamut_volume = float(srgb_hull().volume)
|
|
67
|
+
seed_scores: list[dict[str, float | int | None]] = []
|
|
68
|
+
selected: tuple[
|
|
69
|
+
float,
|
|
70
|
+
int | None,
|
|
71
|
+
NDArray[np.float64],
|
|
72
|
+
NDArray[np.float64],
|
|
73
|
+
NDArray[np.float64],
|
|
74
|
+
int,
|
|
75
|
+
dict[str, Any],
|
|
76
|
+
] | None = None
|
|
77
|
+
|
|
78
|
+
for seed in seeds:
|
|
79
|
+
candidate_embedding = metric_mds(distances, seed)
|
|
80
|
+
if method == "ray":
|
|
81
|
+
candidate_mapped, candidate_metadata = project_directions_to_gamut(
|
|
82
|
+
candidate_embedding
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
candidate_mapped, candidate_metadata = fit_embedding_to_gamut(
|
|
86
|
+
candidate_embedding, distances
|
|
87
|
+
)
|
|
88
|
+
candidate_rgb, candidate_clipped = cam16ucs_to_rgb(candidate_mapped)
|
|
89
|
+
candidate_displayed = rgb_to_cam16ucs(candidate_rgb)
|
|
90
|
+
preservation, exploitation, score = _mds_seed_score(
|
|
91
|
+
input_distances, candidate_displayed, gamut_volume
|
|
92
|
+
)
|
|
93
|
+
seed_scores.append(
|
|
94
|
+
{
|
|
95
|
+
"seed": seed,
|
|
96
|
+
"distance_preservation": preservation,
|
|
97
|
+
"colorspace_exploitation": exploitation,
|
|
98
|
+
"score": score,
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
if selected is None or score > selected[0]:
|
|
102
|
+
selected = (
|
|
103
|
+
score,
|
|
104
|
+
seed,
|
|
105
|
+
candidate_embedding,
|
|
106
|
+
candidate_mapped,
|
|
107
|
+
candidate_rgb,
|
|
108
|
+
candidate_clipped,
|
|
109
|
+
candidate_metadata,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
if selected is None:
|
|
113
|
+
raise RuntimeError("MDS seed selection produced no candidates")
|
|
114
|
+
_, selected_seed, embedding, mapped, rgb, clipped, method_metadata = selected
|
|
115
|
+
displayed_cam16ucs = rgb_to_cam16ucs(rgb)
|
|
116
|
+
metadata.update(method_metadata)
|
|
117
|
+
metadata.update(
|
|
118
|
+
{
|
|
119
|
+
"clipped_color_count": clipped,
|
|
120
|
+
"random_state": random_state,
|
|
121
|
+
"mds_seed_trials": mds_seed_trials,
|
|
122
|
+
"selected_mds_seed": selected_seed,
|
|
123
|
+
"mds_seed_scores": tuple(seed_scores),
|
|
124
|
+
}
|
|
125
|
+
)
|
|
126
|
+
diagnostic_result = (
|
|
127
|
+
build_diagnostics(distances, displayed_cam16ucs, embedding, mapped)
|
|
128
|
+
if diagnostics
|
|
129
|
+
else None
|
|
130
|
+
)
|
|
131
|
+
return _mapping(
|
|
132
|
+
labels=labels,
|
|
133
|
+
rgb=rgb,
|
|
134
|
+
method=method,
|
|
135
|
+
metadata=metadata,
|
|
136
|
+
diagnostics=diagnostic_result,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _mds_seed_candidates(
|
|
141
|
+
random_state: int | None, trials: int
|
|
142
|
+
) -> tuple[int | None, ...]:
|
|
143
|
+
if isinstance(trials, bool) or not isinstance(trials, int) or trials < 1:
|
|
144
|
+
raise ValueError("mds_seed_trials must be a positive integer")
|
|
145
|
+
if trials == 1:
|
|
146
|
+
return (random_state,)
|
|
147
|
+
|
|
148
|
+
seeds = [69]
|
|
149
|
+
if random_state is not None and random_state != 69:
|
|
150
|
+
seeds.append(random_state)
|
|
151
|
+
generator = np.random.default_rng(random_state)
|
|
152
|
+
while len(seeds) < trials:
|
|
153
|
+
seed = int(generator.integers(0, 2**32 - 1))
|
|
154
|
+
if seed not in seeds:
|
|
155
|
+
seeds.append(seed)
|
|
156
|
+
return tuple(seeds[:trials])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _mds_seed_score(
|
|
160
|
+
input_distances: NDArray[np.float64],
|
|
161
|
+
displayed_cam16ucs: NDArray[np.float64],
|
|
162
|
+
gamut_volume: float,
|
|
163
|
+
) -> tuple[float, float, float]:
|
|
164
|
+
color_distances = 1.41 * np.power(pdist(displayed_cam16ucs), 0.63)
|
|
165
|
+
if np.std(input_distances) <= 1e-12 or np.std(color_distances) <= 1e-12:
|
|
166
|
+
preservation = 0.0
|
|
167
|
+
else:
|
|
168
|
+
correlation = float(np.corrcoef(input_distances, color_distances)[0, 1])
|
|
169
|
+
preservation = float(np.clip(correlation, 0.0, 1.0))
|
|
170
|
+
|
|
171
|
+
if displayed_cam16ucs.shape[0] < 4:
|
|
172
|
+
return preservation, 0.0, preservation
|
|
173
|
+
try:
|
|
174
|
+
exploitation = float(
|
|
175
|
+
np.clip(ConvexHull(displayed_cam16ucs).volume / gamut_volume, 0.0, 1.0)
|
|
176
|
+
)
|
|
177
|
+
except QhullError:
|
|
178
|
+
return preservation, 0.0, preservation
|
|
179
|
+
return preservation, exploitation, 0.5 * (preservation + exploitation)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def from_latlon(
|
|
183
|
+
latitudes: ArrayLike,
|
|
184
|
+
longitudes: ArrayLike,
|
|
185
|
+
*,
|
|
186
|
+
labels: Sequence[Any] | None = None,
|
|
187
|
+
method: str = "ray",
|
|
188
|
+
random_state: int | None = 69,
|
|
189
|
+
mds_seed_trials: int = 1,
|
|
190
|
+
diagnostics: bool = False,
|
|
191
|
+
bivariate_map: str = "cube_diagonal",
|
|
192
|
+
) -> ColorMapping:
|
|
193
|
+
"""Generate colors for an ordered set of latitude-longitude points."""
|
|
194
|
+
selected_method = validate_method(method)
|
|
195
|
+
lat, lon = validate_coordinates(latitudes, longitudes)
|
|
196
|
+
checked_labels = validate_labels(labels, lat.size)
|
|
197
|
+
distances = great_circle_matrix(lat, lon)
|
|
198
|
+
metadata: dict[str, Any] = {
|
|
199
|
+
"input": "latitude_longitude",
|
|
200
|
+
"distance": "great_circle_km",
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if selected_method in DISTANCE_METHODS:
|
|
204
|
+
return _distance_mapping(
|
|
205
|
+
distances,
|
|
206
|
+
checked_labels,
|
|
207
|
+
selected_method,
|
|
208
|
+
random_state,
|
|
209
|
+
mds_seed_trials,
|
|
210
|
+
diagnostics,
|
|
211
|
+
metadata,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
if selected_method == "hsluv":
|
|
215
|
+
rgb = hsluv_colors(lat, lon)
|
|
216
|
+
else:
|
|
217
|
+
selected_bivariate = validate_bivariate_map(bivariate_map)
|
|
218
|
+
rgb = bivariate_colors(lat, lon, selected_bivariate)
|
|
219
|
+
metadata["bivariate_map"] = selected_bivariate
|
|
220
|
+
cam16ucs = rgb_to_cam16ucs(rgb)
|
|
221
|
+
diagnostic_result = (
|
|
222
|
+
build_diagnostics(distances, cam16ucs, None, None) if diagnostics else None
|
|
223
|
+
)
|
|
224
|
+
metadata["clipped_color_count"] = 0
|
|
225
|
+
return _mapping(
|
|
226
|
+
labels=checked_labels,
|
|
227
|
+
rgb=rgb,
|
|
228
|
+
method=selected_method,
|
|
229
|
+
metadata=metadata,
|
|
230
|
+
diagnostics=diagnostic_result,
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def from_distance_matrix(
|
|
235
|
+
distances: ArrayLike,
|
|
236
|
+
*,
|
|
237
|
+
labels: Sequence[Any] | None = None,
|
|
238
|
+
method: str = "ray",
|
|
239
|
+
random_state: int | None = 69,
|
|
240
|
+
mds_seed_trials: int = 1,
|
|
241
|
+
diagnostics: bool = False,
|
|
242
|
+
) -> ColorMapping:
|
|
243
|
+
"""Generate colors from an ordered pairwise-distance matrix."""
|
|
244
|
+
selected_method = validate_method(method)
|
|
245
|
+
if selected_method not in DISTANCE_METHODS:
|
|
246
|
+
raise ValueError("distance-matrix input supports only ray and simplex")
|
|
247
|
+
matrix = validate_distance_matrix(distances)
|
|
248
|
+
checked_labels = validate_labels(labels, matrix.shape[0])
|
|
249
|
+
return _distance_mapping(
|
|
250
|
+
matrix,
|
|
251
|
+
checked_labels,
|
|
252
|
+
selected_method,
|
|
253
|
+
random_state,
|
|
254
|
+
mds_seed_trials,
|
|
255
|
+
diagnostics,
|
|
256
|
+
{"input": "distance_matrix", "distance": "user_supplied"},
|
|
257
|
+
)
|
sphericolor/colors.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Color-space conversions and serialization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from coloraide import Color as BaseColor
|
|
7
|
+
from coloraide.distance.delta_e_cam16 import DECAM16
|
|
8
|
+
from coloraide.spaces.cam16_ucs import CAM16LCD, CAM16SCD, CAM16UCS, CAM16JMh # type: ignore[attr-defined]
|
|
9
|
+
from numpy.typing import ArrayLike, NDArray
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Color(BaseColor):
|
|
13
|
+
"""Package-local ColorAide registry."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
Color.register([CAM16UCS(), CAM16SCD(), CAM16LCD(), DECAM16(), CAM16JMh()])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def rgb_to_cam16ucs(rgb: ArrayLike) -> NDArray[np.float64]:
|
|
20
|
+
values = np.asarray(rgb, dtype=np.float64)
|
|
21
|
+
output = np.empty_like(values)
|
|
22
|
+
for index, color in enumerate(values):
|
|
23
|
+
converted = Color("srgb", color.tolist()).convert("cam16-ucs")
|
|
24
|
+
output[index] = converted.coords()
|
|
25
|
+
return output
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def cam16ucs_to_rgb(
|
|
29
|
+
cam16ucs: ArrayLike,
|
|
30
|
+
) -> tuple[NDArray[np.float64], int]:
|
|
31
|
+
values = np.asarray(cam16ucs, dtype=np.float64)
|
|
32
|
+
output = np.empty_like(values)
|
|
33
|
+
clipped = 0
|
|
34
|
+
for index, color in enumerate(values):
|
|
35
|
+
converted = np.asarray(
|
|
36
|
+
Color("cam16-ucs", color.tolist()).convert("srgb").coords(), dtype=np.float64
|
|
37
|
+
)
|
|
38
|
+
clipped += int(np.any((converted < 0.0) | (converted > 1.0)))
|
|
39
|
+
output[index] = np.clip(converted, 0.0, 1.0)
|
|
40
|
+
return output, clipped
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def rgb_to_hex(rgb: ArrayLike) -> NDArray[np.str_]:
|
|
44
|
+
values = np.rint(np.asarray(rgb, dtype=np.float64) * 255.0).astype(np.uint8)
|
|
45
|
+
return np.asarray(
|
|
46
|
+
[f"#{red:02x}{green:02x}{blue:02x}" for red, green, blue in values], dtype=np.str_
|
|
47
|
+
)
|
|
File without changes
|