fit

package
v0.0.0-...-508dbe3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinCircleRadius keeps optimized circles large enough to cover at least one
	// pixel when their center is on the canvas.
	MinCircleRadius = 1.0
	// MinCircleOpacity is the smallest opacity that can affect an 8-bit output
	// channel. It also makes the optimizer's opacity bound strictly positive.
	MinCircleOpacity = 1.0 / 255.0
	// MaxCenterOffsetFraction permits centers up to half a canvas dimension
	// beyond each corresponding edge.
	MaxCenterOffsetFraction = 0.5
)

Variables

This section is empty.

Functions

func BenchmarkSSDBackend

func BenchmarkSSDBackend(iterations int, width, height int, durationNs int64) float64

BenchmarkSSDBackend measures throughput of a specific SSD backend.

Returns: throughput in megapixels/second

Example usage in benchmarks:

func BenchmarkSSDScalar(b *testing.B) {
    img := randomImage(256, 256)
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        fastSSD_Scalar(img.Pix, img.Pix, img.Stride, 256, 256)
    }
    b.ReportMetric(BenchmarkSSDBackend(b, 256, 256), "Mpixels/sec")
}

func DiffImage

func DiffImage(reference, candidate *image.NRGBA, colormap Colormap) *image.NRGBA

DiffImage renders the residual between a reference and a candidate as a false-color image: mean absolute RGB error per pixel, run through a colormap.

It lives here rather than in the server because it is the picture that explains a cost, and cost is this package's subject. The server serves it as diff.png and the score command writes it to a file; both want the same mapping, or the two would disagree about where a run is wrong.

func ExactSSD

func ExactSSD(current, reference *image.NRGBA) (uint64, bool)

ExactSSD returns the unnormalized RGB sum of squared differences as an exact integer. The active SIMD kernel currently returns its integer reduction in a float64, so this API accepts only image sizes whose worst-case sum is within float64's exact-integer range. This covers any practical in-memory image; the boolean is false for empty, mismatched, or theoretically oversized inputs. Alpha bytes are ignored, matching FastSSD.

func FastMSECost

func FastMSECost(current, reference *image.NRGBA) float64

FastMSECost is a drop-in replacement for MSECost using the SIMD-accelerated SSD kernel.

This function has the same signature as MSECost and can be used as a CostFunc. It uses the fastest supported SSD kernel and falls back to portable scalar code when the current CPU has no native implementation.

CPURenderer selects this cost by default. After installing a custom cost function, restore it with:

renderer.UseFastCost()

func FastSAD

func FastSAD(current, reference *image.NRGBA) float64

FastSAD computes perceptually-weighted error using SAD + quadratic weighting.

This matches the Delphi ErrorWeightingLoop function:

For each pixel: Value = |R1-R2| + |G1-G2| + |B1-B2|
Weighted cost: Scale × Value × (255 + 9×Value)

The quadratic weighting emphasizes larger differences, which are more perceptually significant.

Returns: Total weighted cost (not normalized).

func FastSSD

func FastSSD(current, reference *image.NRGBA) float64

FastSSD computes sum of squared differences between two NRGBA images.

This is a high-level wrapper around the low-level fastSSD kernel. It handles image dimension validation and computes the mean squared error (MSE) over RGB channels.

The alpha channel is ignored (only RGB channels contribute to cost).

Returns: MSE = sum(squared differences) / (width * height * 3)

Performance: uses the kernel Tier() selected (AVX2, SSE2, NEON, or scalar).

func GetScalarImplementation

func GetScalarImplementation() scalarImplementation

GetScalarImplementation returns the currently active scalar variant.

func MSECost

func MSECost(current, reference *image.NRGBA) float64

MSECost computes Mean Squared Error over sRGB channels.

func MapErrorColor

func MapErrorColor(value, maxError float64, colormap Colormap) color.NRGBA

MapErrorColor maps an error in [0, maxError] to an opaque false color. Values outside the range are clamped. A non-positive maxError maps to the palette's zero value.

func MapNormalizedColor

