import numpy as np, colour, json, warnings; warnings.filterwarnings('ignore')
from scipy.spatial import ConvexHull
# Sample the surface of each RGB cube densely, convert to CIELAB (D65) and OKLab, compute convex-hull-free volume via dense grid point-in-gamut counting (gamut solids are not convex in Lab).
N=64
g=np.linspace(0,1,N); R,G,B=np.meshgrid(g,g,g,indexing='ij'); rgb=np.stack([R,G,B],-1).reshape(-1,3)
spaces={'sRGB':colour.models.RGB_COLOURSPACE_sRGB,'Display P3':colour.models.RGB_COLOURSPACE_DISPLAY_P3,'Rec.2020':colour.models.RGB_COLOURSPACE_BT2020}
# Voxel approach: sample Lab grid, test membership by converting Lab->linear RGB of each space and checking [0,1]
res={}
for name,conv in [('CIELAB',lambda XYZ: colour.XYZ_to_Lab(XYZ, colour.CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'])),('OKLab',colour.XYZ_to_Oklab)]:
    # bounds from Rec.2020 cube samples
    XYZ=colour.RGB_to_XYZ(rgb,spaces['Rec.2020'],apply_cctf_decoding=False)
    L=conv(XYZ); lo=L.min(0); hi=L.max(0)
    M=110
    axes=[np.linspace(lo[i],hi[i],M) for i in range(3)]
    A,Bb,C=np.meshgrid(*axes,indexing='ij'); pts=np.stack([A,Bb,C],-1).reshape(-1,3)
    if name=='CIELAB': XYZp=colour.Lab_to_XYZ(pts, colour.CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'])
    else: XYZp=colour.Oklab_to_XYZ(pts)
    cell=np.prod([(hi[i]-lo[i])/(M-1) for i in range(3)])
    r={}
    for n,s in spaces.items():
        lin=colour.XYZ_to_RGB(XYZp,s,apply_cctf_encoding=False)
        inside=np.all((lin>=-1e-6)&(lin<=1+1e-6),axis=1)
        r[n]=inside.sum()*cell
    res[name]={n:dict(volume=v,ratio_vs_srgb=v/r['sRGB']) for n,v in r.items()}
print(json.dumps(res,indent=1)); json.dump(res,open('gamut_volumes.json','w'),indent=1)
