Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-develop

Source of release 0.1.0

0.1.0 / src / film_model.lucb

## A film stock's model: everything that depends on the stock alone, built
## once when it is chosen (film.lucb holds it for some settings). Its layers'
## spectral sensitivities, its characteristic curves unmixed into dye amounts, the scan of
## every mix of dyes, and the sharpness its MTF curves show, fitted.
import memory
from luce_std import math
from luce_color import spectral
from luce_color import xyz
from luce_color import transfer
import view
from film_stocks import Stock
import densitometry
from densitometry import Densitometer
import film_stocks

## The tables' sizes: the scan's cube, the curves' samples and their log H range.
pub let lut_size: usize = 33
pub let curve_samples: usize = 1024
pub let log_low: f64 = -4.5
pub let log_high: f64 = 2.5

## Slides are seen on a lightbox of this light (D50, as a black body).
let lightbox_kelvin: f64 = 5000.0

## The densities `meter` reads of a negative of `model`'s stock over the dye
## amounts 0..top (33³ × 3, r fastest), over D-min's: what a print material
## sees of it. The caller frees it.
pub func printed_by(model: const Model*, meter: const Densitometer*) -> f64[]!:
    let n = lut_size
    let out = try new f64[n * n * n * 3] --- in memory.heap
    let base = meter.read(model.stock.d_min)
    for b in 0..<n:
        for g in 0..<n:
            for r in 0..<n:
                let amounts: f64[3] = [model.top * (f64)r / (f64)(n - 1), model.top * (f64)g / (f64)(n - 1), model.top * (f64)b / (f64)(n - 1)]
                let read = meter.read(model.density(amounts))
                let at = ((b * n + g) * n + r) * 3
                for k in 0..<(usize)3:
                    out[at + k] = read[k] - base[k]
    return out

# mark: The model =============================================================