func MapNormalizedColor(value float64, colormap Colormap) color.NRGBA

MapNormalizedColor maps a normalized scalar to an opaque false color. Unknown colormaps fall back to Turbo, the application's default.

func PSNR

func PSNR(mse float64) float64

PSNR converts an RGB mean squared error on the 0-255 channel scale to peak signal-to-noise ratio in decibels. A perfect match has positive-infinite PSNR. Invalid MSE values return NaN.

func RegisterTierConsumer

func RegisterTierConsumer(install func(SIMDTier))

RegisterTierConsumer installs a dispatch site. The function is called immediately with the current tier, and again whenever SetForcedTier or ResetTierDetection changes it. Dispatch sites call this from init instead of selecting a kernel inline, which is what lets one process exercise every tier.

func RequiredCircleRadius

func RequiredCircleRadius(x, y float64, width, height int) float64

RequiredCircleRadius returns the minimum radius for a circle centered at (x,y). For an on-canvas center it is one. For an outside center it is the distance to the nearest integer pixel sample. The result is also raised to the exact Q16.16 radius needed after the renderer independently quantizes the center and radius. Using an actual sample is important when, for example, x is outside while y lies between two pixel rows: distance to the continuous canvas rectangle would ignore the fractional y distance and could produce an invisible tangent circle.

func ResetTierDetection

func ResetTierDetection()

ResetTierDetection drops a forced tier and restores the detected one. Pair it with SetForcedTier through t.Cleanup.

func SSIM

func SSIM(current, reference *image.NRGBA) (float64, error)

SSIM computes the mean structural similarity index over the RGB channels. It uses an 11x11 Gaussian window with sigma 1.5, reflected borders, and the conventional K1=0.01 and K2=0.03 constants for 8-bit samples. Alpha is deliberately ignored, matching MSECost and FastMSECost.

func SetForcedTier

func SetForcedTier(tier SIMDTier)

SetForcedTier pins the tier and re-runs every registered dispatch site so the change takes effect in the running process.

This is a test and benchmark facility. It is not safe to call while another goroutine is rendering or computing a cost, because it swaps the kernel function pointers those goroutines read.

func SetScalarImplementation

func SetScalarImplementation(impl scalarImplementation)

SetScalarImplementation changes the active scalar variant (for benchmarking).

This is primarily useful for performance testing different scalar optimizations:

  • SetScalarImplementation(scalarNaive): Simple reference (no optimizations)
  • SetScalarImplementation(scalarUnrolled4): 4-way unrolled (default, balanced)
  • SetScalarImplementation(scalarUnrolled8): 8-way unrolled (experimental, may be faster)

Example usage in benchmarks:

func BenchmarkScalarNaive(b *testing.B) {
    SetScalarImplementation(scalarNaive)
    defer SetScalarImplementation(scalarUnrolled4)
    // ... benchmark code ...
}

Types

type Bounds

type Bounds struct {
	Lower  []float64
	Upper  []float64
	K      int
	Width  int
	Height int
}

Bounds defines valid parameter ranges. Radius has an additional dynamic lower bound: a center outside the canvas must have a radius large enough to cover the nearest integer pixel sample after renderer quantization.

func NewBounds

func NewBounds(k, width, height int) *Bounds

NewBounds creates bounds for K circles in a WxH image.

func (*Bounds) ClampCircle

func (b *Bounds) ClampCircle(c Circle) Circle

ClampCircle clamps circle parameters to valid bounds.

func (*Bounds) ClampIndependentVector

func (b *Bounds) ClampIndependentVector(data []float64)

ClampIndependentVector applies only the rectangular optimizer bounds. It deliberately leaves the center/radius relationship untouched so constrained optimizers can measure and navigate its continuous violation instead of collapsing invalid candidates onto an exact tangent boundary.

func (*Bounds) ClampVector

func (b *Bounds) ClampVector(data []float64)

ClampVector clamps all parameters in a vector.

func (*Bounds) RadiusViolation

func (b *Bounds) RadiusViolation(c Circle) float64

RadiusViolation returns the dynamic raster-coverage constraint value for c. Values at or below zero are feasible; positive values are the missing radius in pixels. This form is suitable for continuous constrained optimizers.

func (*Bounds) ValidVector

func (b *Bounds) ValidVector(data []float64) bool

ValidVector reports whether data contains exactly K valid circles.

func (*Bounds) ValidateCircle

func (b *Bounds) ValidateCircle(c Circle) error

ValidateCircle checks both the independent optimizer bounds and the dynamic radius requirement for an outside center.

type Circle

type Circle struct {
	X, Y, R    float64 // Position and radius
	CR, CG, CB float64 // Color in [0,1]
	Opacity    float64 // Optimized opacity is in [MinCircleOpacity, 1]
}

Circle represents a colored circle with opacity.

type Colormap

type Colormap string

Colormap identifies a false-color palette for normalized scalar values.

const (
	// ColormapTurbo is Google's perceptually smooth rainbow-style colormap.
	ColormapTurbo Colormap = "turbo"
	// ColormapMagma is a perceptually uniform black-purple-orange-yellow colormap.
	ColormapMagma Colormap = "magma"
)

func ParseColormap

func ParseColormap(name string) (Colormap, bool)

ParseColormap validates a user-facing colormap name.

type CostFunc

type CostFunc func(current, reference *image.NRGBA) float64

CostFunc computes the error between current and reference images.

type ParamVector

type ParamVector struct {
	Data   []float64
	K      int // Number of circles
	Width  int // Image width
	Height int // Image height
}

ParamVector encodes K circles as a flat float64 slice.

func NewParamVector

func NewParamVector(k, width, height int) *ParamVector

NewParamVector creates a parameter vector for K circles.

func (*ParamVector) DecodeCircle

func (pv *ParamVector) DecodeCircle(i int) Circle

DecodeCircle reads a circle from position i in the vector.

func (*ParamVector) EncodeCircle

func (pv *ParamVector) EncodeCircle(i int, c Circle)

EncodeCircle writes a circle to position i in the vector.

type SIMDTier

type SIMDTier uint8

SIMDTier names the instruction set every runtime-dispatched kernel in this process is allowed to use. It is resolved once, from one place, and every dispatch site reads it instead of consulting golang.org/x/sys/cpu itself.

Before this existed each kernel re-derived its own ladder from the CPU feature bits and recorded the outcome in its own way: a typed enum here, a free-form string there, a pair of mutually exclusive booleans somewhere else. Nothing kept those answers consistent, and nothing could ask the process as a whole which tier it was running. Both properties are needed to test a tier that the host CPU is not, which is the entire point of having a fallback tier at all.

const (
	TierScalar SIMDTier = iota
	TierSSE2
	TierAVX2
	TierNEON
)

Tiers are ordered by preference within an architecture. Ordering across architectures is meaningless — TierNEON is never comparable to TierAVX2, because no CPU offers both — so only tierSupported decides what may be selected here.

func ActiveSADKernel

func ActiveSADKernel() SIMDTier

ActiveSADKernel reports which kernel SAD dispatch installed.

func ActiveSSDKernel

func ActiveSSDKernel() SIMDTier

ActiveSSDKernel reports which kernel SSD dispatch installed.

This can legitimately be narrower than Tier(): a cost function without a kernel for the process tier falls back, and FastSAD does exactly that below AVX2. Tests assert the relationship rather than assuming equality.

func ParseSIMDTier

func ParseSIMDTier(name string) (SIMDTier, bool)

ParseSIMDTier maps a wire name to a tier. It does not check whether the tier is reachable on this architecture; tierSupported does that.

func Tier

func Tier() SIMDTier

Tier reports the instruction set this process dispatches to. The result is cached; callers may treat it as constant outside of tests that call SetForcedTier.

func (SIMDTier) String

func (t SIMDTier) String() string

String returns the wire name used by simdTierEnv and by the CI gates that assert which tier a job selected. Do not change these spellings.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL