Dataset Viewer
repo
stringlengths 7
45
| pull_number
int64 2
43.6k
| instance_id
stringlengths 11
49
| issue_numbers
stringlengths 5
16
| base_commit
stringlengths 40
40
| patch
stringlengths 245
649k
| test_patch
stringlengths 378
64.4k
| problem_statement
stringlengths 10
30.6k
| hints_text
stringlengths 0
24.1k
| created_at
stringdate 2014-03-08 20:34:09
2025-03-30 05:47:27
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
74
| PASS_TO_PASS
sequencelengths 0
1.35k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
facelessuser/coloraide | 395 | facelessuser__coloraide-395 | ['394'] | fe820f9f0e1e5182d6bff1b72ae10c1fbbc60479 | diff --git a/coloraide/algebra.py b/coloraide/algebra.py
index 5b2922de4..3c0a9a45b 100644
--- a/coloraide/algebra.py
+++ b/coloraide/algebra.py
@@ -132,6 +132,26 @@ def round_to(f: float, p: int = 0, half_up: bool = True) -> float:
return _round(whole if digits > p else f, p - digits)
+def minmax(value: VectorLike | Iterable[float]) -> tuple[float, float]:
+ """Return the minimum and maximum value."""
+
+ mn = INF
+ mx = -INF
+ e = -1
+
+ for i in value:
+ e += 1
+ if i > mx:
+ mx = i
+ if i < mn:
+ mn = i
+
+ if e == -1:
+ raise ValueError("minmax() arg is an empty sequence")
+
+ return mn, mx
+
+
def clamp(
value: SupportsFloatOrInt,
mn: SupportsFloatOrInt | None = None,
diff --git a/coloraide/color.py b/coloraide/color.py
index 70cac36aa..41e7b9652 100644
--- a/coloraide/color.py
+++ b/coloraide/color.py
@@ -61,6 +61,8 @@
from .gamut import Fit
from .gamut.fit_lch_chroma import LChChroma
from .gamut.fit_oklch_chroma import OkLChChroma
+from .gamut.fit_oklch_raytrace import OkLChRayTrace
+from .gamut.fit_lch_raytrace import LChRayTrace
from .cat import CAT, Bradford
from .filters import Filter
from .filters.w3c_filter_effects import Sepia, Brightness, Contrast, Saturate, Opacity, HueRotate, Grayscale, Invert
@@ -1394,6 +1396,8 @@ def alpha(self, *, nans: bool = True) -> float:
# Fit
LChChroma(),
OkLChChroma(),
+ LChRayTrace(),
+ OkLChRayTrace(),
# Filters
Sepia(),
diff --git a/coloraide/gamut/fit_lch_raytrace.py b/coloraide/gamut/fit_lch_raytrace.py
new file mode 100644
index 000000000..e34486397
--- /dev/null
+++ b/coloraide/gamut/fit_lch_raytrace.py
@@ -0,0 +1,15 @@
+"""
+Gamut mapping by scaling.
+
+This employs a faster approach than bisecting to reduce chroma.
+"""
+from .fit_oklch_raytrace import OkLChRayTrace
+
+
+class LChRayTrace(OkLChRayTrace):
+ """Apply gamut mapping using ray tracing."""
+
+ NAME = 'lch-raytrace'
+ SPACE = "lch-d65"
+ MAX_LIGHTNESS = 100
+ MIN_LIGHTNESS = 0
diff --git a/coloraide/gamut/fit_oklch_raytrace.py b/coloraide/gamut/fit_oklch_raytrace.py
new file mode 100644
index 000000000..165512b50
--- /dev/null
+++ b/coloraide/gamut/fit_oklch_raytrace.py
@@ -0,0 +1,283 @@
+"""
+Gamut mapping by using ray tracing.
+
+This employs a faster approach than bisecting to reduce chroma.
+"""
+from __future__ import annotations
+import functools
+from .. import algebra as alg
+from ..gamut import Fit
+from ..spaces import Space, RGBish, HSLish, HSVish, HWBish
+from ..spaces.hsl import hsl_to_srgb, srgb_to_hsl
+from ..spaces.hsv import hsv_to_srgb, srgb_to_hsv
+from ..spaces.hwb import hwb_to_srgb, srgb_to_hwb
+from ..spaces.srgb_linear import sRGBLinear
+from ..types import Vector
+from typing import TYPE_CHECKING, Callable, Any # noqa: F401
+
+if TYPE_CHECKING: # pragma: no cover
+ from ..color import Color
+
+
[email protected]_cache(maxsize=10)
+def coerce_to_rgb(OrigColor: type[Color], cs: Space) -> tuple[type[Color], str]:
+ """
+ Coerce an HSL, HSV, or HWB color space to RGB to allow us to ray trace the gamut.
+
+ It is rare to have a color space that is bound to an RGB gamut that does not exist as an RGB
+ defined RGB space. HPLuv is one that is defined only as a cylindrical, HSL-like space. Okhsl
+ and Okhsv are another whose gamut is meant to target sRGB, but it is very fuzzy and has sRGB
+ colors not quite in gamut, and others that exceed the sRGB gamut.
+
+ For gamut mapping, RGB cylindrical spaces can be coerced into an RGB form using traditional
+ HSL, HSV, or HWB approaches which is good enough.
+ """
+
+ if isinstance(cs, HSLish):
+ to_ = hsl_to_srgb # type: Callable[[Vector], Vector]
+ from_ = srgb_to_hsl # type: Callable[[Vector], Vector]
+ elif isinstance(cs, HSVish):
+ to_ = hsv_to_srgb
+ from_ = srgb_to_hsv
+ elif isinstance(cs, HWBish): # pragma: no cover
+ to_ = hwb_to_srgb
+ from_ = srgb_to_hwb
+ else: # pragma: no cover
+ raise ValueError('Cannot coerce {} to an RGB space.'.format(cs.NAME))
+
+ class RGB(sRGBLinear):
+ """Custom RGB class."""
+
+ NAME = '-rgb-{}'.format(cs.NAME)
+ BASE = cs.NAME
+ GAMUT_CHECK = None
+ CLIP_SPACE = None
+ WHITE = cs.WHITE
+ DYAMIC_RANGE = cs.DYNAMIC_RANGE
+ INDEXES = cs.indexes() # type: ignore[attr-defined]
+ # Scale saturation and lightness (or HWB whiteness and blackness)
+ SCALE_SAT = cs.CHANNELS[INDEXES[1]].high
+ SCALE_LIGHT = cs.CHANNELS[INDEXES[1]].high
+
+ def to_base(self, coords: Vector) -> Vector:
+ """Convert from RGB to HSL."""
+
+ coords = from_(coords)
+ if self.SCALE_SAT != 1:
+ coords[1] *= self.SCALE_SAT
+ if self.SCALE_LIGHT != 1:
+ coords[2] *= self.SCALE_LIGHT
+ ordered = [0.0, 0.0, 0.0]
+ for e, c in enumerate(coords):
+ ordered[self.INDEXES[e]] = c
+ return ordered
+
+ def from_base(self, coords: Vector) -> Vector:
+ """Convert from HSL to RGB."""
+
+ coords = [coords[i] for i in self.INDEXES]
+ if self.SCALE_SAT != 1:
+ coords[1] /= self.SCALE_SAT
+ if self.SCALE_LIGHT != 1:
+ coords[2] /= self.SCALE_LIGHT
+ coords = to_(coords)
+ return coords
+
+ class ColorRGB(OrigColor): # type: ignore[valid-type, misc]
+ """Custom color."""
+
+ ColorRGB.register(RGB())
+
+ return ColorRGB, RGB.NAME
+
+
+def raytrace_cube(size: Vector, start: Vector, end: Vector) -> tuple[int, Vector]:
+ """
+ Returns the face and the intersection tuple of an array from start to end of a cube of size [x, y, z].
+
+ - 0: None, (point is None)
+ - 1: intersection with x==0 face,
+ - 2: intersection with x==size[0] face,
+ - 3: intersection with y==0 face,
+ - 4: intersection with y==size[1] face,
+ - 5: intersection with z==0 face,
+ - 6: intersection with z==size[2] face,
+
+ The cube is an axis-aligned cube: (0,0,0)-(size[0],size[1],size[2]).
+
+ ```
+ mwt (https://math.stackexchange.com/users/591865/mwt),
+ Finding the side of a cube intersecting a line using the shortest computation,
+ URL (version: 2020-08-01): https://math.stackexchange.com/q/3776157
+ ```
+ """
+
+ # Negated deltas
+ ndx = start[0] - end[0]
+ ndy = start[1] - end[1]
+ ndz = start[2] - end[2]
+
+ # Sizes scaled by the negated deltas
+ sxy = ndx * size[1]
+ sxz = ndx * size[2]
+ syx = ndy * size[0]
+ syz = ndy * size[2]
+ szx = ndz * size[0]
+ szy = ndz * size[1]
+
+ # Cross terms
+ cxy = end[0] *start[1] - end[1] * start[0]
+ cxz = end[0] *start[2] - end[2] * start[0]
+ cyz = end[1] *start[2] - end[2] * start[1]
+
+ # Absolute delta products
+ axy = abs(ndx * ndy)
+ axz = abs(ndx * ndz)
+ ayz = abs(ndy * ndz)
+ axyz = abs(ndz * axy)
+
+ # Default to "no intersection"
+ face_num = 0
+ face_tau = abs(ndz * axy)
+
+ # These variables are no longer used:
+ del ndx, ndy, ndz
+
+ if start[0] < 0 and 0 < end[0]:
+ # Face 1: x == 0
+ tau = -start[0] * ayz
+ if tau < face_tau and cxy >= 0 and cxz >= 0 and cxy <= -sxy and cxz <= -sxz:
+ face_tau = tau
+ face_num = 1
+
+ elif end[0] < size[0] and size[0] < start[0]:
+ # Face 2: x == size[0]
+ tau = (start[0] - size[0]) * ayz
+ if tau < face_tau and cxy <= syx and cxz <= szx and cxy >= syx - sxy and cxz >= szx - sxz:
+ face_tau = tau
+ face_num = 2
+
+ if start[1] < 0 and end[1] > 0:
+ # Face 3: y == 0
+ tau = -start[1] * axz
+ if tau < face_tau and cxy <= 0 and cyz >= 0 and cxy >= syx and cyz <= -syz:
+ face_tau = tau
+ face_num = 3
+
+ elif start[1] > size[1] and end[1] < size[1]:
+ # Face 4: y == size[1]
+ tau = (start[1] - size[1]) * axz
+ if tau < face_tau and cxy >= -sxy and cyz <= szy and cxy <= syx - sxy and cyz >= szy - syz:
+ face_tau = tau
+ face_num = 4
+
+ if start[2] < 0 and end[2] > 0:
+ # Face 5: z == 0
+ tau = -start[2] * axy
+ if tau < face_tau and cxz <= 0 and cyz <= 0 and cxz >= szx and cyz >= szy:
+ face_tau = tau
+ face_num = 5
+
+ elif start[2] > size[2] and end[2] < size[2]:
+ # Face 6: z == size[2]
+ tau = (start[2] - size[2]) * axy
+ if tau < face_tau and cxz >= -sxz and cyz >= -syz and cxz <= szx - sxz and cyz <= szy - syz:
+ face_tau = tau
+ face_num = 6
+
+ if face_num > 0:
+ tend = face_tau / axyz
+ tstart = 1.0 - tend
+ return (
+ face_num,
+ [
+ tstart * start[0] + tend * end[0],
+ tstart * start[1] + tend * end[1],
+ tstart * start[2] + tend * end[2]
+ ]
+ )
+ else: # pragma: no cover
+ return 0, []
+
+
+class OkLChRayTrace(Fit):
+ """Gamut mapping by using ray tracing."""
+
+ NAME = "oklch-raytrace"
+ SPACE = "oklch"
+ MAX_LIGHTNESS = 1
+ MIN_LIGHTNESS = 0
+ TRACES = 3
+ BACKOFF_MAP = {
+ 1: [0.99],
+ 2: [0.88, 0.99],
+ 3: [0.9, 0.95, 0.99]
+ }
+
+ def fit(self, color: Color, space: str, *, traces: int = 0, **kwargs: Any) -> None:
+ """Scale the color within its gamut but preserve L and h as much as possible."""
+
+ # Requires an RGB-ish space, preferably a linear space.
+ coerced = None
+ cs = color.CS_MAP[space]
+
+ # Coerce RGB cylinders with no defined RGB space to RGB
+ if not isinstance(cs, RGBish):
+ coerced = color
+ Color_, space = coerce_to_rgb(type(color), cs)
+ cs = Color_.CS_MAP[space]
+ color = Color_(color)
+
+ # For now, if a non-linear CSS variant is specified, just use the linear form.
+ linear = cs.linear() # type: ignore[attr-defined]
+ if linear and linear in color.CS_MAP:
+ space = linear
+
+ orig = color.space()
+ mapcolor = color.convert(self.SPACE, norm=False) if orig != self.SPACE else color.clone().normalize(nans=False)
+ l, c, h = mapcolor._space.indexes() # type: ignore[attr-defined]
+ # Perform the iteration(s) scaling within the RGB space but afterwards preserving all but chroma
+ gamutcolor = color.convert(space, norm=False) if orig != space else color.clone().normalize(nans=False)
+
+ mn, mx = alg.minmax(gamutcolor[:-1])
+ # Return white for white or black.
+ if mn == mx and mx >= 1:
+ color.update(space, [1.0, 1.0, 1.0], mapcolor[-1])
+ elif mn == mx and mx <= 0:
+ color.update(space, [0.0, 0.0, 0.0], mapcolor[-1])
+ else:
+ # Perform the iteration(s) scaling within the RGB space but afterwards preserving all but chroma
+ gamutcolor = color.convert(space, norm=False) if orig != space else color.clone().normalize(nans=False)
+ achroma = mapcolor.clone().set('c', 0).convert(space)
+
+ L = self.SPACE + '.' + str(l)
+ C = self.SPACE + '.' + str(c)
+ H = self.SPACE + '.' + str(h)
+
+ # Create a line from our color to color with zero lightness.
+ # Trace the line to the RGB cube finding the face and the point where it intersects.
+ # Back off chroma on each iteration, less as we get closer.
+ size = [1.0, 1.0, 1.0]
+ backoff = self.BACKOFF_MAP[traces if traces else self.TRACES]
+ for i in range(len(backoff)):
+ face, intersection = raytrace_cube(size, gamutcolor.coords(), achroma.coords())
+ if face:
+ gamutcolor[:-1] = intersection
+ # Back off chroma and try with a closer point
+ gamutcolor.set(
+ {
+ L: mapcolor[l],
+ C: lambda a, b=mapcolor[c], i=i: (b - ((b - a) * backoff[i])),
+ H: mapcolor[h]
+ }
+ )
+ else: # pragma: no cover
+ # We were already within the cube
+ break
+
+ # Finally, clip the color just in case
+ gamutcolor[:-1] = [alg.clamp(x, 0, 1) for x in gamutcolor[:-1]]
+ color.update(gamutcolor)
+
+ if coerced:
+ coerced.update(color)
diff --git a/coloraide/spaces/__init__.py b/coloraide/spaces/__init__.py
index 0c1eef1f1..a0f66c8e7 100644
--- a/coloraide/spaces/__init__.py
+++ b/coloraide/spaces/__init__.py
@@ -43,6 +43,11 @@ def indexes(self) -> list[int]:
return [self.get_channel_index(name) for name in self.names()] # type: ignore[attr-defined]
+ def linear(self) -> str:
+ """Will return the name of the space which is the linear version of itself (if available)."""
+
+ return ''
+
class HSLish(Cylindrical):
"""HSL-ish space."""
diff --git a/coloraide/spaces/a98_rgb.py b/coloraide/spaces/a98_rgb.py
index a9165cc36..87088ae5d 100644
--- a/coloraide/spaces/a98_rgb.py
+++ b/coloraide/spaces/a98_rgb.py
@@ -1,7 +1,6 @@
"""A98 RGB color class."""
from __future__ import annotations
-from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -18,12 +17,16 @@ def gam_a98rgb(rgb: Vector) -> Vector:
return [alg.npow(val, 256 / 563) for val in rgb]
-class A98RGB(sRGB):
+class A98RGB(sRGBLinear):
"""A98 RGB class."""
BASE = "a98-rgb-linear"
NAME = "a98-rgb"
- WHITE = WHITES['2deg']['D65']
+
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from A98 RGB."""
diff --git a/coloraide/spaces/a98_rgb_linear.py b/coloraide/spaces/a98_rgb_linear.py
index fbdf6de8f..e0168db33 100644
--- a/coloraide/spaces/a98_rgb_linear.py
+++ b/coloraide/spaces/a98_rgb_linear.py
@@ -1,7 +1,6 @@
"""Linear A98 RGB color class."""
from __future__ import annotations
-from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -37,13 +36,12 @@ def xyz_to_lin_a98rgb(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_RGB, xyz, dims=alg.D2_D1)
-class A98RGBLinear(sRGB):
+class A98RGBLinear(sRGBLinear):
"""Linear A98 RGB class."""
BASE = "xyz-d65"
NAME = "a98-rgb-linear"
SERIALIZE = ('--a98-rgb-linear',)
- WHITE = WHITES['2deg']['D65']
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from A98 RGB."""
diff --git a/coloraide/spaces/aces2065_1.py b/coloraide/spaces/aces2065_1.py
index 5503c476b..2efc70070 100644
--- a/coloraide/spaces/aces2065_1.py
+++ b/coloraide/spaces/aces2065_1.py
@@ -5,7 +5,7 @@
"""
from __future__ import annotations
from ..channels import Channel
-from ..spaces.srgb import sRGB
+from ..spaces.srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -37,12 +37,12 @@ def xyz_to_aces(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_AP0, xyz, dims=alg.D2_D1)
-class ACES20651(sRGB):
+class ACES20651(sRGBLinear):
"""The ACES color class."""
BASE = "xyz-d65"
NAME = "aces2065-1"
- SERIALIZE = ("--aces2065-1",) # type: tuple[str, ...]
+ SERIALIZE = ("--aces2065-1",)
WHITE = (0.32168, 0.33767)
CHANNELS = (
Channel("r", 0.0, 65504.0, bound=True),
diff --git a/coloraide/spaces/acescc.py b/coloraide/spaces/acescc.py
index 23bb82816..a1bfc7afb 100644
--- a/coloraide/spaces/acescc.py
+++ b/coloraide/spaces/acescc.py
@@ -6,7 +6,7 @@
from __future__ import annotations
import math
from ..channels import Channel
-from ..spaces.srgb import sRGB
+from ..spaces.srgb_linear import sRGBLinear
from ..types import Vector
CC_MIN = (math.log2(2 ** -16) + 9.72) / 17.52
@@ -50,7 +50,7 @@ def acescg_to_acescc(acescg: Vector) -> Vector:
return acescc
-class ACEScc(sRGB):
+class ACEScc(sRGBLinear):
"""The ACEScc color class."""
BASE = "acescg"
@@ -64,6 +64,11 @@ class ACEScc(sRGB):
)
DYNAMIC_RANGE = 'hdr'
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To XYZ."""
diff --git a/coloraide/spaces/acescct.py b/coloraide/spaces/acescct.py
index 3e04da7f1..5b0eb1664 100644
--- a/coloraide/spaces/acescct.py
+++ b/coloraide/spaces/acescct.py
@@ -6,7 +6,7 @@
from __future__ import annotations
import math
from ..channels import Channel
-from ..spaces.srgb import sRGB
+from ..spaces.srgb_linear import sRGBLinear
from ..types import Vector
from .acescc import CC_MAX
@@ -45,7 +45,7 @@ def acescg_to_acescct(acescg: Vector) -> Vector:
return acescc
-class ACEScct(sRGB):
+class ACEScct(sRGBLinear):
"""The ACEScct color class."""
BASE = "acescg"
@@ -59,6 +59,11 @@ class ACEScct(sRGB):
)
DYNAMIC_RANGE = 'hdr'
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To XYZ."""
diff --git a/coloraide/spaces/acescg.py b/coloraide/spaces/acescg.py
index 5cdd6d147..ad6394dcb 100644
--- a/coloraide/spaces/acescg.py
+++ b/coloraide/spaces/acescg.py
@@ -5,7 +5,7 @@
"""
from __future__ import annotations
from ..channels import Channel
-from ..spaces.srgb import sRGB
+from ..spaces.srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -34,7 +34,7 @@ def xyz_to_acescg(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_AP1, xyz, dims=alg.D2_D1)
-class ACEScg(sRGB):
+class ACEScg(sRGBLinear):
"""The ACEScg color class."""
BASE = "xyz-d65"
diff --git a/coloraide/spaces/display_p3.py b/coloraide/spaces/display_p3.py
index 4c6415fb2..42fe41b95 100644
--- a/coloraide/spaces/display_p3.py
+++ b/coloraide/spaces/display_p3.py
@@ -1,16 +1,20 @@
"""Display-p3 color class."""
from __future__ import annotations
-from ..cat import WHITES
-from .srgb import sRGB, lin_srgb, gam_srgb
+from .srgb_linear import sRGBLinear
+from .srgb import lin_srgb, gam_srgb
from ..types import Vector
-class DisplayP3(sRGB):
+class DisplayP3(sRGBLinear):
"""Display-p3 class."""
BASE = "display-p3-linear"
NAME = "display-p3"
- WHITE = WHITES['2deg']['D65']
+
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Display P3."""
diff --git a/coloraide/spaces/display_p3_linear.py b/coloraide/spaces/display_p3_linear.py
index 9f78d3c53..90f1679dc 100644
--- a/coloraide/spaces/display_p3_linear.py
+++ b/coloraide/spaces/display_p3_linear.py
@@ -1,7 +1,6 @@
"""Linear Display-p3 color class."""
from __future__ import annotations
-from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -35,13 +34,12 @@ def xyz_to_lin_p3(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_RGB, xyz, dims=alg.D2_D1)
-class DisplayP3Linear(sRGB):
+class DisplayP3Linear(sRGBLinear):
"""Linear Display-p3 class."""
BASE = "xyz-d65"
NAME = "display-p3-linear"
SERIALIZE = ('--display-p3-linear',)
- WHITE = WHITES['2deg']['D65']
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Linear Display P3."""
diff --git a/coloraide/spaces/prophoto_rgb.py b/coloraide/spaces/prophoto_rgb.py
index 493889903..550fba549 100644
--- a/coloraide/spaces/prophoto_rgb.py
+++ b/coloraide/spaces/prophoto_rgb.py
@@ -1,7 +1,7 @@
"""Pro Photo RGB color class."""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -47,13 +47,18 @@ def gam_prophoto(rgb: Vector) -> Vector:
return result
-class ProPhotoRGB(sRGB):
+class ProPhotoRGB(sRGBLinear):
"""Pro Photo RGB class."""
BASE = "prophoto-rgb-linear"
NAME = "prophoto-rgb"
WHITE = WHITES['2deg']['D50']
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Pro Photo RGB."""
diff --git a/coloraide/spaces/prophoto_rgb_linear.py b/coloraide/spaces/prophoto_rgb_linear.py
index e1ed29156..520777e05 100644
--- a/coloraide/spaces/prophoto_rgb_linear.py
+++ b/coloraide/spaces/prophoto_rgb_linear.py
@@ -1,7 +1,7 @@
"""Linear Pro Photo RGB color class."""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -35,7 +35,7 @@ def xyz_to_lin_prophoto(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_RGB, xyz, dims=alg.D2_D1)
-class ProPhotoRGBLinear(sRGB):
+class ProPhotoRGBLinear(sRGBLinear):
"""Linear Pro Photo RGB class."""
BASE = "xyz-d50"
diff --git a/coloraide/spaces/rec2020.py b/coloraide/spaces/rec2020.py
index cf84a2420..4e5cfb2a2 100644
--- a/coloraide/spaces/rec2020.py
+++ b/coloraide/spaces/rec2020.py
@@ -1,7 +1,6 @@
"""Rec 2020 color class."""
from __future__ import annotations
-from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
import math
from .. import algebra as alg
from ..types import Vector
@@ -48,12 +47,16 @@ def gam_2020(rgb: Vector) -> Vector:
return result
-class Rec2020(sRGB):
+class Rec2020(sRGBLinear):
"""Rec 2020 class."""
BASE = "rec2020-linear"
NAME = "rec2020"
- WHITE = WHITES['2deg']['D65']
+
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Rec. 2020."""
diff --git a/coloraide/spaces/rec2020_linear.py b/coloraide/spaces/rec2020_linear.py
index 778344fe8..950346e38 100644
--- a/coloraide/spaces/rec2020_linear.py
+++ b/coloraide/spaces/rec2020_linear.py
@@ -1,7 +1,7 @@
"""Linear Rec 2020 color class."""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
@@ -39,7 +39,7 @@ def xyz_to_lin_2020(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_RGB, xyz, dims=alg.D2_D1)
-class Rec2020Linear(sRGB):
+class Rec2020Linear(sRGBLinear):
"""Linear Rec 2020 class."""
BASE = "xyz-d65"
diff --git a/coloraide/spaces/rec2100_hlg.py b/coloraide/spaces/rec2100_hlg.py
index 95d267bc7..77a4ba34d 100644
--- a/coloraide/spaces/rec2100_hlg.py
+++ b/coloraide/spaces/rec2100_hlg.py
@@ -16,7 +16,7 @@
"""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from .. import algebra as alg
from ..types import Vector
import math
@@ -84,7 +84,7 @@ def hlg_eotf(values: Vector, env: Environment) -> Vector:
return adjusted
-class Rec2100HLG(sRGB):
+class Rec2100HLG(sRGBLinear):
"""Rec. 2100 HLG class."""
BASE = "rec2020-linear"
@@ -94,6 +94,11 @@ class Rec2100HLG(sRGB):
DYNAMIC_RANGE = 'hdr'
ENV = Environment(1000, 0, SCALE)
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To base from Rec 2100 HLG."""
diff --git a/coloraide/spaces/rec2100_pq.py b/coloraide/spaces/rec2100_pq.py
index ce047c980..75ab51da1 100644
--- a/coloraide/spaces/rec2100_pq.py
+++ b/coloraide/spaces/rec2100_pq.py
@@ -5,12 +5,12 @@
"""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
from ..types import Vector
from .. import util
-class Rec2100PQ(sRGB):
+class Rec2100PQ(sRGBLinear):
"""Rec. 2100 PQ class."""
BASE = "rec2020-linear"
@@ -19,6 +19,11 @@ class Rec2100PQ(sRGB):
WHITE = WHITES['2deg']['D65']
DYNAMIC_RANGE = 'hdr'
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Rec. 2100 PQ."""
diff --git a/coloraide/spaces/rec709.py b/coloraide/spaces/rec709.py
index 806e7851d..1eef14170 100644
--- a/coloraide/spaces/rec709.py
+++ b/coloraide/spaces/rec709.py
@@ -8,7 +8,7 @@
- https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.709-6-201506-I!!PDF-E.pdf
"""
from __future__ import annotations
-from .srgb import sRGB
+from .srgb_linear import sRGBLinear
import math
from .. import algebra as alg
from ..types import Vector
@@ -55,13 +55,18 @@ def gam_709(rgb: Vector) -> Vector:
return result
-class Rec709(sRGB):
+class Rec709(sRGBLinear):
"""Rec. 709 class."""
BASE = "srgb-linear"
NAME = "rec709"
SERIALIZE = ("--rec709",)
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
+
+ return self.BASE
+
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from Rec. 709."""
diff --git a/coloraide/spaces/srgb/__init__.py b/coloraide/spaces/srgb/__init__.py
index da09c4c25..6fa9020ac 100644
--- a/coloraide/spaces/srgb/__init__.py
+++ b/coloraide/spaces/srgb/__init__.py
@@ -1,8 +1,6 @@
"""sRGB color class."""
from __future__ import annotations
-from ...spaces import RGBish, Space
-from ...cat import WHITES
-from ...channels import Channel, FLG_OPT_PERCENT
+from ..srgb_linear import sRGBLinear
from ... import algebra as alg
from ...types import Vector
import math
@@ -44,33 +42,18 @@ def gam_srgb(rgb: Vector) -> Vector:
return result
-class sRGB(RGBish, Space):
+class sRGB(sRGBLinear):
"""sRGB class."""
BASE = "srgb-linear"
NAME = "srgb"
- CHANNELS = (
- Channel("r", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT),
- Channel("g", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT),
- Channel("b", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT)
- )
- CHANNEL_ALIASES = {
- "red": 'r',
- "green": 'g',
- "blue": 'b'
- }
- WHITE = WHITES['2deg']['D65']
-
+ SERIALIZE = ("srgb",)
EXTENDED_RANGE = True
- def is_achromatic(self, coords: Vector) -> bool:
- """Test if color is achromatic."""
+ def linear(self) -> str:
+ """Return linear version of the RGB (if available)."""
- white = [1, 1, 1]
- for x in alg.vcross(coords, white):
- if not math.isclose(0.0, x, abs_tol=1e-5):
- return False
- return True
+ return self.BASE
def from_base(self, coords: Vector) -> Vector:
"""From sRGB Linear to sRGB."""
diff --git a/coloraide/spaces/srgb_linear.py b/coloraide/spaces/srgb_linear.py
index 332712444..04bd11790 100644
--- a/coloraide/spaces/srgb_linear.py
+++ b/coloraide/spaces/srgb_linear.py
@@ -1,9 +1,11 @@
"""sRGB Linear color class."""
from __future__ import annotations
from ..cat import WHITES
-from .srgb import sRGB
+from ..spaces import RGBish, Space
+from ..channels import Channel, FLG_OPT_PERCENT
from .. import algebra as alg
from ..types import Vector
+import math
RGB_TO_XYZ = [
@@ -35,13 +37,31 @@ def xyz_to_lin_srgb(xyz: Vector) -> Vector:
return alg.matmul(XYZ_TO_RGB, xyz, dims=alg.D2_D1)
-class sRGBLinear(sRGB):
+class sRGBLinear(RGBish, Space):
"""sRGB linear."""
BASE = 'xyz-d65'
NAME = "srgb-linear"
- SERIALIZE = ("srgb-linear",)
WHITE = WHITES['2deg']['D65']
+ CHANNELS = (
+ Channel("r", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT),
+ Channel("g", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT),
+ Channel("b", 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT)
+ )
+ CHANNEL_ALIASES = {
+ "red": 'r',
+ "green": 'g',
+ "blue": 'b'
+ }
+
+ def is_achromatic(self, coords: Vector) -> bool:
+ """Test if color is achromatic."""
+
+ white = [1, 1, 1]
+ for x in alg.vcross(coords, white):
+ if not math.isclose(0.0, x, abs_tol=1e-5):
+ return False
+ return True
def to_base(self, coords: Vector) -> Vector:
"""To XYZ from sRGB Linear."""
diff --git a/docs/src/dictionary/en-custom.txt b/docs/src/dictionary/en-custom.txt
index 8308cb17a..9db544613 100644
--- a/docs/src/dictionary/en-custom.txt
+++ b/docs/src/dictionary/en-custom.txt
@@ -228,6 +228,7 @@ deregister
deregistered
deregistering
deregistration
+desaturated
deuteranomaly
deuteranopia
dichromacy
diff --git a/docs/src/markdown/about/changelog.md b/docs/src/markdown/about/changelog.md
index b640a2d50..82641ad3f 100644
--- a/docs/src/markdown/about/changelog.md
+++ b/docs/src/markdown/about/changelog.md
@@ -8,6 +8,12 @@
support will be removed for these spaces. Additionally, these spaces are now registered by default.
- **NEW**: ∆E methods `z` and `itp` are now registered by default as their associated color spaces are now registered
by default as well.
+- **NEW**: Ray tracing gamut mapping algorithms have been added: `oklch-raytrace` and `lch-raytrace`. Both require
+ the target gamut to have an RGB gamut equivalent and will choose the linear variant if one is detected.
+- **NEW**: RGB spaces now expose a `linear()` function on the underlying class to specify if they have a linear
+ equivalent.
+- **NEW**: Adjust inheritance order of RGB spaces. Previously, many inherited from `sRGB`, now they inherit from
+ `sRGBLinear`.
- **FIX**: Ensure that when using discrete interpolation that spline based interpolations are truly discrete.
## 2.16
diff --git a/docs/src/markdown/gamut.md b/docs/src/markdown/gamut.md
index e01beabfa..653d0f129 100644
--- a/docs/src/markdown/gamut.md
+++ b/docs/src/markdown/gamut.md
@@ -211,33 +211,55 @@ Clipping is unique to all other clipping methods in that it has its own dedicate
method name `clip` is reserved. While not always the best approach for gamut mapping in general, clip is very important
to some other gamut mapping and has specific cases where its speed and simplicity are of great value.
-### LCh Chroma
+### MINDE Chroma Reduction
+
+MINDE chroma reduction is an approach that reduces the chroma in a perceptual color space until the color is within
+gamut of a targeted color space. As the exact point at which the color will be in gamut is unknown, the chroma is
+reduced using bisection. The color is compared periodically to the the clipped version of the current iteration to see
+if the ∆E distance between them is below the "just noticeable difference" (JND) defined for the color space. If the
+color is close enough to the clipped version, the clipped version is returned.
+
+This method is good because it does a fairly accurate job at approach the gamut surface. It is not prone to over
+correcting, and clipping before you reach the surface helps soften gamut mapping to reduce hard edges in interpolation.
+This approach also keeps lightness and hue fairly constant. If the JND is reduced, the lightness and hue will be held
+even more constant.
+
+Computationally, MINDE Chroma Reduction is slower to compute than clipping, but generally provides better results.
+
+All MINDE Chroma Reduction methods allow the setting of the JND. The default is usually specific to the perceptual
+space being used, but it should be noted that while a lower JND will give you a theoretically better value, some color
+spaces have quirks. Consider the color `#!color color(display-p3 1 1 0)`. If we were to gamut map it in LCh with a very
+low JND, we can see that the odd shape of LCh can cause us to get a very desaturated color. By using the default JND of
+2 for LCh, the fuzziness of the MINDE will catch the more saturated yellow. This isn't a problem in OkLCh, but it has
+its own quirks as well.
+
+/// tab | JND 0
+
+///
+
+/// tab | JND 2
+
+///
+
+#### LCh Chroma
/// success | The `lch-chroma` gamut mapping is registered in `Color` by default
///
-LCh Chroma uses a combination of chroma reduction and MINDE in the CIELCh color space to bring a color into gamut. By
-reducing chroma in the CIELCh color space, LCh Chroma can hold hue and lightness in the LCh color space relatively
-constant. This is currently the default method used.
+LCh Chroma applies MINDE Chroma Reduction within the CIELCh color space. This is the default in ColorAide.
/// note
As most colors in ColorAide use a D65 white point by default, LCh D65 is used as the gamut mapping color space.
///
-The algorithm generally works by performing both clipping and chroma reduction. Using bisection, the chroma is reduced
-and then the chroma reduced color is clipped. Using ∆E~2000~, the distance between the chroma reduced color and the
-clipped chroma reduced color is measured. If the resultant distance falls within the specified threshold, the clipped
-color is returned.
+CIELCh, is not necessarily the best perceptual color space available, but it is a generally well understood color space
+that has been available a long time. It does suffer from a purple shift when dealing with blue colors, but can generally
+handle colors in very wide gamuts reasonably due to its fairly consistent shape well past the spectral locus.
-Computationally, LCh Chroma is slower to compute than clipping, but generally provides better results. CIELCh, is not
-necessarily the best perceptual color space available, but it is a generally well understood color space that has been
-available a long time. It does suffer from a purple shift when dealing with blue colors, but can generally handle colors
-in very wide gamuts reasonably.
-
-While CSS has currently proposed LCh Chroma reduction to be done with OkLCh, and we do offer an [OkLCh variant](#oklch-chroma),
-we currently still use CIELCh as the default until OkLCh can be evaluated more fully as it suffers from its own set of
-issues even if generally has better hue preservation. In the future, the default gamut mapping approach could change if
-a definitively better option is determined.
+CSS originally proposed MINDE Chroma Reduction with CIELCh, but has later changed to OkLCh. It is possible that the
+entire choice in algorithms could change as well in the future. We do offer an [OkLCh variant](#oklch-chroma), but we
+currently still use CIELCh due to its consistency even with colors far outside the gamut. If you are working within
+reasonable gamuts, OkLCh may be a better choice.
LCh Chroma is the default gamut mapping algorithm by default, unless otherwise changed, and can be performed by simply
calling `fit()` or by calling `fit(method='lch-chroma')`.
@@ -255,14 +277,18 @@ c = Color('srgb', [2, -1, 0])
c.fit(method='lch-chroma', jnd=0.2)
```
-### OkLCh Chroma
+#### OkLCh Chroma
/// success | The `lch-chroma` gamut mapping is registered in `Color` by default
///
The CSS [CSS Color Level 4 specification](https://drafts.csswg.org/css-color/#binsearch) currently recommends using
-OkLCh as the gamut mapping color space. OkLCh Chroma is performed exactly like [LCh Chroma](#lch-chroma) except that it
-uses the perceptually uniform OkLCh color space as the LCh color space of choice.
+perceptually uniform OkLCh color space with the MINDE Chroma Reduction approach.
+
+OkLCh does a much better job holding hues constant. When combined with gamut mapping, it generally does a better job
+than CIELCh, but it does have limitations. When colors get near the edge of the visible spectrum, the shape of the
+color space distorts, and gamut mapping will not be as good. But if you are working within reasonable gamuts, it may
+be a option.
OkLCh has the advantage of doing a better job at holding hues uniform than CIELCh.
@@ -279,13 +305,7 @@ c = Color('srgb', [2, -1, 0])
c.fit(method='oklch-chroma', jnd=0.002)
```
-OkLCh is a very new color space to be used in the field of gamut mapping. While CIELCh is not perfect, its weakness are
-known. OkLCh does seem to have certain quirks of its own, and may have more that have yet to be discovered. OkLCh gamut
-mapping can exhibit some issues with some colors with extremely large chroma, near the edge of the visible spectrum.
-While we have not made `oklch-chroma` our default, we have exposed the algorithm so users can begin exploring it mimic
-the CSS approach.
-
-### HCT Chroma
+#### HCT Chroma
/// failure | The `hct-chroma` gamut mapping is **not** registered in `Color` by default
///
@@ -328,6 +348,109 @@ class Color(Base): ...
Color.register([HCT(), DEHCT(), HCTChroma()])
```
+### Ray Tracing Chroma Reduction
+
+/// warning | Experimental Gamut Mapping
+///
+
+ColorAide has developed an experimental chroma reduction technique that employs ray tracing. This approach currently
+only works with RGB gamuts, or spaces that are represented with RGB gamuts. If ColorAide can detect a linear version of
+the targeted RGB space, that version will be used automatically for best results.
+
+The way this approach works is it takes a given color and converts it to a perceptual LCh like color space. Then the
+achromatic version of the color (chroma set to zero) is calculated. Both of these colors are converted to the targeted
+RGB color space. Then a ray traced from the out of gamut RGB color to the achromatic color within the RGB cube
+representing the color gamut. The intersection of the line and the cube is returned as the most saturated color.
+Because the RGB space is not perceptual, the color is then corrected by setting the lightness and hue back to the
+original color's. Before the color is returned, a final clip is applied.
+
+This is an approximation, but with a couple of iterations of ray tracing and corrections before the final clip (backing
+off on the chroma a little on each attempt) you can get a color reasonably close to what you would get by reducing
+chroma via bisection in the perceptual space, but in less time.
+
+As noted, the one downside is that results aren't as accurate as using MINDE Chroma Reduction as it isn't directly
+operating in the perceptual space, but they can be reasonably close.
+
+As noted earlier, the targeted gamut should be an RGB space or RGB equivalent space.
+
+```py play
+Color('oklch(90% 0.8 270)').fit('srgb', method='lch-raytrace')
+```
+
+In general, no matter what approach is being used, RGB is usually preferred. As a matter of fact, by default, most
+spaces will automatically redirect to an RGB gamut, such as HSL, HSV, etc. But there are a few spaces that do not have a
+clearly defined RGB gamut. In these cases, the color space will be mapped to a cube to apply the algorithm. Results
+are often comparable to the MINDE Chroma Reduction approach (especially when using the max traces, the default).
+
+For instance, HPLuv is a space that is only defined as a cylindrical space and contains only a portion of the sRGB
+space. Okhsl and Okhsv are another exception. They generally represent the sRGB gamut, but it is only an approximation
+and has some colors on the fringe missing and contains some colors that are actually outside the sRGB gamut. Gamut
+correcting in these spaces can have hit or miss results, even when using the default MINDE chroma reduction approach,
+and so it is in ray tracing as well.
+
+In general, while ColorAide can map some of these exception spaces, you will get the best results by gamut mapping to
+the closest RGB space.
+
+Lastly, all ray tracing methods allow configuring number of passes or traces performed, from as low as 1X up to 3X. More
+traces usually mean better results and closer hugging of the gamut shape, less traces means it will be faster, but with
+somewhat diminished results. By default 3X, the best, is used.
+
+Depending on the perceptual space used to correct the gamut mapping, this can expose non-optimal geometry. Consider the
+color `#!color color(display-p3 1 1 0)`. This can be particularly problematic when gamut mapping using CIELCh. 3X traces
+holds lightness very constant, and can get very desaturated yellow. If you use 1X traces, you get a less accurate color,
+but a color that makes more sense to the user. This is not a bug, but just the way a color space's geometry can work
+with you or against you. While this is not an issue in OkLCh, it has its own quirks.
+
+/// tab | 3X Traces
+
+///
+
+/// tab | 1X Traces
+
+///
+
+#### LCh Ray Tracing Chroma Reduction
+
+/// success | The `lch-raytrace` gamut mapping is registered in `Color` by default.
+///
+
+This is a ray tracing approach to chroma reduction using CIELCh D65. This can be a faster approach to gamut mapping.
+
+```py play
+Color('oklch(90% 0.8 270)').fit('srgb', method='lch-raytrace')
+Color('oklch(90% 0.8 270)').fit('hsl', method='lch-raytrace')
+```
+
+Ray Tracing Chroma reduction can be performed at either 1X, 2X, or 3X traces, 3X being the default as it provides the
+best results. You can change the required traces on demand via the `traces` argument.
+
+```py play
+Color('oklch(90% 0.8 270)').fit('srgb', method='lch-raytrace', traces=1)
+Color('oklch(90% 0.8 270)').fit('hsl', method='lch-raytrace', traces=2)
+Color('oklch(90% 0.8 270)').fit('hsl', method='lch-raytrace', traces=3)
+```
+
+#### OkLCh Ray Tracing Chroma Reduction
+
+/// success | The `oklch-raytrace` gamut mapping is registered in `Color` by default.
+///
+
+This is a ray tracing approach to chroma reduction using OkLCh. This can be a faster approach to gamut mapping.
+
+```py play
+Color('oklch(90% 0.8 270)').fit('srgb', method='oklch-raytrace')
+Color('oklch(90% 0.8 270)').fit('hsl', method='oklch-raytrace')
+```
+
+Ray Tracing Chroma reduction can be performed at either 1X, 2X, or 3X traces, 3X being the default as it provides the
+best results. You can change the required traces on demand via the `traces` argument.
+
+```py play
+Color('oklch(90% 0.8 270)').fit('srgb', method='oklch-raytrace', traces=1)
+Color('oklch(90% 0.8 270)').fit('hsl', method='oklch-raytrace', traces=2)
+Color('oklch(90% 0.8 270)').fit('hsl', method='oklch-raytrace', traces=3)
+```
+
## Why Not Just Clip?
In the past, clipping has been the default way in which out of gamut colors have been handled in web browsers. It is
@@ -335,39 +458,26 @@ fast, and has generally been fine as most browsers have been constrained to usin
adopt more wide gamut monitors such as Display P3, and CSS grows to support an assortment of wide and ultra wide color
spaces, representing the best intent of an out of gamut color becomes even more important.
-ColorAide currently uses a default gamut mapping algorithm that performs gamut mapping in the CIELCh color space using
-chroma reduction coupled with minimum ∆E (MINDE). This approach is meant to preserve enough of the important attributes
-of the out of gamut color as is possible, mostly preserving both lightness and hue, hue being the attribute that people
-are most sensitive to. MINDE is used to abandon chroma reduction and clip the color when the color is very close to
-being in gamut. MINDE also allows us to catch cases where the geometry of the color space's gamut is such that we may
-slip by higher chroma options resulting in undesirable, aggressive chroma reduction. While CIELCh is not a perfect
-color space, and we may use a different color space in the future, this method is generally more accurate that using
-clipping alone.
-
-Below we have an example of using chroma reduction with MINDE. It can be noted that chroma is reduced until we are very
-close to being in gamut. The MINDE helps us catch the peak of the yellow shape as, otherwise, we would have continued
-reducing chroma until we were at a very chroma reduced, pale yellow.
-
-
-
One might see some cases of clipping and think it does a fine job and question why any of this complexity is necessary.
In order to demonstrate the differences in gamut mapping vs clipping, see the example below. We start with the color
-`#!color color(display-p3 1 1 0)` and interpolate with it in the CIELCh color space reducing just the lightness. This
-will leave both chroma and hue intact. The Interactive playground below automatically gamut maps the color previews to
-sRGB, but we'll control the method being used by providing two different `#!py Color` objects: one that uses
-`lch-chroma` (the default) for gamut mapping, and one that uses `clip`. Notice how clipping, the bottom color set, clips
-these dark colors and makes them reddish. This is a very undesirable outcome.
+`#!color color(display-p3 1 1 0)` and interpolate with in the LCh color space reducing just the lightness. This
+will leave both chroma and hue intact. The high chroma in lower and brighter lightness will be too much to display on
+the screen, so we will employ various gamut mapping approaches: `oklch-chroma`, `oklch-raytrace`, and `clip`. Notice how
+clipping, the bottom color set, clips these dark colors and makes them reddish. This is a very undesirable outcome.
```py play
-# Gamut mapping in LCh
+# Gamut mapping in OkLCh with Ray Tracing
yellow = Color('color(display-p3 1 1 0)')
lightness_mask = Color('lch(0% none none)')
-Row([c.fit('srgb') for c in Color.steps([yellow, lightness_mask], steps=10, space='lch')])
-
+Steps([c.fit('srgb', method='oklch-chroma') for c in Color.steps([yellow, lightness_mask], steps=20, space='lch')])
+# Gamut mapping in OkLCh
+yellow = Color('color(display-p3 1 1 0)')
+lightness_mask = Color('lch(0% none none)')
+Steps([c.fit('srgb', method='oklch-raytrace') for c in Color.steps([yellow, lightness_mask], steps=20, space='lch')])
# Clipping
yellow = Color('color(display-p3 1 1 0)')
lightness_mask = Color('lch(0% none none)')
-Row([c.clip('srgb') for c in Color.steps([yellow, lightness_mask], steps=10, space='lch')])
+Steps([c.clip('srgb') for c in Color.steps([yellow, lightness_mask], steps=20, space='lch')])
```
There are times when clipping is simply preferred. It is fast, and if you are just trimming noise off channels, it is
diff --git a/docs/src/markdown/images/gamut-lch-chroma-yellow.png b/docs/src/markdown/images/gamut-lch-chroma-yellow.png
deleted file mode 100644
index 98eaa0746..000000000
Binary files a/docs/src/markdown/images/gamut-lch-chroma-yellow.png and /dev/null differ
diff --git a/docs/src/markdown/images/jnd-0.png b/docs/src/markdown/images/jnd-0.png
new file mode 100644
index 000000000..ca9812283
Binary files /dev/null and b/docs/src/markdown/images/jnd-0.png differ
diff --git a/docs/src/markdown/images/jnd-2.png b/docs/src/markdown/images/jnd-2.png
new file mode 100644
index 000000000..557b98be1
Binary files /dev/null and b/docs/src/markdown/images/jnd-2.png differ
diff --git a/docs/src/markdown/images/trace-1x.png b/docs/src/markdown/images/trace-1x.png
new file mode 100644
index 000000000..1c8af83e5
Binary files /dev/null and b/docs/src/markdown/images/trace-1x.png differ
diff --git a/docs/src/markdown/images/trace-3x.png b/docs/src/markdown/images/trace-3x.png
new file mode 100644
index 000000000..f6425b837
Binary files /dev/null and b/docs/src/markdown/images/trace-3x.png differ
diff --git a/mkdocs.yml b/mkdocs.yml
index 8eb047a9c..47684f504 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -4,7 +4,7 @@ repo_url: https://github.com/facelessuser/coloraide
edit_uri: ""
site_description: A library to aid in using colors
copyright: |
- Copyright © 2020 - 2023 <a href="https://github.com/facelessuser" target="_blank" rel="noopener">Isaac Muse</a>
+ Copyright © 2020 - 2024 <a href="https://github.com/facelessuser" target="_blank" rel="noopener">Isaac Muse</a>
docs_dir: docs/src/markdown
theme:
diff --git a/tools/gamut_3d_plotly.py b/tools/gamut_3d_plotly.py
index 41bba271a..5d71df043 100644
--- a/tools/gamut_3d_plotly.py
+++ b/tools/gamut_3d_plotly.py
@@ -179,7 +179,7 @@ def cyl_disc(ColorCyl, space, gamut, location, resolution, opacity, edges):
# Ensure colors fit in output color gamut.
s = c.convert('srgb')
if not s.in_gamut():
- s.fit()
+ s.fit(method='lch-raytrace')
else:
s.clip()
cmap.append(s)
@@ -302,7 +302,7 @@ def render_space_cyl(fig, space, gamut, resolution, opacity, edges):
# Adjust gamut to fit the display space
s = c.convert('srgb')
if not s.in_gamut():
- s.fit()
+ s.fit(method='lch-raytrace')
else:
s.clip()
@@ -364,7 +364,7 @@ def render_rect_face(colorrgb, s1, s2, dim, space, gamut, resolution, opacity, e
# Fit colors to output gamut
s = t.convert('srgb')
if not s.in_gamut():
- s.fit()
+ s.fit(method='lch-raytrace')
else:
s.clip()
cmap.append(s)
diff --git a/tools/gamut_diagram.py b/tools/gamut_diagram.py
index 8098580dc..07555d5f1 100644
--- a/tools/gamut_diagram.py
+++ b/tools/gamut_diagram.py
@@ -27,7 +27,14 @@ def main():
parser.add_argument('--dark', action="store_true", help="Use dark theme.")
parser.add_argument('--dpi', default=200, type=int, help="DPI of image.")
parser.add_argument('--output', '-o', default='', help='Output file.')
-
+ parser.add_argument(
+ '--jnd', type=float, default=-1.0,
+ help="Set the JND for MINDE approaches. If set to -1, default JND is used."
+ )
+ parser.add_argument(
+ '--traces', type=int, default=3,
+ help="Set the number of ray trace passes for ray trace approaches. Default is 3."
+ )
args = parser.parse_args()
method = args.method
@@ -36,21 +43,21 @@ def main():
raise ValueError('"{}" is an unsupported clipping space'.format(args.clip_space))
method = args.clip_space + '-chroma'
- if method == 'lch-chroma':
+ if method.startswith('lch'):
space = 'lch-d65'
t_space = 'CIELCh D65'
xaxis = 'c:0:264'
yaxis = 'l:0:100'
x = 'c'
y = 'l'
- elif method == 'oklch-chroma':
+ elif method.startswith('oklch'):
space = 'oklch'
t_space = 'OkLCh'
xaxis = 'c:0:1.5'
yaxis = 'l:0:1'
x = 'c'
y = 'l'
- elif method == 'hct-chroma':
+ elif method.startswith('hct'):
space = 'hct'
t_space = 'HCT'
xaxis = 'c:0:267'
@@ -62,11 +69,18 @@ def main():
if args.method == 'clip':
title = 'Clipping shown in {}'.format(t_space)
- else:
+ elif args.method.endswith('-chroma'):
title = 'MINDE and Chroma Reduction in {}'.format(t_space)
+ elif args.method.endswith('-raytrace'):
+ title = 'Ray Tracing Chroma Reduction in {}'.format(t_space)
+
+ jnd = None if args.jnd == -1 else args.jnd
+ traces = args.traces
+ gmap = {'method': args.method, 'jnd': jnd, 'traces': traces}
- color = Color(args.color).convert(space, in_place=True)
- color2 = color.clone().fit(args.gamut, method=args.method)
+ orig = Color(args.color)
+ color = orig.convert(space, in_place=True)
+ color2 = color.clone().fit(args.gamut, **gmap)
mapcolor = color.convert(space)
mapcolor2 = color2.convert(space)
constant = 'h:{}'.format(fmt_float(mapcolor['hue'], 5))
@@ -78,6 +92,7 @@ def main():
xaxis,
yaxis,
gamut=args.gamut,
+ gmap=gmap,
resolution=int(args.resolution),
title=title,
subtitle=subtitle,
@@ -99,7 +114,7 @@ def main():
mapcolor[x],
mapcolor[y],
marker="o",
- color=color2.convert('srgb').to_string(hex=True, fit=args.method),
+ color=color2.convert('srgb').to_string(hex=True, fit=gmap),
edgecolor='black',
zorder=100
)
@@ -108,7 +123,7 @@ def main():
mapcolor2[x],
mapcolor2[y],
marker="o",
- color=color2.convert('srgb').to_string(hex=True, fit=args.method),
+ color=color2.convert('srgb').to_string(hex=True, fit=gmap),
edgecolor='black',
zorder=100
)
diff --git a/tools/slice_diagram.py b/tools/slice_diagram.py
index e5d5b3219..5c84167a2 100644
--- a/tools/slice_diagram.py
+++ b/tools/slice_diagram.py
@@ -52,10 +52,14 @@ def plot_slice(
subtitle='',
polar=False,
border=False,
- pointer=False
+ pointer=False,
+ gmap=None
):
"""Plot a slice."""
+ if gmap is None:
+ gmap = {}
+
res = resolution
if not dark:
plt.style.use('seaborn-v0_8-darkgrid')
@@ -207,7 +211,7 @@ def plot_slice(
# Save the points
xaxis.append(c1)
yaxis.append(c2)
- c_map.append(r.convert('srgb').to_string(hex=True))
+ c_map.append(r.convert('srgb').to_string(hex=True, fit=gmap))
# Create axes
ax = plt.axes(
@@ -300,6 +304,7 @@ def main():
parser = argparse.ArgumentParser(prog='slice_diagrams', description='Plot a slice of a color space.')
parser.add_argument('--space', '-s', help='Desired space.')
parser.add_argument('--gamut', '-g', default="srgb", help='Gamut to evaluate the color in (default is sRGB).')
+ parser.add_argument('--jnd', default=-1, help='Gamut mapping approach (default is lch-chroma).')
parser.add_argument('--pointer', '-P', action='store_true', help="Restrict to Pointer gamut")
parser.add_argument(
'--constant', '-c', help="The channel(s) to hold constant and the value to use 'name:value;name2:value2'."
@@ -316,15 +321,28 @@ def main():
parser.add_argument('--dark', action="store_true", help="Use dark theme.")
parser.add_argument('--dpi', default=200, type=int, help="DPI of image.")
parser.add_argument('--output', '-o', default='', help='Output file.')
+ parser.add_argument('--gmap', '-G', default='lch-chroma', help='Gamut mapping approach (default is lch-chroma).')
+ parser.add_argument(
+ '--jnd', type=float, default=-1.0,
+ help="Set the JND for MINDE approaches. If set to -1, default JND is used."
+ )
+ parser.add_argument(
+ '--traces', type=int, default=3,
+ help="Set the number of ray trace passes for ray trace approaches. Default is 3."
+ )
args = parser.parse_args()
+ jnd = None if args.jnd == -1 else args.jnd
+ traces = args.traces
+
plot_slice(
args.space,
args.constant,
args.xaxis,
args.yaxis,
gamut=args.gamut,
+ gmap={'method': args.gmap, 'jnd': jnd, 'traces': traces},
resolution=int(args.resolution),
title=args.title,
subtitle=args.sub_title,
| diff --git a/tests/test_a98_rgb.py b/tests/test_a98_rgb.py
index 4d8aaa873..3d5ac249d 100644
--- a/tests/test_a98_rgb.py
+++ b/tests/test_a98_rgb.py
@@ -51,6 +51,11 @@ class TestA98RGBSerialize(util.ColorAssertsPyTest):
('color(a98-rgb none 0.3 0.75)', {'none': True}, 'color(a98-rgb none 0.3 0.75)'),
# Test Fit
('color(a98-rgb 1.2 0.2 0)', {}, 'color(a98-rgb 1 0.48377 0.33147)'),
+ (
+ 'color(a98-rgb 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(a98-rgb 0.99981 0.53028 0.39084)'
+ ),
('color(a98-rgb 1.2 0.2 0)', {'fit': False}, 'color(a98-rgb 1.2 0.2 0)')
]
diff --git a/tests/test_acescc.py b/tests/test_acescc.py
index acf9eccf3..b4a75825e 100644
--- a/tests/test_acescc.py
+++ b/tests/test_acescc.py
@@ -52,6 +52,11 @@ class TestACESccSerialize(util.ColorAssertsPyTest):
('color(--acescc none 0.3 0.75)', {'none': True}, 'color(--acescc none 0.3 0.75)'),
# Test Fit
('color(--acescc 1.5 0.2 0)', {}, 'color(--acescc 1.468 0.2 0)'),
+ (
+ 'color(--acescc 1.5 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(--acescc 0.55479 0.2 0)'
+ ),
('color(--acescc 1.5 0.2 0)', {'fit': False}, 'color(--acescc 1.5 0.2 0)')
]
diff --git a/tests/test_acescct.py b/tests/test_acescct.py
index 986c27c13..14fd715b5 100644
--- a/tests/test_acescct.py
+++ b/tests/test_acescct.py
@@ -55,6 +55,11 @@ class TestACEScctSerialize(util.ColorAssertsPyTest):
('color(--acescct none 0.3 0.75)', {'none': True}, 'color(--acescct none 0.3 0.75)'),
# Test Fit
('color(--acescct 1.5 0.2 0)', {}, 'color(--acescct 1.468 0.2 0.07291)'),
+ (
+ 'color(--acescct 1.5 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(--acescct 0.55479 0.2 0.07291)'
+ ),
('color(--acescct 1.5 0.2 0)', {'fit': False}, 'color(--acescct 1.5 0.2 0)')
]
diff --git a/tests/test_algebra.py b/tests/test_algebra.py
index 3aa386d59..549a2996f 100644
--- a/tests/test_algebra.py
+++ b/tests/test_algebra.py
@@ -2285,6 +2285,14 @@ def test_order(self):
self.assertEqual(alg.order(2), 0)
self.assertEqual(alg.order(0.002), -3)
+ def test_min_max(self):
+ """Test getting the minimum and maximum value."""
+
+ self.assertEqual(alg.minmax([-4, 2, 8, 1]), (-4, 8))
+
+ with self.assertRaises(ValueError):
+ alg.minmax([])
+
def test_pprint(capsys):
"""Test matrix print."""
diff --git a/tests/test_display_p3.py b/tests/test_display_p3.py
index b74b96ac1..b7dca132f 100644
--- a/tests/test_display_p3.py
+++ b/tests/test_display_p3.py
@@ -51,6 +51,11 @@ class TestDisplayP3Serialize(util.ColorAssertsPyTest):
('color(display-p3 none 0.3 0.75)', {'none': True}, 'color(display-p3 none 0.3 0.75)'),
# Test Fit
('color(display-p3 1.2 0.2 0)', {}, 'color(display-p3 1 0.4425 0.20621)'),
+ (
+ 'color(display-p3 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(display-p3 0.97566 0.5001 0.29454)'
+ ),
('color(display-p3 1.2 0.2 0)', {'fit': False}, 'color(display-p3 1.2 0.2 0)')
]
diff --git a/tests/test_gamut.py b/tests/test_gamut.py
index 2b752d60d..fcdf0cbfd 100644
--- a/tests/test_gamut.py
+++ b/tests/test_gamut.py
@@ -192,6 +192,79 @@ def test_fit_options_to_string(self):
)
+class TestRayTrace(util.ColorAsserts, unittest.TestCase):
+ """Test gamut mapping/fitting with ray tracing."""
+
+ def test_sdr_extremes_low(self):
+ """Test SDR extreme low case."""
+
+ color = Color('oklch(-10% 0 none)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0 0 none)'))
+
+ def test_sdr_extremes_high(self):
+ """Test SDR extreme high case."""
+
+ color = Color('oklch(110% 0 none)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(100% 0 none)'))
+
+ def test_non_rgb_space(self):
+ """Test coercion to RGB."""
+
+ color = Color('oklch(90% .4 270)')
+ self.assertColorEqual(color.fit('hpluv', method='oklch-raytrace'), Color('oklch(0.89567 0.04471 270.87)'))
+
+ color = Color('oklch(90% .4 270)')
+ self.assertColorEqual(color.fit('okhsv', method='oklch-raytrace'), Color('oklch(0.89717 0.04962 271.54)'))
+
+ def test_sdr_extremes_high_non_rgb_space(self):
+ """Test coercion of extreme high to RGB."""
+
+ color = Color('oklch(110% 0 none)')
+ self.assertColorEqual(color.fit('okhsl', method='oklch-raytrace'), Color('oklch(100% 0 none)'))
+
+ def test_sdr_extremes_low_non_rgb_space(self):
+ """Test failure with non-RGB space."""
+
+ color = Color('oklch(-10% 0 none)')
+ self.assertColorEqual(color.fit('okhsl', method='oklch-raytrace'), Color('oklch(0 0 none)'))
+
+ def test_trace_face1(self):
+ """Test tracing of face 1."""
+
+ color = Color('oklch(30% .4 160)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.30119 0.06919 159.06)'))
+
+ def test_trace_face2(self):
+ """Test tracing of face 2."""
+
+ color = Color('oklch(90% .4 60)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.89901 0.06608 60.711)'))
+
+ def test_trace_face3(self):
+ """Test tracing of face 3."""
+
+ color = Color('oklch(30% .4 10)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.30184 0.12068 10.577)'))
+
+ def test_trace_face4(self):
+ """Test tracing of face 4."""
+
+ color = Color('oklch(90% .4 150)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.89926 0.18309 150.03)'))
+
+ def test_trace_face5(self):
+ """Test tracing of face 5."""
+
+ color = Color('oklch(30% .4 100)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.30032 0.06231 99.36)'))
+
+ def test_trace_face6(self):
+ """Test tracing of face 6."""
+
+ color = Color('oklch(90% .4 270)')
+ self.assertColorEqual(color.fit('srgb', method='oklch-raytrace'), Color('oklch(0.89917 0.04852 269.03)'))
+
+
class TestHCTGamut(util.ColorAsserts, unittest.TestCase):
"""
Test HCT gamut mapping by producing tonal maps.
diff --git a/tests/test_prophoto_rgb.py b/tests/test_prophoto_rgb.py
index 3225d65de..b8d06c30c 100644
--- a/tests/test_prophoto_rgb.py
+++ b/tests/test_prophoto_rgb.py
@@ -51,6 +51,11 @@ class TestProPhotoRGBSerialize(util.ColorAssertsPyTest):
('color(prophoto-rgb none 0.3 0.75)', {'none': True}, 'color(prophoto-rgb none 0.3 0.75)'),
# Test Fit
('color(prophoto-rgb 1.2 0.2 0)', {}, 'color(prophoto-rgb 1 0.36233 0.1352)'),
+ (
+ 'color(prophoto-rgb 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(prophoto-rgb 0.97164 0.42956 0.20834)'
+ ),
('color(prophoto-rgb 1.2 0.2 0)', {'fit': False}, 'color(prophoto-rgb 1.2 0.2 0)')
]
diff --git a/tests/test_rec2020.py b/tests/test_rec2020.py
index 3db7de670..b956379fd 100644
--- a/tests/test_rec2020.py
+++ b/tests/test_rec2020.py
@@ -51,6 +51,11 @@ class TestRec2020Serialize(util.ColorAssertsPyTest):
('color(rec2020 none 0.3 0.75)', {'none': True}, 'color(rec2020 none 0.3 0.75)'),
# Test Fit
('color(rec2020 1.2 0.2 0)', {}, 'color(rec2020 1 0.41739 0.13711)'),
+ (
+ 'color(rec2020 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(rec2020 0.97555 0.48189 0.2323)'
+ ),
('color(rec2020 1.2 0.2 0)', {'fit': False}, 'color(rec2020 1.2 0.2 0)')
]
diff --git a/tests/test_rec2100_hlg.py b/tests/test_rec2100_hlg.py
index 16191417e..0be20b8b5 100644
--- a/tests/test_rec2100_hlg.py
+++ b/tests/test_rec2100_hlg.py
@@ -51,6 +51,11 @@ class TestRec2100HLGSerialize(util.ColorAssertsPyTest):
('color(rec2100-hlg none 0.3 0.75)', {'none': True}, 'color(rec2100-hlg none 0.3 0.75)'),
# Test Fit
('color(rec2100-hlg 1.2 0.2 0)', {}, 'color(rec2100-hlg 1 0.94165 0.89523)'),
+ (
+ 'color(rec2100-hlg 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(rec2100-hlg 0.75 0.2 0)'
+ ),
('color(rec2100-hlg 1.2 0.2 0)', {'fit': False}, 'color(rec2100-hlg 1.2 0.2 0)')
]
diff --git a/tests/test_rec2100_pq.py b/tests/test_rec2100_pq.py
index 95873b7c2..6f0f7f71f 100644
--- a/tests/test_rec2100_pq.py
+++ b/tests/test_rec2100_pq.py
@@ -51,6 +51,11 @@ class TestRec2100PQSerialize(util.ColorAssertsPyTest):
('color(rec2100-pq none 0.3 0.75)', {'none': True}, 'color(rec2100-pq none 0.3 0.75)'),
# Test Fit
('color(rec2100-pq 1.2 0.2 0)', {}, 'color(rec2100-pq 1 1 1)'),
+ (
+ 'color(rec2100-pq 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(rec2100-pq 0.58069 0.2 0)'
+ ),
('color(rec2100-pq 1.2 0.2 0)', {'fit': False}, 'color(rec2100-pq 1.2 0.2 0)')
]
diff --git a/tests/test_rec709.py b/tests/test_rec709.py
index c2ce2493f..faf21c492 100644
--- a/tests/test_rec709.py
+++ b/tests/test_rec709.py
@@ -51,6 +51,11 @@ class TestRec709Serialize(util.ColorAssertsPyTest):
('color(--rec709 none 0.3 0.75)', {'none': True}, 'color(--rec709 none 0.3 0.75)'),
# Test Fit
('color(--rec709 1.2 0.2 0)', {}, 'color(--rec709 1 0.37065 0.18538)'),
+ (
+ 'color(--rec709 1.2 0.2 0)',
+ {'color': True, 'fit': 'lch-raytrace'},
+ 'color(--rec709 0.99019 0.41784 0.25318)'
+ ),
('color(--rec709 1.2 0.2 0)', {'fit': False}, 'color(--rec709 1.2 0.2 0)')
]
diff --git a/tests/test_srgb.py b/tests/test_srgb.py
index e74e362ed..f214578eb 100644
--- a/tests/test_srgb.py
+++ b/tests/test_srgb.py
@@ -126,6 +126,7 @@ class TestsRGBSerialize(util.ColorAssertsPyTest):
('rgb(0 255 25.5 / 0.5)', {'color': True, 'alpha': False}, 'color(srgb 0 1 0.1)'),
# Test Fit
('color(srgb 1.2 0.2 0)', {'color': True}, 'color(srgb 1 0.42056 0.2633)'),
+ ('color(srgb 1.2 0.2 0)', {'color': True, 'fit': 'lch-raytrace'}, 'color(srgb 0.99476 0.46349 0.32156)'),
('color(srgb 1.2 0.2 0)', {'color': True, 'fit': False}, 'color(srgb 1.2 0.2 0)')
]
| Add new GMA algorithm
Created a new GMA algorithm inspired by a method called Scale LH over at https://github.com/color-js/color.js.
Scale LH was a fast method that very roughly approximates the gamut (currently targeting Display P3). It does so by scaling the color towards the midpoint in linear light. Essentially it does two passes with the scaling, the first it preserves L and H, hence the name. It performs admirably, but I did have a few issues with it.
- It does not hold Light very constant. It can actually deviate a lot.
- Due to its deviations, it can affect gradients.
- If used in images, the color relations and be a little jarring.
This new method, which I'll call Scale LH Achromatic for now, scales the color toward an achromatic version of itself. This method requires the target gamut to be an RGB space, ideally linear RGB. Basically, the algorithm is.
1. Calculate the OkLCh version of the color.
2. Create an achromatic versioning OkLCh.
3. Convert both to Linear RGB (if possible).
4. Scale the color towards the achromatic value in the linear RGB space until the color is in the gamut.
5. Write the original OkLCh L and H values back.
6. Step (5) should be performed at least twice but can be done more. Currently, I've found three to be decent.
7. Clip the color and return.
My first attempt generally worked pretty well, but I did run into issues in lower light blue (and maybe a few other places). This was a bit frustrating as the approach generally seemed to work better, but in this one area, it performed a bit worse.
After experimenting for far too long, I found that if I separated out the lightness and scaled the color so that the lightness could be better preserved, I no longer over (or under) corrected. This greatly improved performance in low-light blue and other places.
In general, this approach may be a good fit for sending colors directly to a display format (usually RGB). It performs similarly to the slower, MINDE chroma reduction method but is much faster.
Ref: https://github.com/color-js/color.js/pull/449
| So, with further experimentation, we ended up implementing a better approach that introduced ray tracing to reduce the chroma. A PR will be up soon. | 2024-02-25T02:27:20.000 | -1.0 | [
"tests/test_acescct.py::TestACEScctSerialize::test_colors[color(--acescct",
"tests/test_rec2100_hlg.py::TestRec2100HLGSerialize::test_colors[color(rec2100-hlg",
"tests/test_display_p3.py::TestDisplayP3Serialize::test_colors[color(display-p3",
"tests/test_gamut.py::TestRayTrace::test_trace_face4",
"tests/test_prophoto_rgb.py::TestProPhotoRGBSerialize::test_colors[color(prophoto-rgb",
"tests/test_gamut.py::TestRayTrace::test_sdr_extremes_high_non_rgb_space",
"tests/test_gamut.py::TestRayTrace::test_non_rgb_space",
"tests/test_gamut.py::TestRayTrace::test_sdr_extremes_high",
"tests/test_algebra.py::TestAlgebra::test_min_max",
"tests/test_gamut.py::TestRayTrace::test_sdr_extremes_low",
"tests/test_rec2020.py::TestRec2020Serialize::test_colors[color(rec2020",
"tests/test_gamut.py::TestRayTrace::test_trace_face1",
"tests/test_rec709.py::TestRec709Serialize::test_colors[color(--rec709",
"tests/test_a98_rgb.py::TestA98RGBSerialize::test_colors[color(a98-rgb",
"tests/test_gamut.py::TestRayTrace::test_trace_face6",
"tests/test_rec2100_pq.py::TestRec2100PQSerialize::test_colors[color(rec2100-pq",
"tests/test_gamut.py::TestRayTrace::test_trace_face3",
"tests/test_srgb.py::TestsRGBSerialize::test_colors[color(srgb",
"tests/test_gamut.py::TestRayTrace::test_trace_face5",
"tests/test_acescc.py::TestACESccSerialize::test_colors[color(--acescc",
"tests/test_gamut.py::TestRayTrace::test_trace_face2",
"tests/test_gamut.py::TestRayTrace::test_sdr_extremes_low_non_rgb_space"
] | [
"tests/test_gamut.py::TestGamut::test_bad_fit",
"tests/test_algebra.py::TestAlgebra::test_det",
"tests/test_srgb.py::TestsRGB::test_colors[green-color(srgb",
"tests/test_acescc.py::TestACEScc::test_colors[black-color(--acescc",
"tests/test_srgb.py::TestsRGB::test_colors[violet-color(srgb",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[violet-color(a98-rgb",
"tests/test_rec2020.py::TestRec2020::test_colors[violet-color(rec2020",
"tests/test_srgb.py::TestsRGB::test_colors[black-color(srgb",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(50%,",
"tests/test_gamut.py::TestGamut::test_in_gamut_other_space",
"tests/test_srgb.py::TestsRGB::test_colors[blue-color(srgb",
"tests/test_algebra.py::TestAlgebra::test_vstack",
"tests/test_gamut.py::TestPointerGamut::test_fit_pointer_gamut_too_dark",
"tests/test_algebra.py::TestAlgebra::test_eye",
"tests/test_algebra.py::TestAlgebra::test_any",
"tests/test_gamut.py::TestPointerGamut::test_fit_pointer_gamut",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[orange-color(rec2100-pq",
"tests/test_srgb.py::TestsRGBProperties::test_blue",
"tests/test_rec709.py::TestRec709::test_colors[green-color(--rec709",
"tests/test_rec2100_pq.py::Testrec2100PQPoperties::test_r",
"tests/test_algebra.py::TestAlgebra::test_vectorize1",
"tests/test_algebra.py::TestAlgebra::test_dot",
"tests/test_algebra.py::TestAlgebra::test_interpolate_natural",
"tests/test_algebra.py::TestAlgebra::test_hstack",
"tests/test_display_p3.py::TestDisplayP3::test_colors[white-color(display-p3",
"tests/test_gamut.py::TestPointerGamut::test_in_pointer_gamut_too_light",
"tests/test_display_p3.py::TestDisplayP3::test_colors[yellow-color(display-p3",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(0%,",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[yellow-color(a98-rgb",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[white-color(rec2100-pq",
"tests/test_algebra.py::TestAlgebra::test_multi_dot",
"tests/test_gamut.py::TestGamut::test_clip_other_gamut_in_gamut",
"tests/test_gamut.py::TestPointerGamut::test_pointer_boundary_too_dark",
"tests/test_acescct.py::TestACEScct::test_colors[gray-color(--acescct",
"tests/test_algebra.py::TestAlgebra::test_apply_one_input",
"tests/test_gamut.py::TestGamut::test_fit_options_to_string",
"tests/test_gamut.py::TestGamut::test_sdr_extremes_high",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[color(a98-rgb",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[yellow-color(rec2100-pq",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[yellow-color(prophoto-rgb",
"tests/test_acescct.py::TestACEScctProperties::test_alpha",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[blue-color(rec2100-hlg",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[black-color(a98-rgb",
"tests/test_algebra.py::TestAlgebra::test_is_nan",
"tests/test_algebra.py::TestAlgebra::test_identity",
"tests/test_rec2020.py::TestRec2020::test_colors[green-color(rec2020",
"tests/test_acescc.py::TestACEScc::test_colors[color(--acescc",
"tests/test_srgb.py::TestsRGB::test_colors[orange-color(srgb",
"tests/test_algebra.py::TestAlgebra::test_divide",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[orange-color(a98-rgb",
"tests/test_rec2020.py::TestRec2020::test_colors[blue-color(rec2020",
"tests/test_algebra.py::TestAlgebra::test_lu",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[blue-color(prophoto-rgb",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(none",
"tests/test_algebra.py::TestAlgebra::test_all",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(50%",
"tests/test_acescct.py::TestACEScctProperties::test_green",
"tests/test_rec2020.py::TestRec2020Properties::test_green",
"tests/test_acescc.py::TestACEScc::test_colors[yellow-color(--acescc",
"tests/test_acescct.py::TestACEScct::test_colors[white-color(--acescct",
"tests/test_rec709.py::TestRec709::test_colors[orange-color(--rec709",
"tests/test_algebra.py::TestAlgebra::test_no_nan",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[indigo-color(a98-rgb",
"tests/test_algebra.py::TestAlgebra::test_round_to_num",
"tests/test_gamut.py::TestGamut::test_out_of_gamut",
"tests/test_rec2020.py::TestRec2020::test_colors[red-color(rec2020",
"tests/test_gamut.py::TestGamut::test_fit_options",
"tests/test_gamut.py::TestPointerGamut::test_in_pointer_gamut",
"tests/test_acescc.py::TestACEScc::test_colors[violet-color(--acescc",
"tests/test_algebra.py::TestAlgebra::test_scale",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[red-color(rec2100-pq",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(0",
"tests/test_algebra.py::TestAlgebra::test_order",
"tests/test_prophoto_rgb.py::TestProPhotoRGBProperties::test_red",
"tests/test_srgb.py::TestsRGB::test_colors[#ee82ee80-color(srgb",
"tests/test_acescct.py::TestACEScctToACES2065_1::test_colors[color(--aces2065-1",
"tests/test_rec709.py::TestRec709::test_colors[violet-color(--rec709",
"tests/test_algebra.py::TestAlgebra::test_inv",
"tests/test_algebra.py::TestAlgebra::test_cbrt",
"tests/test_gamut.py::TestGamut::test_clip",
"tests/test_acescc.py::TestACEScc::test_colors[indigo-color(--acescc",
"tests/test_rec2020.py::TestRec2020::test_colors[white-color(rec2020",
"tests/test_display_p3.py::TestDisplayP3::test_colors[black-color(display-p3",
"tests/test_acescct.py::TestACEScctProperties::test_red",
"tests/test_acescc.py::TestACESccProperties::test_green",
"tests/test_rec2020.py::TestRec2020::test_colors[orange-color(rec2020",
"tests/test_algebra.py::TestAlgebra::test_reshape",
"tests/test_acescc.py::TestACESccProperties::test_blue",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[green-color(a98-rgb",
"tests/test_gamut.py::TestGamut::test_fit_other_space",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(none,",
"tests/test_gamut.py::TestPointerGamut::test_in_pointer_gamut_too_dark",
"tests/test_gamut.py::TestGamut::test_clip_other_space",
"tests/test_a98_rgb.py::TestA98RGBProperties::test_red",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(0%,",
"tests/test_rec709.py::TestRec709::test_colors[color(--rec709",
"tests/test_acescct.py::TestACEScctProperties::test_blue",
"tests/test_rec709.py::TestRec709Properties::test_red",
"tests/test_rec2100_pq.py::Testrec2100PQPoperties::test_b",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(128deg",
"tests/test_display_p3.py::TestDisplayP3::test_colors[gray-color(display-p3",
"tests/test_algebra.py::TestAlgebra::test_matmul",
"tests/test_algebra.py::TestAlgebra::test_broacast_to",
"tests/test_rec709.py::TestRec709::test_colors[yellow-color(--rec709",
"tests/test_algebra.py::TestAlgebra::test_round",
"tests/test_acescc.py::TestACESccProperties::test_red",
"tests/test_algebra.py::TestAlgebra::test_round_to_zero",
"tests/test_algebra.py::TestAlgebra::test_apply_two_inputs",
"tests/test_algebra.py::TestAlgebra::test_cross",
"tests/test_gamut.py::TestGamut::test_fit_in_place",
"tests/test_acescct.py::TestACEScct::test_colors[orange-color(--acescct",
"tests/test_algebra.py::TestAlgebra::test_fill_diagonal",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[green-color(rec2100-pq",
"tests/test_rec2100_hlg.py::Testrec2100HLGPoperties::test_r",
"tests/test_srgb.py::TestsRGBSerialize::test_colors[rgb(260",
"tests/test_srgb.py::TestsRGB::test_colors[indigo-color(srgb",
"tests/test_rec709.py::TestRec709::test_colors[red-color(--rec709",
"tests/test_display_p3.py::TestDisplayP3Properties::test_green",
"tests/test_algebra.py::TestAlgebra::test_vectorize",
"tests/test_rec709.py::TestRec709::test_colors[gray-color(--rec709",
"tests/test_srgb.py::TestsRGB::test_colors[#3838-color(srgb",
"tests/test_gamut.py::TestPointerGamut::test_hue_wrap",
"tests/test_gamut.py::TestHCTGamut::test_blue",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[black-color(prophoto-rgb",
"tests/test_acescct.py::TestACEScct::test_colors[blue-color(--acescct",
"tests/test_srgb.py::TestsRGBProperties::test_alpha",
"tests/test_srgb.py::TestsRGBSerialize::test_colors[rgb(none",
"tests/test_display_p3.py::TestDisplayP3::test_colors[blue-color(display-p3",
"tests/test_algebra.py::TestAlgebra::test_isnan",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[color(prophoto-rgb",
"tests/test_gamut.py::TestGamut::test_clip_in_place",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[red-color(rec2100-hlg",
"tests/test_acescc.py::TestACESccMisc::test_close_to_black",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[orange-color(rec2100-hlg",
"tests/test_srgb.py::TestsRGB::test_colors[color(srgb",
"tests/test_algebra.py::TestAlgebra::test_zeros",
"tests/test_srgb.py::TestsRGBProperties::test_green",
"tests/test_acescct.py::TestACEScct::test_colors[black-color(--acescct",
"tests/test_srgb.py::TestsRGB::test_colors[red-color(srgb",
"tests/test_acescc.py::TestACESccToACES2056_1::test_colors[color(--aces2065-1",
"tests/test_algebra.py::TestAlgebra::test_vectorize2",
"tests/test_acescct.py::TestACEScct::test_colors[red-color(--acescct",
"tests/test_rec2020.py::TestRec2020Properties::test_blue",
"tests/test_acescc.py::TestACESccProperties::test_alpha",
"tests/test_rec2100_hlg.py::Testrec2100HLGPoperties::test_alpha",
"tests/test_acescct.py::TestACEScct::test_colors[yellow-color(--acescct",
"tests/test_rec2020.py::TestRec2020Properties::test_alpha",
"tests/test_rec2020.py::TestRec2020Properties::test_red",
"tests/test_algebra.py::TestAlgebra::test_ilerp2d",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[white-color(prophoto-rgb",
"tests/test_acescct.py::TestACEScct::test_colors[violet-color(--acescct",
"tests/test_rec2100_pq.py::Testrec2100PQPoperties::test_alpha",
"tests/test_algebra.py::TestAlgebra::test_linspace",
"tests/test_rec2020.py::TestRec2020::test_colors[black-color(rec2020",
"tests/test_a98_rgb.py::TestA98RGBProperties::test_blue",
"tests/test_rec709.py::TestRec709Properties::test_alpha",
"tests/test_srgb.py::TestsRGB::test_colors[#383-color(srgb",
"tests/test_rec2020.py::TestRec2020::test_colors[indigo-color(rec2020",
"tests/test_acescc.py::TestACEScc::test_colors[green-color(--acescc",
"tests/test_display_p3.py::TestDisplayP3::test_colors[green-color(display-p3",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[color(rec2100-pq",
"tests/test_rec709.py::TestRec709::test_colors[blue-color(--rec709",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[gray-color(a98-rgb",
"tests/test_display_p3.py::TestDisplayP3::test_colors[indigo-color(display-p3",
"tests/test_srgb.py::TestsAchromatic::test_achromatic",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(none",
"tests/test_a98_rgb.py::TestA98RGBProperties::test_green",
"tests/test_algebra.py::TestAlgebra::test_diag",
"tests/test_acescc.py::TestACEScc::test_colors[blue-color(--acescc",
"tests/test_gamut.py::TestGamut::test_clip_undefined",
"tests/test_gamut.py::TestPointerGamut::test_pointer_boundary_max",
"tests/test_rec709.py::TestRec709::test_colors[indigo-color(--rec709",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(none,",
"tests/test_algebra.py::TestAlgebra::test_multiply",
"tests/test_gamut.py::TestGamut::test_fit_clip",
"tests/test_gamut.py::TestPointerGamut::test_pointer_boundary_mid",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(0%",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[blue-color(a98-rgb",
"tests/test_gamut.py::TestGamut::test_fit_self",
"tests/test_prophoto_rgb.py::TestProPhotoRGBProperties::test_green",
"tests/test_algebra.py::TestAlgebra::test_arange",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[black-color(rec2100-hlg",
"tests/test_algebra.py::TestAlgebra::test_full",
"tests/test_algebra.py::TestAlgebra::test_add",
"tests/test_algebra.py::TestAlgebra::test_interpolate_extrapolate",
"tests/test_gamut.py::TestGamut::test_hue_clipping",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[gray-color(prophoto-rgb",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[indigo-color(prophoto-rgb",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(0%",
"tests/test_algebra.py::TestAlgebra::test_clamp",
"tests/test_gamut.py::TestPointerGamut::test_out_of_pointer_gamut",
"tests/test_display_p3.py::TestDisplayP3::test_colors[orange-color(display-p3",
"tests/test_srgb.py::TestsRGBSerialize::test_colors[rgb(255",
"tests/test_algebra.py::TestAlgebra::test_zdiv",
"tests/test_algebra.py::TestAlgebra::test_lerp2d",
"tests/test_gamut.py::TestGamut::test_fit_method_to_string",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(50%,",
"tests/test_gamut.py::TestGamut::test_in_gamut",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[red-color(prophoto-rgb",
"tests/test_rec709.py::TestRec709Properties::test_green",
"tests/test_display_p3.py::TestDisplayP3::test_colors[violet-color(display-p3",
"tests/test_acescct.py::TestACEScct::test_colors[indigo-color(--acescct",
"tests/test_rec709.py::TestRec709::test_colors[black-color(--rec709",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(128,",
"tests/test_algebra.py::TestAlgebra::test_flatiter",
"tests/test_gamut.py::TestGamut::test_hdr_extreme_high",
"tests/test_algebra.py::TestAlgebra::test_ones",
"tests/test_gamut.py::TestGamut::test_fit",
"tests/test_display_p3.py::TestDisplayP3::test_colors[red-color(display-p3",
"tests/test_acescc.py::TestACEScc::test_colors[orange-color(--acescc",
"tests/test_rec2100_pq.py::Testrec2100PQPoperties::test_g",
"tests/test_algebra.py::TestAlgebra::test_shape",
"tests/test_acescc.py::TestACEScc::test_colors[white-color(--acescc",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[gray-color(rec2100-hlg",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(0,",
"tests/test_prophoto_rgb.py::TestProPhotoRGBProperties::test_blue",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[violet-color(rec2100-hlg",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[white-color(rec2100-hlg",
"tests/test_rec2100_hlg.py::Testrec2100HLGPoperties::test_b",
"tests/test_algebra.py::TestAlgebra::test_subtraction",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[gray-color(rec2100-pq",
"tests/test_algebra.py::TestAlgebra::test_round_to_inf",
"tests/test_algebra.py::test_pprint",
"tests/test_srgb.py::TestsRGB::test_colors[rgba(0",
"tests/test_gamut.py::TestPointerGamut::test_fit_pointer_gamut_too_light",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[white-color(a98-rgb",
"tests/test_acescct.py::TestACEScct::test_colors[color(--acescct",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[violet-color(prophoto-rgb",
"tests/test_algebra.py::TestAlgebra::test_ilerp",
"tests/test_algebra.py::TestAlgebra::test_solve",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[orange-color(prophoto-rgb",
"tests/test_srgb.py::TestsRGBProperties::test_red",
"tests/test_rec2100_hlg.py::Testrec2100HLGPoperties::test_g",
"tests/test_rec709.py::TestRec709::test_colors[white-color(--rec709",
"tests/test_algebra.py::TestAlgebra::test_broadcast_reset",
"tests/test_algebra.py::TestAlgebra::test_inner",
"tests/test_display_p3.py::TestDisplayP3Properties::test_alpha",
"tests/test_display_p3.py::TestDisplayP3Properties::test_red",
"tests/test_srgb.py::TestsRGBSerialize::test_colors[rgb(0",
"tests/test_algebra.py::TestAlgebra::test_transpose",
"tests/test_rec709.py::TestRec709Properties::test_blue",
"tests/test_acescct.py::TestACEScct::test_colors[green-color(--acescct",
"tests/test_gamut.py::TestGamut::test_hdr_extreme_low",
"tests/test_srgb.py::TestsRGB::test_colors[white-color(srgb",
"tests/test_algebra.py::TestAlgebra::test_round_to_full",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[violet-color(rec2100-pq",
"tests/test_srgb.py::TestsRGB::test_colors[#ee82ee-color(srgb",
"tests/test_a98_rgb.py::TestA98RGB::test_colors[red-color(a98-rgb",
"tests/test_algebra.py::TestAlgebra::test_extract_columns",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(0,",
"tests/test_gamut.py::TestGamut::test_sdr_extremes_low",
"tests/test_display_p3.py::TestDisplayP3Properties::test_blue",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(128deg,",
"tests/test_rec2020.py::TestRec2020::test_colors[yellow-color(rec2020",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[blue-color(rec2100-pq",
"tests/test_prophoto_rgb.py::TestProPhotoRGB::test_colors[green-color(prophoto-rgb",
"tests/test_gamut.py::TestGamut::test_clip_other_gamut",
"tests/test_gamut.py::TestPointerGamut::test_pointer_boundary_too_light",
"tests/test_srgb.py::TestsRGB::test_colors[yellow-color(srgb",
"tests/test_acescc.py::TestACEScc::test_colors[red-color(--acescc",
"tests/test_rec2020.py::TestRec2020::test_colors[color(rec2020",
"tests/test_algebra.py::TestAlgebra::test_outer",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[black-color(rec2100-pq",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[indigo-color(rec2100-hlg",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[color(rec2100-hlg",
"tests/test_srgb.py::TestsRGB::test_colors[gray-color(srgb",
"tests/test_display_p3.py::TestDisplayP3::test_colors[color(display-p3",
"tests/test_algebra.py::TestAlgebra::test_broadcast",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[yellow-color(rec2100-hlg",
"tests/test_rec2020.py::TestRec2020::test_colors[gray-color(rec2020",
"tests/test_rec2100_pq.py::TestRec2100PQ::test_colors[indigo-color(rec2100-pq",
"tests/test_rec2100_hlg.py::TestRec2100HLG::test_colors[green-color(rec2100-hlg",
"tests/test_algebra.py::TestAlgebra::test_interpolate",
"tests/test_gamut.py::TestGamut::test_out_of_gamut_other_space",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(128",
"tests/test_prophoto_rgb.py::TestProPhotoRGBProperties::test_alpha",
"tests/test_srgb.py::TestsRGB::test_colors[rgb(50%",
"tests/test_a98_rgb.py::TestA98RGBProperties::test_alpha",
"tests/test_acescc.py::TestACEScc::test_colors[gray-color(--acescc",
"tests/test_gamut.py::TestHCTGamut::test_inside_but_high_chroma"
] |
facelessuser/coloraide | 220 | facelessuser__coloraide-220 | ['219'] | 77492e1c6bdd7178a2884a25b37bb4c79db7cdf7 | diff --git a/coloraide/color.py b/coloraide/color.py
index 512b58e05..cc14197ea 100644
--- a/coloraide/color.py
+++ b/coloraide/color.py
@@ -54,8 +54,8 @@
from .filters.w3c_filter_effects import Sepia, Brightness, Contrast, Saturate, Opacity, HueRotate, Grayscale, Invert
from .filters.cvd import Protan, Deutan, Tritan
from .interpolate import Interpolator, Interpolate
-from .interpolate.bezier import InterpolateBezier
-from .interpolate.piecewise import InterpolatePiecewise
+from .interpolate.bspline import BSpline
+from .interpolate.linear import Linear
from .types import Plugin
from typing import overload, Union, Sequence, Dict, List, Optional, Any, cast, Callable, Tuple, Type, Mapping
@@ -751,7 +751,7 @@ def interpolate(
mixing occurs.
"""
- return interpolate.get_interpolator(
+ return interpolate.interpolator(
method,
cls,
colors=colors,
@@ -943,7 +943,7 @@ def set( # noqa: A003
WCAG21Contrast(),
# Interpolation
- InterpolateBezier(),
- InterpolatePiecewise()
+ Linear(),
+ BSpline()
]
)
diff --git a/coloraide/interpolate/__init__.py b/coloraide/interpolate/__init__.py
index e58556926..553614298 100644
--- a/coloraide/interpolate/__init__.py
+++ b/coloraide/interpolate/__init__.py
@@ -58,7 +58,7 @@ class Interpolator(metaclass=ABCMeta):
def __init__(
self,
coordinates: List[Vector],
- names: Sequence[str],
+ channel_names: Sequence[str],
create: Type['Color'],
easings: List[Optional[Callable[..., float]]],
stops: Dict[int, float],
@@ -76,7 +76,7 @@ def __init__(
self.easings = easings
self.coordinates = coordinates
self.length = len(self.coordinates)
- self.names = names
+ self.channel_names = channel_names
self.create = create
self.progress = progress
self.space = space
@@ -228,32 +228,20 @@ class Interpolate(Plugin, metaclass=ABCMeta):
NAME = ""
@abstractmethod
- def get_interpolator(self) -> Type[Interpolator]:
- """Get the interpolator object."""
-
- def interpolate(
+ def interpolator(
self,
+ coordinates: List[Vector],
+ channel_names: Sequence[str],
create: Type['Color'],
- colors: Sequence[Union[ColorInput, stop, Callable[..., float]]],
- space: Optional[str],
- out_space: Optional[str],
+ easings: List[Optional[Callable[..., float]]],
+ stops: Dict[int, float],
+ space: str,
+ out_space: str,
progress: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
- hue: str,
premultiplied: bool,
**kwargs: Any
) -> Interpolator:
- """Return an interpolator object."""
-
- return color_interpolator(
- self.get_interpolator(),
- create,
- colors,
- space,
- out_space,
- progress,
- hue,
- premultiplied
- )
+ """Get the interpolator object."""
def calc_stops(stops: Dict[int, float], count: int) -> Dict[int, float]:
@@ -449,8 +437,8 @@ def normalize_hue(
return color2, offset
-def color_interpolator(
- plugin: Type[Interpolator],
+def interpolator(
+ interpolator: str,
create: Type['Color'],
colors: Sequence[Union[ColorInput, stop, Callable[..., float]]],
space: Optional[str],
@@ -460,7 +448,12 @@ def color_interpolator(
premultiplied: bool,
**kwargs: Any
) -> Interpolator:
- """Bezier interpolation."""
+ """Get desired blend mode."""
+
+ try:
+ plugin = create.INTERPOLATE_MAP[interpolator]
+ except KeyError:
+ raise ValueError("'{}' is not a recognized interpolator".format(interpolator))
# Construct piecewise interpolation object
stops = {} # type: Any
@@ -527,7 +520,7 @@ def color_interpolator(
stops = calc_stops(stops, i)
# Send the interpolation list along with the stop map to the Piecewise interpolator
- return plugin(
+ return plugin.interpolator(
coords,
current._space.channels,
create,
@@ -539,24 +532,3 @@ def color_interpolator(
premultiplied,
**kwargs
)
-
-
-def get_interpolator(
- interpolator: str,
- create: Type['Color'],
- colors: Sequence[Union[ColorInput, stop, Callable[..., float]]],
- space: Optional[str],
- out_space: Optional[str],
- progress: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
- hue: str,
- premultiplied: bool,
- **kwargs: Any
-) -> Interpolator:
- """Get desired blend mode."""
-
- try:
- i = create.INTERPOLATE_MAP[interpolator]
- except KeyError:
- raise ValueError("'{}' is not a recognized interpolator".format(interpolator))
-
- return i.interpolate(create, colors, space, out_space, progress, hue, premultiplied, **kwargs)
diff --git a/coloraide/interpolate/bezier.py b/coloraide/interpolate/bezier.py
deleted file mode 100644
index 3b82335aa..000000000
--- a/coloraide/interpolate/bezier.py
+++ /dev/null
@@ -1,108 +0,0 @@
-"""Bezier interpolation."""
-from .. import algebra as alg
-from ..interpolate import Interpolator, Interpolate
-from ..types import Vector
-from typing import Optional, Callable, Mapping, List, Union, Type
-
-
-def binomial_row(n: int) -> List[int]:
- """
- Binomial row.
-
- Return row in Pascal's triangle.
- """
-
- row = [1, 1]
- for _ in range(n - 1):
- r = [1]
- x = 0
- for x in range(1, len(row)):
- r.append(row[x] + row[x - 1])
- r.append(row[x])
- row = r
- return row
-
-
-def handle_undefined(coords: Vector) -> Vector:
- """Handle null values."""
-
- backfill = None
- for x in range(1, len(coords)):
- a = coords[x - 1]
- b = coords[x]
- if alg.is_nan(a) and not alg.is_nan(b):
- coords[x - 1] = b
- elif alg.is_nan(b) and not alg.is_nan(a):
- coords[x] = a
- elif alg.is_nan(a) and alg.is_nan(b):
- # Multiple undefined values, mark the start
- backfill = x - 1
- continue
-
- # Replace all undefined values that occurred prior to
- # finding the current defined value
- if backfill is not None:
- coords[backfill:x - 1] = [b] * (x - 1 - backfill)
- backfill = None
-
- return coords
-
-
-class InterpolatorBezier(Interpolator):
- """Interpolate Bezier."""
-
- def interpolate(
- self,
- easing: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
- point: float,
- index: int
- ) -> Vector:
- """Interpolate."""
-
- # Bezier interpolates against all colors, so make point absolute
- piece = 1 / (self.length - 1)
- first = (index - 1) * piece
- last = index * piece
-
- # Get row from Pascal's Triangle
- n = self.length - 1
- row = binomial_row(n)
-
- # Use Bezier interpolation of all color for each channel
- channels = []
- for i, coords in enumerate(zip(*self.coordinates)):
-
- # Do we have an easing function, or mapping with a channel easing function?
- progress = None
- name = self.names[i]
- if isinstance(easing, Mapping):
- progress = easing.get(name)
- if progress is None:
- progress = easing.get('all')
- else:
- progress = easing
-
- # Apply easing and scale properly between the colors
- t = alg.clamp(point if progress is None else progress(point), 0.0, 1.0)
- t = t * (last - first) + first
-
- # Find new points using a bezier curve, but ensure we handle undefined
- # values in a sane way.
- x = 1 - t
- s = 0.0
- for j, c in enumerate(handle_undefined(list(coords)), 0):
- s += row[j] * (x ** (n - j)) * (t ** j) * c
- channels.append(s)
-
- return channels
-
-
-class InterpolateBezier(Interpolate):
- """Bezier interpolation plugin."""
-
- NAME = "bezier"
-
- def get_interpolator(self) -> Type[Interpolator]:
- """Return the Bezier interpolator."""
-
- return InterpolatorBezier
diff --git a/coloraide/interpolate/bspline.py b/coloraide/interpolate/bspline.py
new file mode 100644
index 000000000..281c9b19d
--- /dev/null
+++ b/coloraide/interpolate/bspline.py
@@ -0,0 +1,149 @@
+"""B-Spline interpolation."""
+from .. import algebra as alg
+from ..interpolate import Interpolator, Interpolate
+from ..types import VectorLike, Vector
+from typing import Optional, Callable, Mapping, List, Union, Sequence, Dict, Any, Type, TYPE_CHECKING
+
+if TYPE_CHECKING: # pragma: no cover
+ from ..color import Color
+
+
+def handle_undefined(coords: VectorLike) -> Vector:
+ """Handle null values."""
+
+ backfill = None
+ adjusted = list(coords)
+ for x in range(1, len(adjusted)):
+ a = adjusted[x - 1]
+ b = adjusted[x]
+ if alg.is_nan(a) and not alg.is_nan(b):
+ adjusted[x - 1] = b
+ elif alg.is_nan(b) and not alg.is_nan(a):
+ adjusted[x] = a
+ elif alg.is_nan(a) and alg.is_nan(b):
+ # Multiple undefined values, mark the start
+ backfill = x - 1
+ continue
+
+ # Replace all undefined values that occurred prior to
+ # finding the current defined value
+ if backfill is not None:
+ adjusted[backfill:x - 1] = [b] * (x - 1 - backfill)
+ backfill = None
+
+ return adjusted
+
+
+class InterpolatorBspline(Interpolator):
+ """Interpolate with B-spline."""
+
+ def __init__(
+ self,
+ coordinates: List[Vector],
+ names: Sequence[str],
+ create: Type['Color'],
+ easings: List[Optional[Callable[..., float]]],
+ stops: Dict[int, float],
+ space: str,
+ out_space: str,
+ progress: Optional[Union[Callable[..., float], Mapping[str, Callable[..., float]]]],
+ premultiplied: bool,
+ **kwargs: Any
+ ):
+ """Initialize."""
+
+ super().__init__(
+ coordinates,
+ names,
+ create,
+ easings,
+ stops,
+ space,
+ out_space,
+ progress,
+ premultiplied,
+ **kwargs
+ )
+
+ # Process undefined values
+ self.coordinates = [list(x) for x in zip(*[handle_undefined(c) for c in zip(*self.coordinates)])]
+
+ # We cannot interpolate all the way to `coord[0]` and `coord[-1]` without additional points
+ # to coax the curve through the end points. Generate a point at both ends so that we can
+ # properly evaluate the spline.
+ c1 = self.coordinates[1]
+ c2 = self.coordinates[-2]
+ self.coordinates.insert(0, [2 * a - b for a, b in zip(self.coordinates[0], c1)])
+ self.coordinates.append([2 * a - b for a, b in zip(self.coordinates[-1], c2)])
+
+ def interpolate(
+ self,
+ easing: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
+ point: float,
+ index: int
+ ) -> Vector:
+ """Interpolate."""
+
+ # Use Bezier interpolation of all color for each channel
+ channels = []
+ for i, coords in enumerate(zip(*self.coordinates)):
+
+ # Do we have an easing function, or mapping with a channel easing function?
+ progress = None
+ name = self.channel_names[i]
+ if isinstance(easing, Mapping):
+ progress = easing.get(name)
+ if progress is None:
+ progress = easing.get('all')
+ else:
+ progress = easing
+
+ # Apply easing and scale properly between the colors
+ t = alg.clamp(point if progress is None else progress(point), 0.0, 1.0)
+ t2 = t ** 2
+ t3 = t2 * t
+
+ p0, p1, p2, p3 = coords[index - 1:index + 3]
+ channels.append(
+ (
+ ((1 - t) ** 3) * p0 + # B0
+ (3 * t3 - 6 * t2 + 4) * p1 + # B1
+ (-3 * t3 + 3 * t2 + 3 * t + 1) * p2 + # B2
+ t3 * p3 # B3
+ ) / 6
+ )
+
+ return channels
+
+
+class BSpline(Interpolate):
+ """B-spline interpolation plugin."""
+
+ NAME = "b-spline"
+
+ def interpolator(
+ self,
+ coordinates: List[Vector],
+ channel_names: Sequence[str],
+ create: Type['Color'],
+ easings: List[Optional[Callable[..., float]]],
+ stops: Dict[int, float],
+ space: str,
+ out_space: str,
+ progress: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
+ premultiplied: bool,
+ **kwargs: Any
+ ) -> Interpolator:
+ """Return the B-spline interpolator."""
+
+ return InterpolatorBspline(
+ coordinates,
+ channel_names,
+ create,
+ easings,
+ stops,
+ space,
+ out_space,
+ progress,
+ premultiplied
+ )
diff --git a/coloraide/interpolate/piecewise.py b/coloraide/interpolate/linear.py
similarity index 59%
rename from coloraide/interpolate/piecewise.py
rename to coloraide/interpolate/linear.py
index 7896f09b3..cf1c1a7cc 100644
--- a/coloraide/interpolate/piecewise.py
+++ b/coloraide/interpolate/linear.py
@@ -2,11 +2,14 @@
from .. import algebra as alg
from ..interpolate import Interpolator, Interpolate
from ..types import Vector
-from typing import Optional, Callable, Mapping, Union, Type
+from typing import Optional, Callable, Mapping, Union, Any, Type, Sequence, List, Dict, TYPE_CHECKING
+if TYPE_CHECKING: # pragma: no cover
+ from ..color import Color
-class InterpolatorPiecewise(Interpolator):
- """Interpolate multiple ranges of colors."""
+
+class InterpolatorLinear(Interpolator):
+ """Interpolate multiple ranges of colors using linear, Piecewise interpolation."""
def interpolate(
self,
@@ -35,7 +38,7 @@ def interpolate(
else:
# Do we have an easing function, or mapping with a channel easing function?
progress = None
- name = self.names[i]
+ name = self.channel_names[i]
if isinstance(easing, Mapping):
progress = easing.get(name)
if progress is None:
@@ -53,12 +56,34 @@ def interpolate(
return channels
-class InterpolatePiecewise(Interpolate):
- """Linear piecewise interpolation plugin."""
+class Linear(Interpolate):
+ """Linear interpolation plugin."""
NAME = "linear"
- def get_interpolator(self) -> Type[Interpolator]:
- """Return the linear piecewise interpolator."""
+ def interpolator(
+ self,
+ coordinates: List[Vector],
+ channel_names: Sequence[str],
+ create: Type['Color'],
+ easings: List[Optional[Callable[..., float]]],
+ stops: Dict[int, float],
+ space: str,
+ out_space: str,
+ progress: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
+ premultiplied: bool,
+ **kwargs: Any
+ ) -> Interpolator:
+ """Return the linear interpolator."""
- return InterpolatorPiecewise
+ return InterpolatorLinear(
+ coordinates,
+ channel_names,
+ create,
+ easings,
+ stops,
+ space,
+ out_space,
+ progress,
+ premultiplied
+ )
diff --git a/docs/src/markdown/about/changelog.md b/docs/src/markdown/about/changelog.md
index 85ef4fc31..c43a93ea7 100644
--- a/docs/src/markdown/about/changelog.md
+++ b/docs/src/markdown/about/changelog.md
@@ -2,7 +2,8 @@
## 1.0rc2
-- **NEW**: Bezier interpolation now supports hue fix-ups: `shorter`, `longer`, `increasing`, `decreasing`,
+- **NEW**: Bezier interpolation dropped for B-spline which provides much better interpolation.
+- **NEW**: All new interpolation methods now supports hue fix-ups: `shorter`, `longer`, `increasing`, `decreasing`,
and `specified`.
- **NEW**: Interpolation is now exposed as a plugin to allow for expansion.
diff --git a/docs/src/markdown/about/releases/1.0.md b/docs/src/markdown/about/releases/1.0.md
index 3b6e2c801..b59592bf1 100644
--- a/docs/src/markdown/about/releases/1.0.md
+++ b/docs/src/markdown/about/releases/1.0.md
@@ -270,7 +270,7 @@ All of this makes for a less confusing experience when using interpolation. Addi
the logic allowing us to even add a new interpolation method!
```playground
-Color.interpolate(['red', 'blue', 'green', 'orange'], method='bezier')
+Color.interpolate(['red', 'blue', 'green', 'orange'], method='b-spline')
```
## Color Space Filters
diff --git a/docs/src/markdown/images/bezier-interpolation.png b/docs/src/markdown/images/bezier-interpolation.png
deleted file mode 100644
index 3bc297773..000000000
Binary files a/docs/src/markdown/images/bezier-interpolation.png and /dev/null differ
diff --git a/docs/src/markdown/images/bspline-interpolation.png b/docs/src/markdown/images/bspline-interpolation.png
new file mode 100644
index 000000000..664dc04e7
Binary files /dev/null and b/docs/src/markdown/images/bspline-interpolation.png differ
diff --git a/docs/src/markdown/interpolation.md b/docs/src/markdown/interpolation.md
index 917787e51..2e33afa79 100644
--- a/docs/src/markdown/interpolation.md
+++ b/docs/src/markdown/interpolation.md
@@ -75,25 +75,24 @@ Color.interpolate(['black', 'red', 'white'])
This approach generally works well, but since the placement of colors may not be in a straight line, you will often
have pivot points and the transition may not be quite as smooth.
-## Bezier Interpolation
+## B-Spline Interpolation
-Not all interpolation methods are linear, and ColorAide implements one such approach called Bezier interpolation.
-Instead of trying to draw a straight line or series of straight lines through a series of points, a Bezier curve will
-essentially draw a line that roughly follows the shape of the points. It is not guarantee that this curve will pass
+Not all interpolation methods are linear, and ColorAide implements one such approach called B-spline interpolation.
+Instead of trying to draw a straight line or series of straight lines through a series of points, a B-Spline curve will
+essentially draw a line that roughly follows the shape of the points. It is not guaranteed that this curve will pass
through all the points, but each point will have influence on the curvature of the line. This allows for smoother
transitions across multiple colors.
-
+
-By simply passing the `method='bezier`, we can interpolate using this method. Below we can see the difference between
-linear and the Bezier method. Notice in the linear interpolation the pivot point where the gradient fully transitions to
-purple and then begins the transition to green the linear example the the point. The Bezier curve doesn't have the
-pivot point as the curve bends towards purple smoothly, without passing directly through it, and then away towards
-green.
+By simply passing the `method='b-spline`, we can interpolate using this method. Below we can see the difference between
+linear and the B-spline method. Notice in the linear interpolation the pivot point where the gradient fully transitions
+to purple and then begins the transition to green. The B-spline curve doesn't have the pivot point as the curve bends
+towards purple smoothly, without passing directly through it at a harsh angle.
```playground
Color.interpolate(['orange', 'purple', 'green'])
-Color.interpolate(['orange', 'purple', 'green'], method='bezier')
+Color.interpolate(['orange', 'purple', 'green'], method='b-spline')
```
## Hue Interpolation
@@ -123,7 +122,7 @@ To help visualize the different hue methods, consider the following evaluation b
!!! tip "Interpolating Multiple Colors"
The algorithm has been tweaked in order to calculate fix-ups of multiple hues such that they are all relative to
- each other. This is a requirement for interpolation methods such as Bezier that evaluate all hues at the same time
+ each other. This is a requirement for interpolation methods such as B-spline that evaluate all hues at the same time
as opposed to the linear, piecewise interpolation that only evaluates two hues at any given time.
=== "shorter"
@@ -261,7 +260,7 @@ i = Color.interpolate(
## Easing Functions
-When interpolating, whether it using linear interpolation or something like Bezier interpolation, the transitioning of
+When interpolating, whether it using linear interpolation or something like B-Spline interpolation, the transitioning of
a color from one to another is done in linear time. For example, if you are translating between 2 colors and you request
the `#!py3 0.5` point in the interpolation process, you will get a color exactly in the middle of the transition. With
easing functions, you can completely change the progress in relation to time by compressing the rate of change at the
@@ -379,7 +378,7 @@ parameter or even a different interpolation method via `method`. `mix` accepts a
`interpolate`, though concepts like [stops and hints](#color-stops-and-hints) are not allowed with mixing.
```playground
-Color("red").mix(Color("blue"), space="hsl", method='bezier')
+Color("red").mix(Color("blue"), space="hsl", method='b-spline')
```
Mix can also accept a string and will create the color for us which is great if we don't need to work with the second
@@ -486,11 +485,11 @@ specifying the method via the `delta_e` parameter.
)
```
-And much like [`interpolate`](#linear-interpolation), we can use [`stops` and `hints`](#color-stops-and-hints) and of
-the supported `interpolate` parameters as well.
+And much like [`interpolate`](#linear-interpolation), we can use [`stops` and `hints`](#color-stops-and-hints) and any
+of the other supported `interpolate` features as well.
```playground
-Color.steps(['orange', stop('purple', 0.25), 'green'], method='bezier', steps=10)
+Color.steps(['orange', stop('purple', 0.25), 'green'], method='b-spline', steps=10)
```
## Undefined/NaN Handling {#null-handling}
@@ -523,8 +522,8 @@ When performing linear interpolation, where only two color's channels are ever b
if one color's channel has a `NaN`, the other color's channel will be used as the result. If both colors have a `NaN`
for the same channel, then `NaN` will be returned.
-!!! tip "NaN Handling in Bezier Interpolation"
- This logic is similar for things like Bezier interpolation, but will be extended as Bezier interpolation can
+!!! tip "NaN Handling in B-Spline Interpolation"
+ This logic is similar for things like B-spline interpolation, but will be extended as B-spline interpolation can
evaluate multiple colors at a time. For instance if interpolating a single channel across three colors, `NaN` must
be resolved simultaneously across all three colors.
diff --git a/docs/src/markdown/plugins/interpolate.md b/docs/src/markdown/plugins/interpolate.md
index 7d54e27da..402ce6d8d 100644
--- a/docs/src/markdown/plugins/interpolate.md
+++ b/docs/src/markdown/plugins/interpolate.md
@@ -16,7 +16,19 @@ class Interpolate(Plugin, metaclass=ABCMeta):
NAME = ""
@abstractmethod
- def get_interpolator(self) -> Type[Interpolator]:
+ def interpolator(
+ self,
+ coordinates: List[Vector],
+ channel_names: Sequence[str],
+ create: Type['Color'],
+ easings: List[Optional[Callable[..., float]]],
+ stops: Dict[int, float],
+ space: str,
+ out_space: str,
+ progress: Optional[Union[Mapping[str, Callable[..., float]], Callable[..., float]]],
+ premultiplied: bool,
+ **kwargs: Any
+ ) -> Interpolator:
"""Get the interpolator object."""
```
@@ -29,7 +41,7 @@ color.interpolate(colors, method=NAME)
```
In general, the `Interpolate` plugin is mainly a wrapper to ensure the interpolation setup uses an appropriate
-`Interpolator` object which does the actual work. An interpolation plugin should derive their `Interpolate` class from
+`Interpolator` object which does the actual work. An interpolation plugin should derive their `Interpolator` class from
`coloraide.interpolate.Interpolator`. While we won't show all the methods of the class, we will show the one function
that must be defined.
diff --git a/tools/interp_diagram.py b/tools/interp_diagram.py
index 1447d541e..10aba5d05 100644
--- a/tools/interp_diagram.py
+++ b/tools/interp_diagram.py
@@ -18,7 +18,6 @@
except ImportError:
from coloraide.everything import ColorAll as Color
from tools.slice_diagram import plot_slice # noqa: E402
-from coloraide.util import fmt_float # noqa: E402
from coloraide.spaces import Cylindrical # noqa: E402
| diff --git a/tests/test_interpolation.py b/tests/test_interpolation.py
index 197cba31f..eacc0a3c1 100644
--- a/tests/test_interpolation.py
+++ b/tests/test_interpolation.py
@@ -336,23 +336,23 @@ def test_interpolate(self):
self.assertColorEqual(Color.interpolate(['red', 'blue'], space="srgb")(0.25), Color("srgb", [0.75, 0, 0.25]))
self.assertColorEqual(Color.interpolate(['red', 'blue'], space="srgb")(0), Color("srgb", [1, 0, 0]))
- def test_interpolate_bezier(self):
- """Test interpolation bezier."""
+ def test_interpolate_bspline(self):
+ """Test interpolation B-spline."""
self.assertColorEqual(
- Color.interpolate(['red', 'blue'], space="srgb", method="bezier")(1), Color("srgb", [0, 0, 1])
+ Color.interpolate(['red', 'blue'], space="srgb", method="b-spline")(1), Color("srgb", [0, 0, 1])
)
self.assertColorEqual(
- Color.interpolate(['red', 'blue'], space="srgb", method="bezier")(0.75), Color("srgb", [0.25, 0, 0.75])
+ Color.interpolate(['red', 'blue'], space="srgb", method="b-spline")(0.75), Color("srgb", [0.25, 0, 0.75])
)
self.assertColorEqual(
- Color.interpolate(['red', 'blue'], space="srgb", method="bezier")(0.5), Color("srgb", [0.5, 0, 0.5])
+ Color.interpolate(['red', 'blue'], space="srgb", method="b-spline")(0.5), Color("srgb", [0.5, 0, 0.5])
)
self.assertColorEqual(
- Color.interpolate(['red', 'blue'], space="srgb", method="bezier")(0.25), Color("srgb", [0.75, 0, 0.25])
+ Color.interpolate(['red', 'blue'], space="srgb", method="b-spline")(0.25), Color("srgb", [0.75, 0, 0.25])
)
self.assertColorEqual(
- Color.interpolate(['red', 'blue'], space="srgb", method="bezier")(0), Color("srgb", [1, 0, 0])
+ Color.interpolate(['red', 'blue'], space="srgb", method="b-spline")(0), Color("srgb", [1, 0, 0])
)
def test_interpolate_channel(self):
@@ -363,12 +363,12 @@ def test_interpolate_channel(self):
Color('rgb(119.63 0 0 / 0.875)')
)
- def test_interpolate_channel_bezier(self):
+ def test_interpolate_channel_bspline(self):
"""Test interpolating a specific channel differently."""
self.assertColorEqual(
Color.interpolate(
- ['red', Color('blue').set('alpha', 0)], progress={'alpha': lambda t: t ** 3}, method='bezier'
+ ['red', Color('blue').set('alpha', 0)], progress={'alpha': lambda t: t ** 3}, method='b-spline'
)(0.5),
Color('rgb(119.63 0 0 / 0.875)')
)
@@ -425,11 +425,12 @@ def test_interpolate_input_piecewise(self):
Color.interpolate(['red', stop('blue', 0.5)], space="srgb")(0.5), Color("srgb", [0, 0, 1])
)
- def test_interpolate_input_bezier(self):
+ def test_interpolate_input_bspline(self):
"""Test interpolation with piecewise."""
self.assertColorEqual(
- Color.interpolate(['red', stop('blue', 0.5)], space="srgb", method='bezier')(0.5), Color("srgb", [0, 0, 1])
+ Color.interpolate(['red', stop('blue', 0.5)], space="srgb", method='b-spline')(0.5),
+ Color("srgb", [0, 0, 1])
)
def test_interpolate_stop(self):
@@ -442,11 +443,11 @@ def test_interpolate_stop(self):
Color.interpolate([stop('red', 0.6), 'blue'], space="srgb")(0.7), Color('rgb(191.25 0 63.75)')
)
- def test_interpolate_stop_bezier(self):
+ def test_interpolate_stop_bspline(self):
"""Test interpolation with piecewise."""
self.assertColorEqual(
- Color.interpolate([stop('red', 0.6), 'blue'], space="srgb", method='bezier')(0.5), Color('red')
+ Color.interpolate([stop('red', 0.6), 'blue'], space="srgb", method='b-spline')(0.5), Color('red')
)
def test_interpolate_space(self):
@@ -478,12 +479,12 @@ def test_interpolate_piecewise(self):
self.assertColorEqual(func(-0.1), Color('rgb(255 255 255)'))
self.assertColorEqual(func(1.1), Color('rgb(0 0 0)'))
- def test_interpolate_multi_bezier(self):
- """Test multiple inputs for bezier interpolation."""
+ def test_interpolate_multi_bspline(self):
+ """Test multiple inputs for B-spline interpolation."""
- func = Color.interpolate(['white', 'red', 'black'], method='bezier')
+ func = Color.interpolate(['white', 'red', 'black'], method='b-spline')
self.assertColorEqual(func(0), Color('white'))
- self.assertColorEqual(func(0.5), Color('rgb(180.88 83.809 71.264)'))
+ self.assertColorEqual(func(0.5), Color('rgb(205.87 72.188 58.186)'))
self.assertColorEqual(func(1), Color('black'))
self.assertColorEqual(func(-0.1), Color('rgb(255 255 255)'))
self.assertColorEqual(func(1.1), Color('rgb(0 0 0)'))
@@ -639,11 +640,12 @@ def test_steps_input_piecewise(self):
Color.steps(['red', stop('blue', 0.5)], space="srgb", steps=5)[2], Color("srgb", [0, 0, 1])
)
- def test_steps_input_bezier(self):
- """Test steps with bezier."""
+ def test_steps_input_bspline(self):
+ """Test steps with B-spline."""
self.assertColorEqual(
- Color.steps(['red', stop('blue', 0.5)], space="srgb", steps=5, method='bezier')[2], Color("srgb", [0, 0, 1])
+ Color.steps(['red', stop('blue', 0.5)], space="srgb", steps=5, method='b-spline')[2],
+ Color("srgb", [0, 0, 1])
)
def test_steps_multi(self):
@@ -892,11 +894,11 @@ def test_too_few_colors_linear(self):
with self.assertRaises(ValueError):
Color.interpolate(['green', lambda t: t * 3])
- def test_too_few_colors_bezier(self):
- """Test too few colors during bezier interpolation."""
+ def test_too_few_colors_bspline(self):
+ """Test too few colors during B-spline interpolation."""
with self.assertRaises(ValueError):
- Color.interpolate(['green', lambda t: t * 3], method='bezier')
+ Color.interpolate(['green', lambda t: t * 3], method='b-spline')
def test_bad_method(self):
"""Test bad interpolation method."""
@@ -910,68 +912,68 @@ def test_bad_easing(self):
with self.assertRaises(ValueError):
Color.interpolate([lambda t: t * 3, 'green'])
- def test_bad_color_input_bezier(self):
- """Test bad color easing bezier."""
+ def test_bad_color_input_bspline(self):
+ """Test bad color easing B-spline."""
with self.assertRaises(ValueError):
- Color.interpolate([lambda t: t * 3, 'green'], method='bezier')
+ Color.interpolate([lambda t: t * 3, 'green'], method='b-spline')
- def test_bezier_all_none(self):
- """Test multiple bezier inputs with the same channel all none."""
+ def test_bspline_all_none(self):
+ """Test multiple B-spline inputs with the same channel all none."""
self.assertColorEqual(
Color.interpolate(
['Color(srgb 1 none 0.5)', 'Color(srgb 0.1 none 0.7)', 'Color(srgb 0.2 none 0.9)'],
space='srgb',
- method='bezier'
+ method='b-spline'
)(0.5),
- Color('rgb(89.25 none 178.5)')
+ Color('rgb(68 none 178.5)')
)
- def test_bezier_most_none(self):
- """Test multiple bezier inputs with the same channel with most none."""
+ def test_bspline_most_none(self):
+ """Test multiple B-spline inputs with the same channel with most none."""
self.assertColorEqual(
Color.interpolate(
['Color(srgb 1 none 0.5)', 'Color(srgb 0.1 none 0.7)', 'Color(srgb 0.2 0.8 0.9)'],
space='srgb',
- method='bezier'
+ method='b-spline'
)(0.5),
- Color('rgb(89.25 204 178.5)')
+ Color('rgb(68 204 178.5)')
)
- def test_bezier_none_after(self):
- """Test multiple bezier inputs with the same channel with most none but not none at the start."""
+ def test_bspline_none_after(self):
+ """Test multiple B-spline inputs with the same channel with most none but not none at the start."""
self.assertColorEqual(
Color.interpolate(
['Color(srgb 1 0.8 0.5)', 'Color(srgb 0.1 none 0.7)', 'Color(srgb 0.2 none 0.9)'],
space='srgb',
- method='bezier'
+ method='b-spline'
)(0.5),
- Color('rgb(89.25 204 178.5)')
+ Color('rgb(68 204 178.5)')
)
- def test_bezier_cylindrical(self):
- """Test bezier with a cylindrical space."""
+ def test_bspline_cylindrical(self):
+ """Test B-spline with a cylindrical space."""
self.assertColorEqual(
Color.interpolate(
['hsl(250 50% 30%)', 'hsl(none 0% 10%)', 'hsl(120 75% 75%)'],
space='hsl',
- method='bezier'
+ method='b-spline'
)(0.75),
- Color('hsl(176.88 45.313% 47.813%)')
+ Color('hsl(182.29 40.104% 44.271%)')
)
- def test_bezier_cylindrical_gamut(self):
- """Test bezier with a cylindrical space with at least one color out of gamut."""
+ def test_bspline_cylindrical_gamut(self):
+ """Test B-spline with a cylindrical space with at least one color out of gamut."""
self.assertColorEqual(
Color.interpolate(
['hsl(250 50% 30%)', 'hsl(none 0% 110%)'],
space='hsl',
- method='bezier'
+ method='b-spline'
)(0.75),
Color('hsl(332.5 12.5% 82.5%)')
)
diff --git a/tests/test_plugin.py b/tests/test_plugin.py
index b36abbf75..107dedae2 100644
--- a/tests/test_plugin.py
+++ b/tests/test_plugin.py
@@ -252,22 +252,22 @@ class Custom(Color):
def test_plugin_registration_interpolate(self):
"""Test plugin registration of `interpolate`."""
- from coloraide.interpolate.bezier import InterpolateBezier
+ from coloraide.interpolate.bspline import BSpline
# Deregistration should have taken place
class Custom(Color):
pass
- Custom.deregister('interpolate:bezier')
- color = Color('red').mix('blue', method='bezier')
+ Custom.deregister('interpolate:b-spline')
+ color = Color('red').mix('blue', method='b-spline')
with self.assertRaises(ValueError):
- Custom('red').mix('blue', method='bezier')
+ Custom('red').mix('blue', method='b-spline')
# Now it is registered again
- Custom.register(InterpolateBezier())
+ Custom.register(BSpline())
self.assertColorEqual(
- Custom('red').mix('blue', method='bezier'),
+ Custom('red').mix('blue', method='b-spline'),
color
)
| Look into interpolation with b splines
B splines are a better alternative to using bezier curves. Changes in control points are more localized.
| Okay, B-Splines are much better than Bezier. From top to bottom: linear, bezier, bspline. With the control points affects much more localized, the interpolation shows through all the colors more, but still keeps the transitions smooth.
<img width="731" alt="Screen Shot 2022-07-24 at 5 22 21 PM" src="https://user-images.githubusercontent.com/1055125/180669979-c76c6400-bbdf-4aa5-b9cb-291f946aa798.png">
B-Spline does so much better that I can't think of a reason to keep Bezier around. | 2022-07-25T01:00:20.000 | -1.0 | [
"tests/test_plugin.py::TestCustom::test_plugin_registration_interpolate",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_channel_bspline",
"tests/test_interpolation.py::TestInterpolation::test_steps_input_bspline",
"tests/test_interpolation.py::TestInterpolation::test_bspline_most_none",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_multi_bspline",
"tests/test_interpolation.py::TestInterpolation::test_bspline_cylindrical",
"tests/test_interpolation.py::TestInterpolation::test_bspline_none_after",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_bspline",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_input_bspline",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_stop_bspline",
"tests/test_interpolation.py::TestInterpolation::test_bspline_cylindrical_gamut",
"tests/test_interpolation.py::TestInterpolation::test_bspline_all_none"
] | [
"tests/test_interpolation.py::TestInterpolation::test_steps_progress",
"tests/test_plugin.py::TestCustom::test_override_precision",
"tests/test_plugin.py::TestCustom::test_bad_registration_type",
"tests/test_interpolation.py::TestInterpolation::test_steps",
"tests/test_interpolation.py::TestInterpolation::test_bad_mix_input",
"tests/test_interpolation.py::TestInterpolation::test_hue_decreasing_cases",
"tests/test_interpolation.py::TestInterpolation::test_hue_shorter_cases",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_easing_inline",
"tests/test_interpolation.py::TestInterpolation::test_mix_progress",
"tests/test_interpolation.py::TestInterpolation::test_mix_alpha",
"tests/test_plugin.py::TestCustom::test_reserved_registration_fit",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_out_space",
"tests/test_interpolation.py::TestInterpolation::test_hue_longer_cases",
"tests/test_interpolation.py::TestInterpolation::test_mix_hue_adjust",
"tests/test_interpolation.py::TestInterpolation::test_too_few_colors_linear",
"tests/test_plugin.py::TestCustom::test_plugin_registration_cat",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_alpha",
"tests/test_plugin.py::TestCustom::test_bad_deregister_category",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_premultiplied_alpha_none",
"tests/test_interpolation.py::TestInterpolation::test_mix_hue_adjust_bad",
"tests/test_interpolation.py::TestInterpolation::test_mix_dict",
"tests/test_interpolation.py::TestInterpolation::test_too_few_colors_bspline",
"tests/test_interpolation.py::TestInterpolation::test_mix_input_piecewise",
"tests/test_plugin.py::TestCustom::test_plugin_registration_fit",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_channel_aliases",
"tests/test_plugin.py::TestCustom::test_reserved_deregistration_fit",
"tests/test_interpolation.py::TestInterpolation::test_mix_mask_invert",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_progress",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_piecewise",
"tests/test_interpolation.py::TestInterpolation::test_max_delta_min_step_less_than_two",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_input_piecewise",
"tests/test_interpolation.py::TestInterpolation::test_steps_multi_max_delta_e",
"tests/test_interpolation.py::TestInterpolation::test_mix_out_space",
"tests/test_plugin.py::TestCustom::test_plugin_registration_filter",
"tests/test_interpolation.py::TestInterpolation::test_steps_max_delta_e_steps",
"tests/test_interpolation.py::TestInterpolation::test_mix_space",
"tests/test_plugin.py::TestCustom::test_silent_registration_exists",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_premultiplied_alpha",
"tests/test_interpolation.py::TestInterpolation::test_mix_in_place",
"tests/test_plugin.py::TestCustom::test_deregister_all_category",
"tests/test_plugin.py::TestCustom::test_deregister_all",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_channel",
"tests/test_interpolation.py::TestInterpolation::test_steps_premultiplied_alpha",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_empty_list",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_stop",
"tests/test_plugin.py::TestCustom::test_plugin_registration_contrast",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_fit_required",
"tests/test_interpolation.py::TestInterpolation::test_mix_mask",
"tests/test_plugin.py::TestCustom::test_override_harmony",
"tests/test_interpolation.py::TestInterpolation::test_bad_color_input_bspline",
"tests/test_interpolation.py::TestInterpolation::test_steps_custom_delta_e",
"tests/test_plugin.py::TestCustom::test_bad_deregister_plugin",
"tests/test_interpolation.py::TestInterpolation::test_steps_input_piecewise",
"tests/test_interpolation.py::TestInterpolation::test_steps_space",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_hue_adjust",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_adjust",
"tests/test_interpolation.py::TestInterpolation::test_mix",
"tests/test_plugin.py::TestCustom::test_bad_registration_exists",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_space",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_premultiplied_no_alpha",
"tests/test_interpolation.py::TestInterpolation::test_bad_easing",
"tests/test_interpolation.py::TestInterpolation::test_steps_premultiplied_no_alpha",
"tests/test_plugin.py::TestCustom::test_override_fit",
"tests/test_plugin.py::TestCustom::test_bad_registration_star",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_color_hint",
"tests/test_interpolation.py::TestInterpolation::test_steps_alpha",
"tests/test_plugin.py::TestCustom::test_override_delta_e",
"tests/test_interpolation.py::TestInterpolation::test_mix_premultiplied_alpha",
"tests/test_plugin.py::TestCustom::test_override_interpolate",
"tests/test_interpolation.py::TestInterpolation::test_steps_multi",
"tests/test_interpolation.py::TestInterpolation::test_hue_increasing_cases",
"tests/test_interpolation.py::TestInterpolation::test_steps_nan",
"tests/test_interpolation.py::TestInterpolation::test_steps_max_delta_e",
"tests/test_interpolation.py::TestInterpolation::test_bad_method",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_nan",
"tests/test_interpolation.py::TestInterpolation::test_steps_empty_list",
"tests/test_plugin.py::TestCustom::test_plugin_registration_delta_e",
"tests/test_interpolation.py::TestInterpolation::test_mix_premultiplied_no_alpha",
"tests/test_interpolation.py::TestInterpolation::test_steps_adjust",
"tests/test_interpolation.py::TestInterpolation::test_steps_hue_adjust",
"tests/test_interpolation.py::TestInterpolation::test_mix_hue_nan",
"tests/test_interpolation.py::TestInterpolation::test_mix_nan",
"tests/test_interpolation.py::TestInterpolation::test_interpolate",
"tests/test_plugin.py::TestCustom::test_plugin_registration_space",
"tests/test_interpolation.py::TestInterpolation::test_steps_out_space",
"tests/test_interpolation.py::TestInterpolation::test_interpolate_channel_all",
"tests/test_interpolation.py::TestInterpolation::test_mix_premultiplied_cylindrical",
"tests/test_interpolation.py::TestInterpolation::test_steps_custom_delta_compare",
"tests/test_plugin.py::TestCustom::test_silent_deregister_not_exists"
] |
facelessuser/coloraide | 184 | facelessuser__coloraide-184 | ['182'] | 18a8bed3a17de77661eea34fcaa7af985e922e0e | "diff --git a/coloraide/color.py b/coloraide/color.py\nindex 3854d7ca6..fa2d56c92 100644\n--- a/colo(...TRUNCATED) | "diff --git a/tests/test_a98_rgb_linear.py b/tests/test_a98_rgb_linear.py\nnew file mode 100644\nind(...TRUNCATED) | "Add at least Rec. 2100 PQ\nThis color proves useful to evaluate the HDR range of some of the includ(...TRUNCATED) | 2022-07-06T05:29:01.000 | -1.0 | ["tests/test_a98_rgb_linear.py::TestLinearA98RGB::test_colors[black-color(--a98-rgb-linear","tests/t(...TRUNCATED) | [] |
|
ansible/ansible | 43,583 | ansible__ansible-43583 | ['42388'] | a5774bd29a93ca4dcdf2626b5dcce44a4c35e6eb | "diff --git a/lib/ansible/config/manager.py b/lib/ansible/config/manager.py\n--- a/lib/ansible/confi(...TRUNCATED) | "diff --git a/test/units/config/manager/__init__.py b/test/units/config/manager/__init__.py\nnew fil(...TRUNCATED) | "Windows 10/WSL: Ansible cannot read ansible.cfg from NTFS mounts\n##### SUMMARY\r\nAnsible 2.6.1 ad(...TRUNCATED) | "Files identified in the description:\n* [lib/ansible/cli/config.py](https://github.com/ansible/ansi(...TRUNCATED) | 2018-08-02T00:53:40.000 | -1.0 | ["test/units/config/manager/test_find_ini_config_file.py::TestFindIniFile::test_no_warning_on_writab(...TRUNCATED) | ["test/units/config/test_manager.py::TestConfigData::test_ensure_type_list","test/units/config/test_(...TRUNCATED) |
Delgan/loguru | 1,306 | Delgan__loguru-1306 | ['1305'] | 3cfd03fb6fd2176b90ad14223408f3c4ec803cb6 | "diff --git a/loguru/_colorama.py b/loguru/_colorama.py\nindex b380536c..220ddd89 100644\n--- a/logu(...TRUNCATED) | "diff --git a/tests/test_colorama.py b/tests/test_colorama.py\nindex ab659e09..1aea8e5a 100644\n--- (...TRUNCATED) | "Support for FORCE_COLOR\nhttps://force-color.org/\n\nSimilar to #1178 / #1299 but forcing color to (...TRUNCATED) | 2025-02-20T00:59:01.000 | -1.0 | ["tests/test_colorama.py::test_honor_no_color_standard[--True]","tests/test_colorama.py::test_honor_(...TRUNCATED) | ["tests/test_colorama.py::test_honor_force_color_standard[__stdout__--False]","tests/test_colorama.p(...TRUNCATED) |
|
hamdanal/rich-argparse | 135 | hamdanal__rich-argparse-135 | ['133'] | 6789cbefc17af6fd5112f5d80e738810152cb0ca | "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 8c3617c..3bcd22f 100644\n--- a/CHANGELOG.md\n+++ b/(...TRUNCATED) | "diff --git a/tests/test_argparse.py b/tests/test_argparse.py\nindex 222aaeb..9fb5f49 100644\n--- a/(...TRUNCATED) | "test_help_preview_generation fails with rich==13.8.1\nHi!\r\n\r\nWe are using rich-argparse 1.5.2 a(...TRUNCATED) | "Thanks for the issue. This looks like an upstream bug with rich, I filed https://github.com/Textual(...TRUNCATED) | 2024-11-02T10:21:41.000 | -1.0 | [
"tests/test_argparse.py::test_help_preview_generation"
] | ["tests/test_argparse.py::test_subparsers[req-no_help-mv-no_dest-desc-no_title]","tests/test_argpars(...TRUNCATED) |
ansible/ansible-runner | 161 | ansible__ansible-runner-161 | ['141'] | d9940a55288386abcce8e1e41bd93d8c671a06ca | "diff --git a/ansible_runner/runner.py b/ansible_runner/runner.py\nindex 23b711b67..2e8a6cfdd 100644(...TRUNCATED) | "diff --git a/test/unit/test_runner.py b/test/unit/test_runner.py\nindex c527ab6d4..1ac3c67ae 100644(...TRUNCATED) | "Different data passed to status_handler plugin vs kwargs\nHi,\r\n\r\nAs you can see from my PR, I'm(...TRUNCATED) | What PR are you referring to? I'm fine with adding the ident if you need it in there. | 2018-10-19T15:49:22.000 | -1.0 | [
"test/unit/test_runner.py::test_status_callback_interface"
] | ["test/unit/test_runner.py::test_job_timeout","test/unit/test_runner.py::test_env_vars[abc123]","tes(...TRUNCATED) |
annotated-types/annotated-types | 24 | annotated-types__annotated-types-24 | ['23'] | 9747ec3c89e2bfd09b009f6a59b48fe3684b89ed | "diff --git a/README.md b/README.md\nindex 3eadeb3..24aaffc 100644\n--- a/README.md\n+++ b/README.md(...TRUNCATED) | "diff --git a/annotated_types/test_cases.py b/annotated_types/test_cases.py\nindex f971554..ae2c084 (...TRUNCATED) | "Rethink `max_exclusive`, convert to `max_inclusive`?\nIf we have `MaxLen`, and (in pydantic at leas(...TRUNCATED) | "My personal preference would be to treat slices e.g. `2:10` as `Len(min_inclusive=2, max_inclusive=(...TRUNCATED) | 2022-09-30T10:37:19.000 | -1.0 | ["tests/test_main.py::test_valid_cases[typing.Annotated[typing.List[int],","tests/test_main.py::test(...TRUNCATED) | ["tests/test_main.py::test_valid_cases[typing.Annotated[float,","tests/test_main.py::test_valid_case(...TRUNCATED) |
hamdanal/rich-argparse | 142 | hamdanal__rich-argparse-142 | ['141'] | a729c13725e5347fe05b3981877171459de17543 | "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex fbbd5f8..15cce1d 100644\n--- a/CHANGELOG.md\n+++ b/(...TRUNCATED) | "diff --git a/tests/test_argparse.py b/tests/test_argparse.py\nindex 9fb5f49..4a855f4 100644\n--- a/(...TRUNCATED) | "Formatting of arguments applied even within back-ticks (syntax style)\nThis issue relates to the pr(...TRUNCATED) | "Tested with rich==13.9.4 and rich-argparse==1.6.0 under Python 3.12 on macOS in several terminals ((...TRUNCATED) | 2024-12-22T11:55:23.000 | -1.0 | [
"tests/test_argparse.py::test_default_highlights"
] | ["tests/test_argparse.py::test_subparsers[req-no_help-mv-no_dest-desc-no_title]","tests/test_argpars(...TRUNCATED) |
hamdanal/rich-argparse | 153 | hamdanal__rich-argparse-153 | ['152'] | f946bb34c51956e380be52edc6f8abda6c21a1b7 | "diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex e9f900f..14229ee 100644\n--- a/CHANGELOG.md\n+++ b/(...TRUNCATED) | "diff --git a/tests/test_argparse.py b/tests/test_argparse.py\nindex ec3fd02..0f70ec4 100644\n--- a/(...TRUNCATED) | "Using `%(default)s` inside square brackets crashes with ValueError\nThis program crashes with `Valu(...TRUNCATED) | 2025-02-02T09:14:17.000 | -1.0 | [
"tests/test_argparse.py::test_arg_default_in_markup"
] | ["tests/test_argparse.py::test_subparsers[req-no_help-mv-no_dest-desc-no_title]","tests/test_argpars(...TRUNCATED) |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 28