## Everything that depends on the stock alone, built once per stock.
pub struct Model:
    pub var stock: Stock
    pub var meter: Densitometer
    ## Printing density (`printing`), and D-min's.
    pub var printer: Densitometer
    pub var printer_base: f64[3]
    ## D-min's spectral density as the scan reads it.
    pub var base: f64[3]
    ## Each layer's spectral sensitivity (linear, its peak 1), and the light the
    ## stock is balanced for (a black body, or CIE daylight for daylight stocks).
    pub var sensitivity: f64[243]
    pub var light: spectral.Spectrum
    ## Neutral dye amounts over log H (1024 × 3), and rms granularity.
    pub var neutral: f64[]
    pub var grain: f64[]
    ## The emulsion's grain populations (`fit_populations`): per layer, three
    ## (fast, mid, slow), each the log H where half its grains develop and how
    ## gradually (a logistic's width), six numbers a layer.
    pub var populations: f64[18]
    ## The scan: densities over dye amounts 0..top (33³ × 3), r fastest; and the
    ## printing densities a print stock sees, the same way.
    pub var scan: f64[]
    pub var printed: f64[]
    pub var top: f64
    ## Each layer's most dye (a slide's in its shadows), and normal exposure.
    pub var most: f64[3]
    pub var grey_log_h: f64
    ## Sharpness, fitted to the stock's MTF curves: each layer's light scatter (an
    ## exponential's length, µm, the emulsion's classic spread of light), how strongly its development holds itself back
    ## (self-inhibition, log H per unit of its dye), and how far its inhibitor
    ## spreads (σ, µm). Together they give the curves' fall at high frequencies
    ## and their rise above 100% where edges are developed harder.
    pub var scatter: f64[3]
    pub var self_inhibition: f64[3]
    pub var spread: f64[3]

    pub func release():
        release_table(&self.neutral)
        release_table(&self.grain)
        release_table(&self.scan)
        release_table(&self.printed)

    ## A slide of dye `amounts` on a lightbox of `light`, its clear base white,
    ## the eye adapted to it: the scene light (AP1, log2 over grey) the ACES view
    ## shows as that, as display pictures come in (view.undisplay), as
    ## asinh(256·light).
    pub func viewed(amounts: f64[3], light: const spectral.Spectrum*) -> f64[3]:
        var shown = xyz.XYZ(0.0, 0.0, 0.0)
        var white = xyz.XYZ(0.0, 0.0, 0.0)
        for at in 0..<spectral.samples:
            let d = amounts[0] * self.stock.dyes[at] + amounts[1] * self.stock.dyes[81 + at] + amounts[2] * self.stock.dyes[162 + at]
            let power = light.values[at] * math.pow(10.0, -d)
            shown.x += power * spectral.observer[at * 3]
            shown.y += power * spectral.observer[at * 3 + 1]
            shown.z += power * spectral.observer[at * 3 + 2]
            white.x += light.values[at] * spectral.observer[at * 3]
            white.y += light.values[at] * spectral.observer[at * 3 + 1]
            white.z += light.values[at] * spectral.observer[at * 3 + 2]
        let point = xyz.Chromaticity(white.x / (white.x + white.y + white.z), white.y / (white.x + white.y + white.z))
        let adapted = xyz.apply(xyz.adapt(point, xyz.d65), xyz.XYZ(shown.x / white.y, shown.y / white.y, shown.z / white.y))
        let to_srgb = xyz.xyz_to_rgb(xyz.srgb).m
        var c: f64[3] = [to_srgb[0] * adapted.x + to_srgb[1] * adapted.y + to_srgb[2] * adapted.z,
                         to_srgb[3] * adapted.x + to_srgb[4] * adapted.y + to_srgb[5] * adapted.z,
                         to_srgb[6] * adapted.x + to_srgb[7] * adapted.y + to_srgb[8] * adapted.z]
        # Colors past the display's gamut: toward their luminance until none is negative.
        let least = math.min(c[0], math.min(c[1], c[2]))
        if least < 0.0 and adapted.y > 0.0:
            let t = adapted.y / (adapted.y - least)
            for k in 0..<(usize)3:
                c[k] = adapted.y + (c[k] - adapted.y) * t
        let scene = view.undisplay(transfer.srgb_encode(math.clamp(c[0], 0.0, 1.0)), transfer.srgb_encode(math.clamp(c[1], 0.0, 1.0)),
                                   transfer.srgb_encode(math.clamp(c[2], 0.0, 1.0)))
        # On an inverse hyperbolic sine (linear through black, logarithmic in the
        # light), in which the table interpolates smoothly where a channel of a
        # saturated color runs down to nothing.
        var out: f64[3]
        for k in 0..<(usize)3:
            let v = math.max(scene[k], 0.0) * 256.0
            out[k] = math.log(v + math.sqrt(v * v + 1.0))
        return out

    ## The scan's densities over D-min of dye `amounts` (cyan, magenta, yellow).
    pub func scanned(amounts: f64[3]) -> f64[3]:
        let read = self.meter.read(self.density(amounts))
        return [read[0] - self.base[0], read[1] - self.base[1], read[2] - self.base[2]]

    ## The printing densities over D-min of dye `amounts`: what the print stock
    ## sees through them.
    pub func printing_density(amounts: f64[3]) -> f64[3]:
        let read = self.printer.read(self.density(amounts))
        return [read[0] - self.printer_base[0], read[1] - self.printer_base[1], read[2] - self.printer_base[2]]

    ## The negative's spectral density with dye `amounts`: base, mask and fog
    ## (D-min) and the dyes. Kodak draws its negatives' dyes as they act with
    ## their masking couplers: printing density from them meets Kodak's own
    ## (the test below); taking a modelled mask off them as they form did not.
    pub func density(amounts: f64[3]) -> f64[81]:
        var out: f64[81]
        for at in 0..<spectral.samples:
            out[at] = self.stock.d_min[at] + amounts[0] * self.stock.dyes[at] + amounts[1] * self.stock.dyes[81 + at] + amounts[2] * self.stock.dyes[162 + at]
        return out

func release_table(table: f64[]*):
    if table.length > 0:
        free(*table) in memory.heap
    var empty: f64[]
    *table = empty

