In [1]:
import json

from pathlib import Path

import brushcue

ctx = brushcue.Context()

START_WAVELENGTH = 450.0
END_WAVELENGTH = 680.0

NUMBER_OF_SWATCHES = 6

BASE_PATH = (
    Path(brushcue.__file__).resolve().parents[3]
    / "writing/graphics/chapters/color-formats/assets/lms"
)
BASE_PATH.mkdir(parents=True, exist_ok=True)


def create_swatch(color: brushcue.ProfiledColor, wavelength: float):
    output_file_path = BASE_PATH / f"wavelength-{wavelength:.0f}nm.png"

    painter = brushcue.Painter.new()
    render_style = brushcue.RenderStyle.brush_and_fill(
        brushcue.Brush.solid(
            brushcue.ProfiledColor.from_rgba_srgb(
                brushcue.RGBAColor.from_components(0.0, 0.0, 0.0, 1.0)
            ),
            2,
        ),
        brushcue.Fill.solid(color),
    )
    painter = painter.add_ellipse_with_render_style(
        brushcue.Point2f.from_components(0.0, 0.0),
        brushcue.Vector2f.from_components(400.0, 400.0),
        0,
        render_style,
        brushcue.Transform2.to_list(brushcue.Transform2.identity()),
    )
    result = brushcue.Composition.painter(painter).execute(ctx).to_image_bytes(ctx)
    output_file_path.write_bytes(result)

    json_data = {
        "wavelength_nm": wavelength,
        "lmsa": color.to_lmsa().execute(ctx),
        "oklaba": color.to_ok_lab_a().execute(ctx),
        "rgba_srgb": color.to_rgb_encoded_with_color_profile(
            brushcue.ColorProfile.srgb()
        ).execute(ctx),
        "rgba_srgb_linear": color.to_rgb_linear_with_color_profile(
            brushcue.ColorProfile.srgb()
        ).execute(ctx),
    }
    output_file_path.with_suffix(".json").write_text(json.dumps(json_data, indent=4))


for swatch in range(NUMBER_OF_SWATCHES):
    delta = END_WAVELENGTH - START_WAVELENGTH
    percentage = swatch / (NUMBER_OF_SWATCHES - 1)
    wavelength = (percentage * delta) + START_WAVELENGTH
    color = brushcue.ProfiledColor.from_wavelength_nm(wavelength)
    create_swatch(color, wavelength)
    print(color.to_lmsa().execute(ctx))
(0.07384227216243744, 0.1610066294670105, 1.5344041585922241, 1.0)
(0.06621377915143967, 0.2765865623950958, 0.3540731966495514, 1.0)
(0.5801751613616943, 0.9082087278366089, 0.27371248602867126, 1.0)
(1.05037522315979, 0.737811803817749, 0.2453809678554535, 1.0)
(0.5116046667098999, 0.21499919891357422, 0.0832282230257988, 1.0)
(0.04198211058974266, 0.016194257885217667, 0.006467994302511215, 1.0)
In [ ]: