Skip to content

dist #

vsl.dist

vsl.dist provides histogram binning, density estimates, and text rendering for numeric samples. Histogram stores finite, strictly increasing bin boundaries and counts. Bins are left-closed and right-open, except the last bin includes its right boundary, matching NumPy histogram edge semantics.

API Purpose
Histogram.new(stations) Create a histogram from bin boundaries.
find_bin(x) Return the matching bin index, -1 when outside the range, or an error for invalid edges/NaN.
count(values, clear) Count values, optionally resetting prior counts first.
count_with_policy(values, clear, policy) Count finite values using stats.NonFinitePolicy; return the sample count for density normalization.
gen_labels(format) Format the bins as display labels.
density(nsamples) Estimate per-bin density using each bin's width and the total sample count.
density_area(nsamples) Integrate the density estimate across all bins.
text_hist(labels, counts, barlen) Render labeled counts as a text chart.
build_text_hist(...) Build a histogram and render it in one call.
import vsl.dist

mut histogram := dist.Histogram.new([0.0, 1.0, 2.0, 3.0])
histogram.count([0.2, 0.7, 1.4, 2.8], true)!
labels := histogram.gen_labels('%g')!
println(dist.text_hist(labels, histogram.counts, 0)!)
println(histogram.density(4)!)

For non-uniform bins, each density is count / (sample_count * bin_width). Values outside the bin range still contribute to sample_count; therefore density_area is the fraction of samples that fell within the histogram range. count_with_policy returns the number of finite observations, including those outside the bin range; pass that count to density when using .omit. It keeps existing counts unchanged on rejected inputs. Its .propagate mode returns an error when a non-finite value appears because integer bin counts cannot represent propagated NaN. Weighted histogram counts and automatic bin selection expose matching *_with_policy variants; omitted weighted pairs do not contribute to bins or the returned normalization weight. The legacy unweighted Histogram.count rejects NaN but treats infinities as out-of-range observations. Legacy weighted histogram counting rejects all non-finite values and weights; automatic bin selection rejects non-finite samples.

See the histogram example and hist.v for formatting and boundary behavior.

Seeded random numbers and distributions

vsl.dist also provides independent, reproducible random streams and common distribution samplers without global state.

RNG.new(seed) creates a PCG32 generator (XSH-RR output, splitmix64 seeding). A given seed reproduces the same sequence for the documented algorithm version. Each generator owns its state, so two streams never interfere. uniform() returns a draw strictly inside (0, 1) using 52 bits of precision, whose +0.5 offset stays exact and whose maximum is 1 - 2^-53; logarithms of draws are always finite. The 52-bit construction defines the seed-to-output mapping.

import vsl.dist

mut rng := dist.RNG.new(42)
value := rng.uniform() // strictly in (0, 1)
whole := rng.integer(1, 6)! // inclusive range
standard_normal := rng.normal() // Box-Muller with a cached spare

split() derives a child stream from the parent's next 64-bit draw, advancing the parent. fork(index) derives a child from the parent's seed plus an index without advancing it; it takes a read-only receiver, so many named streams are reproducible.

Samplers take mut rng as their first argument:

  • uniform_sample(rng, low, high), normal_sample(rng, mu, sigma), exponential_sample(rng, lambda)
  • gamma_sample(rng, shape, scale), beta_sample(rng, a, b)
  • binomial_sample(rng, n, p), poisson_sample(rng, lambda)

Density and distribution functions are pure: normal_pdf, normal_cdf, exponential_pdf, exponential_cdf, uniform_pdf, uniform_cdf.

import vsl.dist

mut rng := dist.RNG.new(7)
draw := dist.normal_sample(mut rng, 10.0, 2.0)!
probability := dist.normal_cdf(1.96, 0.0, 1.0)!
println('draw=${draw}, P(Z<=1.96)=${probability:.6f}')

Numerical limitations and supported bounds

  • gamma_sample uses Marsaglia-Tsang rejection for shape >= 1 and the boost trick below it; its accuracy is not guaranteed for extreme shapes.
  • beta_sample forms the gamma ratio in log space, so shapes below 1 (where the boost factor underflows) and very large shapes remain finite in (0, 1).
  • binomial_sample is exact but O(n) Bernoulli trials. It accepts 0 <= n <= 1000000 and rejects larger n instead of stalling; large n needs a normal or Poisson approximation.
  • poisson_sample uses the product method below lambda = 30 and a rounded normal approximation above it; the large-rate branch is explicitly an approximation, so skewness near lambda = 30 is not exact. It accepts 0 < lambda <= 1e9, a bound representable as an int on every build, and rejects larger finite rates.
  • All samplers reject non-finite or out-of-domain parameters.

