it.grypho.scala.leonardo.probability

Members list

Type members

Classlikes

enum DistKind extends Keyworded

The distribution families this package knows.

The distribution families this package knows.

An enum rather than one case class per family: every family shares the same shape — a short parameter vector plus four kernels — so a single carrier keeps Session display, :save serialization and the parser to one case each instead of five.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
trait Keyworded
class Object
trait Matchable
class Any
Show all
object DistKind

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
DistKind.type
object Moments

The linearity rule table behind expect and variance.

The linearity rule table behind expect and variance.

This is the part that belongs in a computer algebra system rather than in a statistics library: E[aX + b] = a·E[X] + b is a rewrite, applied to the expression's structure before any number is computed, so it works while a and b are still free variables.

Structured exactly like scalar.Derive: a rule table, most specific first, with a give-up fallback. The give-up is None, which the calling node turns into "stay symbolic" — the termination guard every _Functional in this codebase shares.

What is deliberately not here. E[XY] = E[X]·E[Y] requires the factors to be independent, and nothing in the language expresses independence between two random variables. Asserting it would produce confidently wrong answers for correlated ones, so a product of two distinct random variables stays symbolic. A product where only one factor is random is fine, and is the a·X rule below.

Attributes

See also
Supertypes
class Object
trait Matchable
class Any
Self type
Moments.type
object Query

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Query.type
enum Query extends Keyworded

What a _DistributionQuery asks of a distribution.

What a _DistributionQuery asks of a distribution.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
trait Keyworded
class Object
trait Matchable
class Any
Show all

Why drawSamples or prbsSequence declined (F_0052 Decision A: the reason travels as data, the REPL prints it). The node itself stays as written.

Why drawSamples or prbsSequence declined (F_0052 Decision A: the reason travels as data, the REPL prints it). The node itself stays as written.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class _Bayes(prior: _Expression, likelihood: _Expression) extends _Expression

Bayes' theorem over a finite set of hypotheses: bayes(prior, likelihood) (F_0050).

Bayes' theorem over a finite set of hypotheses: bayes(prior, likelihood) (F_0050).

Two vectors of the same shape — a 1×n row or an n×1 column — give the normalised posterior pᵢ·Lᵢ / Σⱼ pⱼ·Lⱼ, in that same shape. No new carrier was needed: a row is what tabulate and eigen already return, and it is the form every textbook opens with.

Exact on exact input. When every entry of both vectors is a core._Rational the posterior is computed over the rationals and returned as the prior's own node rebuilt with exact cells, so a posterior of fractions stays a posterior of fractions; one inexact entry demotes the whole computation to Double, the float-contagion rule. The rebuild goes through the prior's core._MatrixShaped node, which is how this package yields a symbolic matrix without importing matrix.

Refuses, staying symbolic: a shape mismatch, an operand that is not a row or a column, a negative entry (neither a probability nor a likelihood), and zero evidence, Σ = 0, which has no posterior at all rather than a degenerate one.

Value parameters

likelihood

the likelihood of the observation under each hypothesis, the same shape

prior

the prior weights over the hypotheses, a row or a column

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
final case class _Distribution extends _Value

A probability distribution: a concrete core._Value, bindable in an Environment and round-trippable through :save.

A probability distribution: a concrete core._Value, bindable in an Environment and round-trippable through :save.

Construction routes through _Distribution.of, which validates the parameters, so every instance that exists is a well-formed distribution.

Value parameters

kind

the family

params

the family's parameters, in the order the grammar takes them

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
trait _Value
trait _Expression
class Object
trait Matchable
class Any
Show all
object _Distribution

Companion for _Distribution: the validating factory.

Companion for _Distribution: the validating factory.

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
case class _DistributionOf(kind: DistKind, args: List[_Expression]) extends _Expression

Builds a distribution from parameter expressions: normal(mu, sigma) and friends.

Builds a distribution from parameter expressions: normal(mu, sigma) and friends.

The node/value split _Matrix has with _MatrixValue: this is the symbolic form, whose eval folds to a _Distribution once every parameter reduces to a number. It keeps normal(m, s) meaningful while m and s are still free variables.

Value parameters

args

the parameter expressions, in the family's declared order

kind

the family

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _DistributionQuery(query: Query, dist: _Expression, args: List[_Expression]) extends _Expression

A numeric question about a distribution: pdf, cdf, prob or quantile.