## Layer `channel`'s Status M density over its toe at `log_h`: the datasheet's
## readings, a toe below them and a shoulder above (estimates: Kodak plots
## neither), rolling off from 8 stops over normal exposure.
func over_minimum(stock: const Stock*, channel: usize, log_h: f64) -> f64:
    let n = stock.curve_count
    let curve = stock.curves[channel * film_stocks.curve_most..<channel * film_stocks.curve_most + n]
    if stock.kind == 1:
        # A slide's curve falls from D-max to D-min, both plateaus plotted: held
        # at its ends, over its least density.
        var least = curve[0]
        for value in curve:
            least = math.min(least, value)
        let position = math.clamp((log_h - stock.curve_first) / stock.curve_step, 0.0, (f64)(n - 1))
        let at = (usize)math.min(math.floor(position), (f64)(n - 2))
        let t = position - (f64)at
        return curve[at] + (curve[at + 1] - curve[at]) * t - least
    let first = curve[0]
    let toe = first - 0.015
    let start_slope = math.max((curve[1] - curve[0]) / stock.curve_step, 0.01)
    let last_x = stock.curve_first + (f64)(n - 1) * stock.curve_step
    if log_h <= stock.curve_first:
        # Approaches the toe exponentially, meeting the first reading's slope.
        let k = start_slope / ((first - toe) * 2.302585092994046)
        return (first - toe) * math.pow(10.0, k * (log_h - stock.curve_first))
    if log_h >= last_x:
        let end_slope = math.max((curve[n - 1] - curve[n - 5]) / (4.0 * stock.curve_step), 0.0)
        let shoulder = stock.grey_log_h + 2.4
        let width = 0.35
        let run = (log_h - last_x) - width * (softplus((log_h - shoulder) / width) - softplus((last_x - shoulder) / width))
        return curve[n - 1] - toe + end_slope * run
    let position = (log_h - stock.curve_first) / stock.curve_step
    let below = (usize)math.min(math.floor(position), (f64)(n - 2))
    let t = position - (f64)below
    return curve[below] + (curve[below + 1] - curve[below]) * t - toe

func softplus(x: f64) -> f64:
    return x + math.log(1.0 + math.exp(-x)) if x > 0.0 else math.log(1.0 + math.exp(x))

## The dye amounts whose scan reads `target` (densities over D-min), by Newton
## from `start`.
func unmix(model: const Model*, target: f64[3], start: f64[3]) -> f64[3]:
    var a = start
    for _ in 0..<30:
        let here = model.scanned(a)
        let residual: f64[3] = [here[0] - target[0], here[1] - target[1], here[2] - target[2]]
        if math.abs(residual[0]) + math.abs(residual[1]) + math.abs(residual[2]) < 1.0e-7:
            break
        var jacobian: f64[9]
        for k in 0..<(usize)3:
            var nudged = a
            nudged[k] += 1.0e-4
            let moved = model.scanned(nudged)
            for row in 0..<(usize)3:
                jacobian[row * 3 + k] = (moved[row] - here[row]) / 1.0e-4
        let step = solve3(jacobian, residual) else break
        for k in 0..<(usize)3:
            a[k] -= step[k]
    return a

func solve3(m: f64[9], v: f64[3]) -> f64[3]?:
    let inverse = invert3(m) else return none
    return apply3(inverse, v)

pub func invert3(m: f64[9]) -> f64[9]?:
    let det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6])
    if math.abs(det) < 1.0e-14:
        return none
    return [(m[4] * m[8] - m[5] * m[7]) / det, (m[2] * m[7] - m[1] * m[8]) / det, (m[1] * m[5] - m[2] * m[4]) / det,
            (m[5] * m[6] - m[3] * m[8]) / det, (m[0] * m[8] - m[2] * m[6]) / det, (m[2] * m[3] - m[0] * m[5]) / det,
            (m[3] * m[7] - m[4] * m[6]) / det, (m[1] * m[6] - m[0] * m[7]) / det, (m[0] * m[4] - m[1] * m[3]) / det]

func apply3(m: const f64[9], v: f64[3]) -> f64[3]:
    return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]]

## Curve sample `at`'s log H.
pub func log_h_at(at: usize) -> f64:
    return log_low + (log_high - log_low) * (f64)at / (f64)(curve_samples - 1)

## Build `stock`'s model: the spectral exposure grid, the unmixed curves, the scan.
## How far red and blue stand from green, seen on the lightbox.
func neutral_miss(model: const Model*, amounts: f64[3], light: const spectral.Spectrum*) -> f64[2]:
    let seen = model.viewed(amounts, light)
    return [seen[0] - seen[1], seen[2] - seen[1]]

## A slide is seen as it is, so grey must look grey on the lightbox: the sheet's
## typical curves stand a few hundredths apart there (within a coating's
## tolerance), and Status A's bands are not the eye. The red and blue layers'
## dye amounts that look neutral beside the green's at grey (Newton on the
## lightbox view), and those layers' curves moved along log H to reach them.
func balance_slide(model: Model*):
    let lightbox = spectral.planck(lightbox_kelvin)
    let grey = math.clamp((model.grey_log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
    let at = (usize)math.round(grey)
    var amounts: f64[3] = [model.neutral[at * 3], model.neutral[at * 3 + 1], model.neutral[at * 3 + 2]]
    # The view is asinh-encoded, about log light: equal values are a neutral.
    # Newton on the red and blue misses against green, both dyes at once (each
    # darkens more than its own channel), the step halved until it helps.
    var miss = neutral_miss(model, amounts, &lightbox)
    for _ in 0..<30:
        if math.abs(miss[0]) + math.abs(miss[1]) < 1.0e-7:
            break
        var jacobian: f64[4]
        for (column, layer) in [((usize)0, (usize)0), ((usize)1, (usize)2)]:
            var nudged = amounts
            nudged[layer] += 1.0e-4
            let moved = neutral_miss(model, nudged, &lightbox)
            jacobian[column] = (moved[0] - miss[0]) / 1.0e-4
            jacobian[2 + column] = (moved[1] - miss[1]) / 1.0e-4
        let det = jacobian[0] * jacobian[3] - jacobian[1] * jacobian[2]
        if math.abs(det) < 1.0e-12:
            break
        let step: f64[2] = [(jacobian[3] * miss[0] - jacobian[1] * miss[1]) / det, (jacobian[0] * miss[1] - jacobian[2] * miss[0]) / det]
        var scale = 1.0
        while scale > 1.0e-3:
            var tried = amounts
            tried[0] -= scale * step[0]
            tried[2] -= scale * step[1]
            let tried_miss = neutral_miss(model, tried, &lightbox)
            if math.abs(tried_miss[0]) + math.abs(tried_miss[1]) < math.abs(miss[0]) + math.abs(miss[1]):
                amounts = tried
                miss = tried_miss
                break
            scale *= 0.5
    for layer in [(usize)0, (usize)2]:
        # Where the layer's own curve forms that amount (it falls with log H).
        var found = (f64)at
        for sample in 1..<curve_samples:
            let high = model.neutral[(sample - 1) * 3 + layer]
            let low = model.neutral[sample * 3 + layer]
            if high >= amounts[layer] and amounts[layer] >= low and high != low:
                found = (f64)(sample - 1) + (high - amounts[layer]) / (high - low)
                break
        let shift = found - (f64)at
        let moved = model.neutral
        var curve: f64[1024]
        for sample in 0..<curve_samples:
            let place = math.clamp((f64)sample + shift, 0.0, (f64)(curve_samples - 1))
            let below = (usize)math.min(math.floor(place), (f64)(curve_samples - 2))
            let t = place - (f64)below
            curve[sample] = moved[below * 3 + layer] * (1.0 - t) + moved[(below + 1) * 3 + layer] * t
        for sample in 0..<curve_samples:
            model.neutral[sample * 3 + layer] = curve[sample]

pub func build_model(stock: Stock) -> Model!:
    # Each stock's curves are read as its sheet reads them: Status A for slides,
    # Status M for color negatives (black-and-white silver is near neutral in
    # either).
    let meter = densitometry.status_a() if stock.kind == 1 else densitometry.status_m()
    var out = Model(stock = stock, meter = meter, printer = densitometry.printing())
    errdefer out.release()
    out.base = out.meter.read(stock.d_min)
    out.printer_base = out.printer.read(stock.d_min)
    # The balance light, and each layer's sensitivity, linear.
    out.light = spectral.illuminant(stock.kelvin)
    for layer in 0..<(usize)3:
        var peak = -1.0e9
        for at in 0..<spectral.samples:
            peak = math.max(peak, stock.sensitivity[layer * 81 + at])
        for at in 0..<spectral.samples:
            out.sensitivity[layer * 81 + at] = math.pow(10.0, stock.sensitivity[layer * 81 + at] - peak)
    # Neutral development: the dye amounts that read each curve's densities.
    out.neutral = try new f64[curve_samples * 3] --- in memory.heap
    out.grain = try new f64[curve_samples * 3] --- in memory.heap
    var start: f64[3] = [0.0, 0.0, 0.0]
    for at in 0..<curve_samples:
        let log_h = log_h_at(at)
        let target: f64[3] = [over_minimum(&stock, 0, log_h), over_minimum(&stock, 1, log_h), over_minimum(&stock, 2, log_h)]
        start = unmix(&out, target, start)
        for layer in 0..<(usize)3:
            out.neutral[at * 3 + layer] = math.max(start[layer], 0.0)
            let last = (f64)(stock.granularity_count - 1)
            let position = math.clamp((log_h - stock.granularity_first) / stock.granularity_step, 0.0, last)
            let below = (usize)math.min(math.floor(position), last - 1.0)
            let t = position - (f64)below
            let row = layer * film_stocks.granularity_most
            out.grain[at * 3 + layer] = stock.granularity[row + below] * (1.0 - t) + stock.granularity[row + below + 1] * t
    out.grey_log_h = stock.grey_log_h
    if stock.kind == 1:
        balance_slide(&out)
    out.top = 0.0
    for at in 0..<curve_samples:
        for layer in 0..<(usize)3:
            out.most[layer] = math.max(out.most[layer], out.neutral[at * 3 + layer])
    for layer in 0..<(usize)3:
        # Room above the densest normal negative for one developed longer: as
        # far as the kinetics go at the longest development (film_develop.lucb,
        # six times normal), up to three times; a slide's dye only moves.
        let u = math.max(stock.saturation[layer], 1.0e-3)
        let room = math.clamp((1.0 - math.exp(-6.0 * u)) / (1.0 - math.exp(-u)), 1.5, 3.0)
        out.top = math.max(out.top, out.most[layer] * (1.1 if stock.kind == 1 else room))
    # The scan over the dye amounts: a negative's densities as the scanner reads
    # them; a slide as seen on a lightbox, as scene light (asinh-encoded).
    let n = lut_size
    out.scan = try new f64[n * n * n * 3] --- in memory.heap
    out.printed = try new f64[n * n * n * 3] --- in memory.heap
    let lightbox = spectral.planck(lightbox_kelvin)
    for b in 0..<n:
        for g in 0..<n:
            for r in 0..<n:
                let amounts: f64[3] = [out.top * (f64)r / (f64)(n - 1), out.top * (f64)g / (f64)(n - 1), out.top * (f64)b / (f64)(n - 1)]
                let read = out.viewed(amounts, &lightbox) if stock.kind == 1 else out.scanned(amounts)
                let at = ((b * n + g) * n + r) * 3
                out.scan[at] = read[0]
                out.scan[at + 1] = read[1]
                out.scan[at + 2] = read[2]
                let printed = out.printing_density(amounts)
                out.printed[at] = printed[0]
                out.printed[at + 1] = printed[1]
                out.printed[at + 2] = printed[2]
    fit_sharpness(&out)
    fit_populations(&out)
    return out

# mark: Grain populations ======================================================

## Each layer's emulsion as three populations of grains, as Kodak coats each
## color record in fast, mid and slow layers ("the highest speed emulsion layer
## creates the portion of the characteristic curve just above the minimum
## density", US 6,686,136): the fast population's grains develop first, in the
## toe, the slow one's last. Each population develops over log H as a
## logistic, placed where the layer's curve has come a sixth, a half and five
## sixths of the way, as wide as the curve takes over its third. A dye cloud's
## site holds many grains of each; how many develop spreads binomially, so
## grain is largest where a population is half developed;
## its strength per population is fitted to the published granularity
## (film.lucb's `population_amplitudes`).
func fit_populations(model: Model*):
    for layer in 0..<(usize)3:
        let low = model.neutral[layer]
        let high = model.neutral[(curve_samples - 1) * 3 + layer]
        let span = high - low
        var crossings: f64[7]
        for c in 0..<(usize)7:
            let level = (f64)c / 6.0
            var found = log_low if span >= 0.0 else log_high
            for at in 1..<curve_samples:
                let a = (model.neutral[(at - 1) * 3 + layer] - low) / (span if math.abs(span) > 1.0e-9 else 1.0)
                let b = (model.neutral[at * 3 + layer] - low) / (span if math.abs(span) > 1.0e-9 else 1.0)
                if a < level and b >= level:
                    found = log_h_at(at - 1) + (level - a) / math.max(b - a, 1.0e-12) * (log_h_at(at) - log_h_at(at - 1))
                    break
            crossings[c] = found
        for p in 0..<(usize)3:
            model.populations[layer * 6 + p * 2] = crossings[2 * p + 1]
            model.populations[layer * 6 + p * 2 + 1] = math.max((crossings[2 * p + 2] - crossings[2 * p]) / 4.4, 0.03)

## How much of population `p` of layer `layer` has developed at log H `log_h`.
pub func developed_share(populations: const f64[18], layer: usize, p: usize, log_h: f64) -> f64:
    let middle = populations[layer * 6 + p * 2]
    let width = populations[layer * 6 + p * 2 + 1]
    return 1.0 / (1.0 + math.exp(-(log_h - middle) / width))

# mark: Sharpness ===============================================================

## Fit the scatter, self-inhibition and spread to the stock's MTF. Linearized
## about grey, a layer whose neutral development rises by g dye per log H answers
## a sine of frequency f with S(f)·(1 − d·g·G(f)) / (1 − d·g): S the scatter's
## transfer (an exponential of length b: 1 / (1 + (2πbf)²)), G the spread's (a
## Gaussian), d the self-inhibition. Where G has fallen and S has not, the
## edges' answer exceeds 1: Kodak's curves rise above 100% there. One spread for
## the stock (the inhibitor diffuses alike in every layer), each layer's b and d
## by search, least squares in log response; d·g stays at most 0.5, so edges
## never gain more than twofold. Kodak's red curves fall early and slowly (the
## bottom layer sees light already spread by the two above it), which this
## follows to within about 20%.
func fit_sharpness(model: Model*):
    let grey_at = (model.grey_log_h - log_low) / (log_high - log_low) * (f64)(curve_samples - 1)
    let low = (usize)math.floor(grey_at) - 20
    let high = (usize)math.floor(grey_at) + 20
    var slopes: f64[3]
    for layer in 0..<(usize)3:
        # A slide's dye falls with exposure; its edges follow the first
        # developer's negative image, which rises as fast.
        slopes[layer] = math.abs((model.neutral[high * 3 + layer] - model.neutral[low * 3 + layer]) / (log_h_at(high) - log_h_at(low)))
    var best_total = 1.0e30
    var spread = 10.0
    while spread <= 40.0:
        var total = 0.0
        var lengths: f64[3]
        var inhibitions: f64[3]
        for layer in 0..<(usize)3:
            var best = 1.0e30
            var d = 0.0
            while d * slopes[layer] <= 0.5:
                var length = 0.0
                while length <= 10.0:
                    let err = mtf_miss(&model.stock, layer, slopes[layer], length, d, spread)
                    if err < best:
                        best = err
                        lengths[layer] = length
                        inhibitions[layer] = d
                    length += 0.2
                d += 0.02
            total += best
        if total < best_total:
            best_total = total
            model.scatter = lengths
            model.self_inhibition = inhibitions
            model.spread = [spread, spread, spread]
        spread += 1.0

## The squared log misses of a layer's modelled MTF against the datasheet's.
func mtf_miss(stock: const Stock*, layer: usize, slope: f64, length: f64, d: f64, spread: f64) -> f64:
    var err = 0.0
    for at in 0..<stock.mtf_count:
        let f = stock.mtf_frequencies[at] / 1000.0
        let s = 1.0 / (1.0 + (2.0 * math.pi * length * f) * (2.0 * math.pi * length * f))
        let g = math.exp(-2.0 * math.pi * math.pi * spread * spread * f * f)
        let response = s * (1.0 - d * slope * g) / (1.0 - d * slope)
        let miss = math.log(response) - math.log(stock.mtf[layer * film_stocks.mtf_most + at] / 100.0)
        err += miss * miss
    return err

# mark: Tests ===================================================================

## The fitted model's MTF for `layer` at `cycles` per mm.
func modelled_mtf(model: const Model*, layer: usize, cycles: f64, slope: f64) -> f64:
    let f = cycles / 1000.0
    let b = model.scatter[layer]
    let s = 1.0 / (1.0 + (2.0 * math.pi * b * f) * (2.0 * math.pi * b * f))
    let g = math.exp(-2.0 * math.pi * math.pi * model.spread[layer] * model.spread[layer] * f * f)
    let d = model.self_inhibition[layer] * slope
    return s * (1.0 - d * g) / (1.0 - d)

test "each stock's sharpness follows its datasheet MTF":
    for at in 0..<film_stocks.stock_count:
        var model = build_model(film_stocks.stock_at(at)) catch failure:
            assert(false)
            return
        defer model.release()
        let grey_at = (usize)math.floor((model.grey_log_h - log_low) / (log_high - log_low) * (f64)(curve_samples - 1))
        print(f"{model.stock.name}: scatter {model.scatter[0]} {model.scatter[1]} {model.scatter[2]} µm, self {model.self_inhibition[0]} {model.self_inhibition[1]} {model.self_inhibition[2]}, spread {model.spread[0]} {model.spread[1]} {model.spread[2]} µm")
        var worst = 0.0
        for layer in 0..<(usize)3:
            let slope = math.abs((model.neutral[(grey_at + 20) * 3 + layer] - model.neutral[(grey_at - 20) * 3 + layer]) / (log_h_at(grey_at + 20) - log_h_at(grey_at - 20)))
            for point in 0..<model.stock.mtf_count:
                let wanted = model.stock.mtf[layer * film_stocks.mtf_most + point] / 100.0
                let got = modelled_mtf(&model, layer, model.stock.mtf_frequencies[point], slope)
                worst = math.max(worst, math.abs(math.log(got / wanted)))
        print(f"  worst miss {worst}")
        assert(worst < 0.22)

test "printing density over Status M is Kodak's for Vision3 50D 5203":
    # Kodak H-387 (2011), Table VII: Status M over printing density 0.933, 0.981,
    # 1.036 for 5203 (its Cineon printing density: 2383 in a standard printer).
    # RP 180's responsivities meet it within 0.05; blue reads low by about that
    # (on 5219, Kodak's 2021 scanning paper gives 1.10, 1.05, 1.0: ours 1.08,
    # 1.04, 0.92), a gap in the dyes' or the bands' blue.
    var model = build_model(film_stocks.stock_at(9)) catch failure:
        assert(false)
        return
    defer model.release()
    assert(model.stock.name == "Kodak Vision3 50D 5203")
    let kodak: f64[3] = [1.0 / 0.933, 1.0 / 0.981, 1.0 / 1.036]
    let high = amounts_at(&model, model.grey_log_h + 0.3)
    let low = amounts_at(&model, model.grey_log_h - 0.3)
    let mh = model.scanned(high)
    let ml = model.scanned(low)
    let ph = model.printing_density(high)
    let pl = model.printing_density(low)
    for k in 0..<(usize)3:
        assert(math.abs((ph[k] - pl[k]) / (mh[k] - ml[k]) - kodak[k]) < 0.05)

## The dye amounts of the neutral curve at `log_h`.
func amounts_at(model: const Model*, log_h: f64) -> f64[3]:
    let place = math.clamp((log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
    let below = (usize)math.min(math.floor(place), (f64)(curve_samples - 2))
    let t = place - (f64)below
    var out: f64[3]
    for k in 0..<(usize)3:
        out[k] = model.neutral[below * 3 + k] * (1.0 - t) + model.neutral[(below + 1) * 3 + k] * t
    return out