See the simulation example.

fn beta_sample #

fn beta_sample(mut rng &RNG, a f64, b f64) !f64

beta_sample draws from Beta(a, b) via two gamma draws. The ratio is formed in log space, so small shapes (whose boost factor underflows) and large shapes (whose draws may overflow) still produce a finite value in (0, 1).

fn binomial_sample #

fn binomial_sample(mut rng &RNG, n int, p f64) !int

binomial_sample draws from Binomial(n, p) by summing Bernoulli trials. It is exact but O(n), so n is capped at max_binomial_n; larger n needs an approximation and is rejected rather than silently stalling.

fn build_text_hist #

fn build_text_hist(xmin f64, xmax f64, nstations int, values []f64, numfmt string, barlen int) !string

build_text_hist builds a text histogram

fn exponential_cdf #

fn exponential_cdf(x f64, lambda f64) !f64

exponential_cdf is the Exp(lambda) cumulative distribution function.

fn exponential_pdf #

fn exponential_pdf(x f64, lambda f64) !f64

exponential_pdf is the Exp(lambda) density; it is zero for negative x.

fn exponential_sample #

fn exponential_sample(mut rng &RNG, lambda f64) !f64

exponential_sample draws from Exp(lambda) with rate lambda > 0.

fn gamma_sample #

fn gamma_sample(mut rng &RNG, shape f64, scale f64) !f64

gamma_sample draws from Gamma(shape, scale) using Marsaglia-Tsang rejection for shape >= 1 and the boost trick below it. Both parameters must be positive.

fn histogram_bin_edges #

fn histogram_bin_edges(values []f64, rule HistogramBinRule) ![]f64

histogram_bin_edges returns equal-width edges selected from the finite sample. Constant samples use one bin spanning value +/- 0.5.

fn histogram_bin_edges_in_range #

fn histogram_bin_edges_in_range(values []f64, rule HistogramBinRule, lower f64, upper f64) ![]f64

histogram_bin_edges_in_range selects edges over an explicit finite interval. Only observations inside the closed interval influence the bin rule. Samples outside it do not contribute; an interval containing no observations errors.

fn histogram_bin_edges_in_range_with_policy #

fn histogram_bin_edges_in_range_with_policy(values []f64, rule HistogramBinRule, lower f64, upper f64, policy stats.NonFinitePolicy) ![]f64

histogram_bin_edges_in_range_with_policy applies a non-finite sample policy before selecting edges inside the explicit interval.

fn histogram_bin_edges_with_policy #

fn histogram_bin_edges_with_policy(values []f64, rule HistogramBinRule, policy stats.NonFinitePolicy) ![]f64

histogram_bin_edges_with_policy selects edges after applying a non-finite sample policy. Propagation is undefined for bin-edge selection and errors when any sample is non-finite.

fn normal_cdf #

fn normal_cdf(x f64, mu f64, sigma f64) !f64

normal_cdf is the N(mu, sigma^2) cumulative distribution function.

fn normal_pdf #

fn normal_pdf(x f64, mu f64, sigma f64) !f64

normal_pdf is the N(mu, sigma^2) density.

fn normal_sample #

fn normal_sample(mut rng &RNG, mu f64, sigma f64) !f64

normal_sample draws from N(mu, sigma^2). sigma must be positive and finite.

fn poisson_sample #

fn poisson_sample(mut rng &RNG, lambda f64) !int

poisson_sample draws from Poisson(lambda). Small rates use the product method; lambda >= 30 uses a rounded normal approximation, documented as an approximation rather than an exact draw. Rates above max_poisson_lambda are rejected so the int result stays representable on every int width.

fn text_hist #

fn text_hist(labels []string, counts []int, barlen int) !string

text_hist prints a text histogram

fn uniform_cdf #

fn uniform_cdf(x f64, a f64, b f64) !f64

uniform_cdf is the U(a, b) cumulative distribution function.

fn uniform_pdf #

fn uniform_pdf(x f64, a f64, b f64) !f64

uniform_pdf is the U(a, b) density, zero outside the interval.

fn uniform_sample #

fn uniform_sample(mut rng &RNG, low f64, high f64) !f64

uniform_sample draws from U(low, high). The interval must be non-empty.

fn Histogram.new #

fn Histogram.new(stations []f64) &Histogram

Histogram.new returns an histogram struct from a given list of stations

fn HistogramBinRule.from #

fn HistogramBinRule.from[W](input W) !HistogramBinRule

from returns the HistogramBinRule value of an integer or of a field name, or an error if there is none.

fn RNG.new #

fn RNG.new(seed u64) &RNG

RNG.new returns a generator initialized from seed.

