---
title: The uniform distribution
summary: skoro's uniform distribution is the law of a space whose reference measure has finite mass, the rotations and the categorical spaces among them, with a constant term, an exact sampler on the host, and a residual of no components, so that a linearization reads it as a factor with no rows; it is how a model says that nothing is known of a quantity.
order: 8
depends_on: [concepts/spaces, concepts/terms, concepts/the-normal, uniform, improper-gaussian]
---

# The uniform distribution

A model often has to say that nothing is known of a quantity before the data are seen: the heading of a robot at start-up, the first pose of a graph, which of two hypotheses holds.
On a space whose reference measure $\nu$ has [finite mass](/concepts/spaces.md#masses-and-uniform-points) there is a law that says exactly that, the uniform distribution $\nu / \nu(\manifold)$.
It lives in a crate of its own, `skoro-uniform`, built on the core's public interface and on one role of `skoro-normal`.
A normal with a large scale is not a substitute on a curved type: [the normal's page](/concepts/the-normal.md#a-large-scale-on-a-curved-type) says why.

The spaces it takes are those of finite mass: `Categorical(n)`, `Boolean` among them, with counting measure of mass $n$; an embedded type that declares its mass, such as the [rotations](/concepts/rotations-and-motions.md), of mass $8\pi^2$; and products of embedded types that declare their masses, a product's factors being continuous.
The note on [the uniform distribution](/math/uniform.md) has the mathematics.

## The term

The uniform distribution has no parameters, only its space:

From `crates/skoro-uniform/src/uniform.rs`, lines 26–50:

```rust
/// The uniform distribution on a space of finite mass: the law `ν / ν(𝕏)`, with no parameters.
#[derive(Clone, Debug)]
pub struct Uniform {
    space: Space,
}

impl Uniform {
    /// The uniform distribution on the space `marker` declares.
    pub fn on<T: Declares>(marker: T) -> Uniform {
        Uniform::in_space(marker.space())
    }

    /// The uniform distribution on `space`, for a product or any space without a marker.
    pub fn in_space(space: Space) -> Uniform {
        Uniform { space }
    }

    pub fn space(&self) -> &Space {
        &self.space
    }

    /// `log ν(𝕏)` (`NoMass` for a space without a finite mass).
    pub fn log_mass(&self) -> Result<f64, Error> {
        self.space.log_mass()
    }
```

Its log-density is the constant $-\log \nu(\manifold)$.
`score` adds it as the term of the quantity, with an exact sampler and a residual of no components:

From `crates/skoro-uniform/src/uniform.rs`, lines 52–86:

```rust
/// Scores `x`: the constant term `-log ν(𝕏)`, its exact sampler, and a residual of no
/// components. Refuses a space without a finite mass (`NoMass`) and an `x` of another space
/// (`SpaceMismatch` of `skoro.uniform.log_density`), recording the refusal at the caller's
/// line. [`sample`](skoro_core::scope::sample) declares a quantity and scores it by a uniform
/// in one call.
///
/// The term is a call of a composite of `x` that does not read it: a mapped node, so a
/// log-density, and one of its own for each quantity scored; refused by the core's check of
/// an operation's inputs when `x` is of another space; and of zero derivative maps. The
/// residual is what a linearization reads of a continuous quantity, a factor with no rows.
#[track_caller]
pub fn score(&self, x: impl Into<QDyn>) -> TermHandle {
    let x = x.into();
    let term = self.log_mass().and_then(|log_mass| {
        let space = self.space.clone();
        Composite::define(
            "skoro.uniform.log_density",
            vec![Param::Space(space.clone())],
            &[space],
            |_| (-constant(Real, log_mass)).untyped(),
        )
        .map_err(|failure| failure.error)
    });
    let log_density = match term {
        Ok(composite) => composite.call(&[x]),
        Err(error) => refuse(error, &[x]),
    };
    score(x.narrow::<Scored>(), log_density.narrow())
        .sampler(Sampler {
            sample: Arc::new(UniformSample::new(self.space.clone())),
            inputs: Vec::new(),
            log_density: None,
        })
        .bind(&roles::RESIDUAL, constant(VectorDyn(0), &[] as &[f64]))
}
```

The term is a call of a composite of the quantity that does not read it.
A call is a mapped node, so it is a log-density, and each call is a node of its own, so two quantities have two terms; the composite takes the distribution's space, so a quantity of another space is refused by the core's check of an operation's inputs, with `SpaceMismatch` of `skoro.uniform.log_density`; and its body is a constant, so its gradient and its Hessian products are zero, and it moves no mode and no step.
A space without a finite mass is refused with the core's `NoMass`, at the caller's line, as the normal refuses what it cannot be exact on.
A uniform is a [`Distribution`](/concepts/terms.md#a-term) by this `score`, so the core's `sample` makes a quantity and scores it by one in one call:

From `crates/skoro-uniform/src/uniform.rs`, lines 89–94:

```rust
impl Distribution for Uniform {
    #[track_caller]
    fn score(&self, x: QDyn) -> TermHandle {
        Uniform::score(self, x)
    }
}
```

The uniform binds the normal's residual role, which means the same of any term with a whitened residual, and no other: it has no mean, no scale, no tangent and no information to give a root of.

## The sampler

A uniform point is drawn on the host, from the variates of the quantity's random key: by the space's declared draw, from as many variates as it has dimensions, or, on a categorical space, as $\lfloor n u \rfloor$ from one variate $u$:

From `crates/skoro-uniform/src/sample.rs`, lines 30–64:

```rust
    fn draw(&self, _: &[Value], keys: &[Key], target: &Target) -> Value {
        let (rows, n) = (keys.len(), self.space.storage());
        match self.space.cardinality() {
            Some(n) => {
                let categories: Vec<i64> = keys
                    .iter()
                    .map(|key| category(n, key.uniforms(1)[0]))
                    .collect();
                match Integers::from_host(&categories, rows, 1, target) {
                    Ok(integers) => Value::Discrete(integers),
                    Err(_) => {
                        unreachable!("a category is below n, which the target's integers hold")
                    }
                }
            }
            None => {
                let d = self.space.dimension().unwrap_or(0);
                let mut points = vec![0.0; rows * n];
                // A space of no storage has no rows to fill.
                for (key, point) in keys.iter().zip(points.chunks_mut(n.max(1))) {
                    if self.space.draw_uniform(&key.uniforms(d), point).is_err() {
                        unreachable!("a term is added on a space of finite mass alone")
                    }
                }
                Value::Continuous(Points::from_host(&points, rows, n, target))
            }
        }
    }
}

/// `⌊n u⌋`, never `n`: the category of a variate `u` in (0, 1), for `n` of one or more. The
/// product is rounded to a double, and the minimum keeps that rounding from ever returning `n`.
pub(crate) fn category(n: usize, u: f64) -> i64 {
    ((n as f64 * u) as usize).min(n - 1) as i64
}
```

The minimum keeps the rounding of $n u$ from ever giving $n$.
The sampler is exact, so in a generation each uniform term cancels against its draw and leaves the [importance weight](/math/importance-weights.md) to the likelihoods.
In the model of a heading of which nothing is known, read by a compass, with a coin beside it, the weight of each drawn row is the compass's log-density at the drawn heading, and neither $\log 8\pi^2$ nor $\log 2$ is in it:

From `crates/skoro-uniform/tests/sample.rs`, lines 128–144:

```rust
let mut writer = Writer::new();
let (heading, compass) = writer
    .build(|| {
        let heading = sample("heading", Rotation, Uniform::on(Rotation));
        sample("outlier", Boolean, Uniform::on(Boolean));
        let noise = Normal::on(Rotation, heading, Scale::sd(0.05));
        let compass = sample("compass", Rotation, noise);
        (heading, compass)
    })
    .unwrap();
let snapshot = writer.snapshot();
let (rows, target) = (16, Target::host());
let reading = [0.5, 0.1, -0.3, 0.7];
let given = Observations::new().observe(compass, reading);
let generated = snapshot
    .generate(&given, &Key::from_seed(41), rows, &target)
    .unwrap();
```

## In a linearization

A [linearization](/concepts/linearization.md) reads the residual of every term with a free quantity, and the uniform's has no components.
Its factor is the [improper Gaussian factor](/math/improper-gaussian.md) with no rows, no linear part and the constant $-\log \nu(\manifold)$: flat in every direction, exactly.
It adds nothing to the rows a step is solved from, and its constant stays in the objective and in the evidence of a Laplace approximation, so the linearizer takes it with no change of its own.
A heading under a uniform prior and read by a compass is estimated where the compass reads it.
A quantity that no other term bears on has no rows at all, and its elimination reports it `Undetermined`, as it should: its posterior is uniform and has no mode.
An observed categorical quantity makes its term a constant of the data, and a free one is refused by a linearization as any free discrete quantity is.

> [!DECISION] A crate of its own, and a term made of a composite
> The uniform is not a normal in any reading, so it is not a module of `skoro-normal`; it depends on that crate only for the residual role, whose meaning is shared.
> Its term is a composite of a constant rather than a primitive operation, which would need a kernel on every backend to compute a number, and a draw is a function of the host rather than a composite, since no pass crosses it.
> See [the implementation](/archive/uniform/implementation.md#the-distribution).