A numeric question about a distribution: pdf, cdf, prob or quantile.

One node for all four rather than four nodes, for the same reason DistKind is one enum: they differ only in which kernel they call.

Why prob(d, lo, hi) and not P(X < 2). The grammar has no comparison operators — only = and ==, which build equations — so a predicate like X < 2 cannot be expressed. Adding `` would be a change to the expression language, not to this domain. An interval is the honest shape available today.

Value parameters

args

the query's own arguments (one for pdf/cdf/quantile, two for prob)

dist

the distribution expression

query

the question

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _Draw(dist: _Expression, n: _Expression, seed: _Expression, offset: Option[_Expression]) extends _Expression

draw(dist, n, seed[, offset]) — drawSamples as a node (F_0067): an n×1 column of draws. A refusal leaves the call as written, and detailed carries the reason.

draw(dist, n, seed[, offset]) — drawSamples as a node (F_0067): an n×1 column of draws. A refusal leaves the call as written, and detailed carries the reason.

Value parameters

dist

the distribution expression

n

the count

offset

the position in the stream, None for 0

seed

the seed

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _Expectation(e: _Expression, x: Option[_Variable]) extends _Expression

The expectation expect(e, X), or expect(d) for a distribution's own mean.

The expectation expect(e, X), or expect(d) for a distribution's own mean.

Why not E[·]. Square brackets are the matrix literal, so E[X] would parse as E times a one-element matrix. expect is unambiguous and needs no grammar change.

The one-argument form is the mean of a distribution; the two-argument form is E[e] where x names the random variable inside e, and is where the linearity rules live.

Value parameters

e

the expression whose expectation is wanted, or the distribution itself

x

the random variable, or None for the one-argument form

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _Posterior(prior: _Expression, likelihood: _Expression, data: _Expression) extends _Expression

Conjugate updating: posterior(prior, likelihood, data) (F_0050).

Conjugate updating: posterior(prior, likelihood, data) (F_0050).

The likelihood is written as the family with its unknown parameter left free — posterior(betadist(2, 2), binomial(10, p), 7) — where p is the one free name, the same exactly-one-free-name rule Predicate applies to a random variable. The answer is an ordinary _Distribution, so pdf/cdf/quantile/expect/variance apply to it unchanged and nothing downstream learns a new type.

The table, each arm validating its data:

prior likelihood (free) data posterior
betadist(a, b) binomial(n, p) a count k in 0..n betadist(a + k, b + n − k)
gammadist(k, rate) poisson(l) observations, non-negative integers gammadist(k + Σx, rate + n)
normal(μ₀, σ₀) normal(μ, σ), σ known observations precision-weighted normal(μₙ, σₙ)

Observations are a 1×n row or an n×1 column; a single number is a sample of one.

Everything else stays symbolic: a pair outside the table, two free names or none, a likelihood whose free slot is not the conjugate parameter (binomial(n, 0.5)), the Normal–Normal case with unknown σ (that needs the Normal-inverse-gamma family, a two-parameter carrier this package does not have), and invalid data. A general posterior — an unnormalised density with no closed form — is deliberately not attempted: it needs numerical integration over the parameter space or sampling, which is a package rather than a function, and declining beats a confident approximation.

Exactness: a _Distribution stores Double parameters, so a conjugate posterior is a Double result even from exact input — the lu/qr precedent, demote rather than refuse. Only _Bayes is exact.

Value parameters

data

the observation: a count, a number, or a vector of observations

likelihood

the sampling family with its unknown parameter free

prior

a distribution expression, the prior

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _Prbs(order: _Expression, n: _Expression, seed: _Expression) extends _Expression

prbs(order, n, seed) — prbsSequence as a node (F_0067): an n×1 column of ±1. A refusal leaves the call as written, and detailed carries the reason.

prbs(order, n, seed) — prbsSequence as a node (F_0067): an n×1 column of ±1. A refusal leaves the call as written, and detailed carries the reason.

Value parameters

n

the count

order

the register length

seed

the seed

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all
case class _Variance(e: _Expression, x: Option[_Variable]) extends _Expression

The variance variance(e, X), or variance(d) for a distribution's own variance.

The variance variance(e, X), or variance(d) for a distribution's own variance.

Value parameters

e

the expression whose variance is wanted, or the distribution itself

x

the random variable, or None for the one-argument form

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait _Expression
class Object
trait Matchable
class Any
Show all

Value members

Concrete methods

def drawSamples(d: _Distribution, n: Int, seed: Long, offset: Long = ...): Either[SamplingFailure, Vector[Double]]

n draws from d, the offset-th of the stream for seed onwards (F_0067, MPC T3-03).

n draws from d, the offset-th of the stream for seed onwards (F_0067, MPC T3-03).

By inversion: each draw is the quantile of one uniform, through the same quantileOf the quantile query uses — so no family needs a sampler of its own, and a family added later can be drawn from as soon as it has a cdf. A discrete family yields integers.

The seed is the state (Decision B): nothing is remembered between calls, and drawSamples(d, n, s, o) ++ drawSamples(d, m, s, o + n) is drawSamples(d, n + m, s, o) exactly — a long stream can be taken in pieces. A control loop that wants fresh noise each cycle passes the cycle number as the seed, or the running count as the offset.

Reproducibility (Decision C): the uniforms are bit-identical on the JVM and Scala.js. A draw goes through the family's cdf, whose exp and log each platform computes itself, so a continuous draw agrees across platforms to rounding (well within 1e-12 relative) rather than to the bit.

Value parameters

d

the distribution

n

how many draws, 1 … MaxDrawCount

offset

the position in the stream to start from, ≥ 0

seed

the seed, any integer

Attributes

Returns

the draws, or why there are none

def prbsSequence(order: Int, n: Int, seed: Long): Either[SamplingFailure, Vector[Double]]

A maximal-length pseudo-random binary sequence of ±1 (F_0067, MPC T3-03): the output of a linear feedback shift register over a primitive polynomial, +1 for a set bit.

A maximal-length pseudo-random binary sequence of ±1 (F_0067, MPC T3-03): the output of a linear feedback shift register over a primitive polynomial, +1 for a set bit.

Its period is 2^order − 1, and each period holds exactly one more +1 than −1 — the property that makes it a persistently exciting input for identification (F_0060). The seed picks the register's starting state, i.e. the phase within the period, so two seeds give rotations of one sequence. A longer n than the period repeats it.

Value parameters

n

how many terms, 1 … MaxPrbsLength

order

the register length, MinPrbsOrder … MaxPrbsOrder

seed

the seed, any integer

Attributes

Returns

the sequence, or why there is none

Concrete fields

val MaxDrawCount: Int

The most samples one draw produces (F_0067).

The most samples one draw produces (F_0067).

Measured (2026-10-10) at the cap, JVM / Node: normal(0, 1) 1.8 / 3.3 s, poisson(4) 0.8 / 2.2 s, binomial(20, 0.3) 3.0 / 6.9 s — the slowest family on the slowest platform. An earlier probe on evenly spaced probabilities predicted 4.4 s for that last figure: random uniforms reach the tails, where the bisection's bracket takes longer to set. T3-03's own acceptance needs 10⁵ normal draws, which is why the cap is not lower; the figure is also Session.MaxSampleCount's, the other materialised sequence a user asks for by count.

The default of core.Limit.MaxDrawCount (F_0124): the Limits overload of drawSamples and the draw node read the caller's value.

Attributes

val MaxPrbsLength: Int

The most terms one prbs produces (F_0067): a step is a few integer operations, so the cost is the result itself — a million Doubles, eight megabytes. Measured at the cap: under 0.35 s on the JVM and on Node, through the library function and through the node. The default of core.Limit.MaxPrbsLength (F_0124).

The most terms one prbs produces (F_0067): a step is a few integer operations, so the cost is the result itself — a million Doubles, eight megabytes. Measured at the cap: under 0.35 s on the JVM and on Node, through the library function and through the node. The default of core.Limit.MaxPrbsLength (F_0124).

Attributes

val MaxPrbsOrder: Int

The highest PRBS order (F_0067). The table stops here because every entry is verified by running its full period in the suite — 2²⁰ − 1 steps is cheap on Node, 2³¹ is not, and an unverified primitive polynomial is a transcription that only looks right.

The highest PRBS order (F_0067). The table stops here because every entry is verified by running its full period in the suite — 2²⁰ − 1 steps is cheap on Node, 2³¹ is not, and an unverified primitive polynomial is a transcription that only looks right.

Attributes

val MinPrbsOrder: Int

The lowest PRBS order (F_0067): order 1 has no maximal sequence worth the name.

The lowest PRBS order (F_0067): order 1 has no maximal sequence worth the name.

Attributes