fn WeightedHistogram.new #

fn WeightedHistogram.new(stations []f64) &WeightedHistogram

WeightedHistogram.new creates weighted bins using the same edge convention as Histogram: left-closed bins, with the final right edge included.

enum HistogramBinRule #

enum HistogramBinRule {
	auto
	fd
	doane
	scott
	stone
	rice
	sturges
	sqrt
}

HistogramBinRule selects a NumPy-compatible automatic bin-width estimator.

struct Histogram #

struct Histogram {
pub mut:
	stations []f64 // stations
	counts   []int // counts
}

Histogram defines a public data structure for this module.

fn (Histogram) find_bin #

fn (o Histogram) find_bin(x f64) !int

find_bin finds where x falls in returns -1 if x is outside the range

fn (Histogram) count #

fn (mut o Histogram) count(vals []f64, clear bool) !

count counts how many items fall within each bin

fn (Histogram) count_with_policy #

fn (mut o Histogram) count_with_policy(vals []f64, clear bool, policy stats.NonFinitePolicy) !int

count_with_policy counts finite observations according to the selected policy. Propagation is undefined for integer bin counts, so it returns an error if any non-finite observation is present.

fn (Histogram) gen_labels #

fn (o Histogram) gen_labels(numfmt string) ![]string

gen_labels generate nice labels identifying bins

fn (Histogram) density #

fn (o Histogram) density(nsamples int) ![]f64

density returns per-bin probability densities using each bin's actual width. nsamples is the total number of observations, including those outside the histogram range; therefore the integrated density is the in-range fraction.

fn (Histogram) density_area #

fn (o Histogram) density_area(nsamples int) !f64

density_area integrates per-bin densities over the histogram range.

struct RNG #

struct RNG {
pub:
	seed u64
mut:
	state u64
	inc   u64
	spare f64 = math.nan()
}

RNG is a seeded PCG32 generator. Each instance owns its state, so independent generators never interfere. A given seed reproduces the same sequence for a documented algorithm version (PCG-XSH-RR 32, splitmix64 seeding).

fn (RNG) next_u32 #

fn (mut rng RNG) next_u32() u32

next_u32 returns the next 32-bit value from the generator.

fn (RNG) next_u64 #

fn (mut rng RNG) next_u64() u64

next_u64 combines two 32-bit draws into a 64-bit value.

fn (RNG) uniform #

fn (mut rng RNG) uniform() f64

uniform returns a value strictly inside (0, 1) using 52 bits of precision. The +0.5 offset is exact at this width, so even the largest draw rounds to 1 - 2^-53 instead of 1.0; logarithms of results are always finite.

fn (RNG) normal #

fn (mut rng RNG) normal() f64

normal returns a standard normal draw using Box-Muller with a cached spare.

fn (RNG) integer #

fn (mut rng RNG) integer(low int, high int) !int

integer returns a uniform integer in the inclusive range [low, high].

fn (RNG) split #

fn (mut rng RNG) split() &RNG

split derives a new independent stream from the current generator. Advancing the child never changes the parent, and both are reproducible from seeds.

fn (RNG) fork #

fn (rng &RNG) fork(index u64) &RNG

fork returns an independent generator seeded from a fixed seed without advancing the caller. Useful when many streams must be reproducible.

struct WeightedHistogram #

struct WeightedHistogram {
pub mut:
	stations []f64 // bin edges
	counts   []f64 // accumulated weight per bin
}

WeightedHistogram accumulates non-negative observation weights in fixed bins.

fn (WeightedHistogram) count #

fn (mut o WeightedHistogram) count(values []f64, weights []f64, clear bool) !f64

count adds each sample's non-negative weight to its bin and returns the total weight from this call, including observations outside the range. clear controls whether previous bin weights are retained. When accumulating calls with clear: false, sum their returned weights for density normalization.

fn (WeightedHistogram) count_with_policy #

fn (mut o WeightedHistogram) count_with_policy(values []f64, weights []f64, clear bool, policy stats.NonFinitePolicy) !f64

count_with_policy accumulates finite value/weight pairs. Under omit, pairs with a non-finite value or weight are excluded from both bins and the returned normalization weight. Propagation is undefined for histogram counts and returns an error when any pair is non-finite.

fn (WeightedHistogram) density #

fn (o WeightedHistogram) density(total_weight f64) ![]f64

density returns each bin's accumulated weight fraction divided by its width. total_weight includes observations outside the range, so the integrated density is the fraction of total weight that fell inside the histogram.

fn (WeightedHistogram) density_area #

fn (o WeightedHistogram) density_area(total_weight f64) !f64

density_area integrates densities over the configured range.