logaritmiskandClaude Opus 5 bb2a845882 feat!: N-team outcome prediction with draw mass, replacing the 2-team panic
`predict_outcome` asserted `teams.len() == 2` and returned `[p, 1 - p]`,
allocating no probability to a draw even with `p_draw > 0`. For a
draw-enabled model the numbers were simply wrong, at any team count.

It now returns `Result<Prediction, InferenceError>` and supports N teams.

Two algorithms, both deterministic:

- Who finishes first. Performances are independent Gaussians, so this
  separates into a one-dimensional integral per team rather than a
  multivariate orthant probability. Adaptive Gauss-Kronrod evaluates it
  to ~1e-15, matching the exact two-team closed form.
- A specific finishing order. The factor graph only constrains
  rank-adjacent teams, so a full order is a chain of local constraints,
  not a general orthant integral. That chain collapses into a sequential
  recursion over cumulative integrals: O(teams * grid) per order.

Fixed-node Gauss-Hermite is the obvious tool for the first and is a trap:
when a rival's sigma is small the CDF product becomes a step narrower
than the node spacing, and the nodes step over it. Measured 4.4e-4 off
the closed form on a mildly skewed matchup and 1.7e-2 on a small-sigma
one, while still returning something that looks like a probability.
Adaptive refinement is what makes that case safe, and
`win_probabilities_survive_a_rival_with_a_tiny_sigma` pins it down.

The acceptance test is an identity rather than a golden: the outcome
space is exhaustive and disjoint, so the probabilities sum to one. Any
drift is integration error and nothing else. Gauss-Hermite failed it at
4.4e-4; this holds to ~1e-9.

Also from #21: unknown keys are now reported rather than dropped, so a
team of strangers can no longer produce a confident-looking prediction.
`predict_quality` returns `Result` for the same reason.

BREAKING CHANGE: `predict_outcome` returns `Result<Prediction, _>`
instead of `Vec<f64>`; `predict_quality` returns `Result<f64, _>`.

Refs #21, #39

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hcFjNDmHXZF8URGLku5zZ
2026-09-07 14:55:11 +02:00

TrueSkill - Through Time

Rust port of TrueSkillThroughTime.py.

Other implementations

Drift

Skill drift models how a competitor's true skill can change between appearances. Each time they reappear after a gap, their skill uncertainty is widened by the drift model before the new evidence is incorporated.

Drift is represented by the Drift trait (src/drift.rs), generic over the history's time type:

pub trait Drift<T: Time>: Copy + Debug + Send + Sync {
    fn variance_delta(&self, from: &T, to: &T) -> f64;
    fn variance_for_elapsed(&self, elapsed: i64) -> f64;
}

Both methods return the amount to add to σ², not to σ. variance_delta works from two timestamps; variance_for_elapsed takes an already-computed elapsed count, and is used on the paths that cache it. Gaussian::forget applies the result entirely in variance space — from_mv(mu, variance() + variance_delta) — taking no square root.

That block is a quotation rather than a doctest. The custom-drift example below is compiled by CI, so it is what actually pins the signature.

ConstantDrift

The built-in ConstantDrift implements a linear random walk — skill uncertainty grows proportionally to time:

variance_delta = elapsed * γ²

This is the standard TrueSkill Through Time model. Pass a ConstantDrift(gamma) when constructing a Rating:

use trueskill_tt::{ConstantDrift, Gaussian, Rating};

// gamma = 0.1 means skill can shift ~0.1 per time unit.
let rating: Rating<i64, ConstantDrift> =
    Rating::new(Gaussian::from_ms(0.0, 6.0), 1.0, ConstantDrift(0.1));

assert_eq!(rating.drift().0, 0.1);

The type annotation is load-bearing: ConstantDrift implements Drift<T> for every T: Time, so without it T is ambiguous.

Custom drift

Implement Drift<T> to express any other model. For example, a drift that saturates after a long absence, with uncertainty growing as the square root of elapsed time instead of linearly:

use trueskill_tt::{Drift, Gaussian, History, Rating, Time};

#[derive(Clone, Copy, Debug)]
struct SqrtDrift {
    gamma: f64,
}

impl<T: Time> Drift<T> for SqrtDrift {
    fn variance_delta(&self, from: &T, to: &T) -> f64 {
        let elapsed = from.elapsed_to(to).max(0) as f64;
        elapsed.sqrt() * self.gamma * self.gamma
    }

    fn variance_for_elapsed(&self, elapsed: i64) -> f64 {
        (elapsed.max(0) as f64).sqrt() * self.gamma * self.gamma
    }
}

// On a single Rating:
let rating: Rating<i64, SqrtDrift> =
    Rating::new(Gaussian::from_ms(0.0, 6.0), 1.0, SqrtDrift { gamma: 0.5 });

// Or for a whole History, via the builder:
let history = History::builder().drift(SqrtDrift { gamma: 0.5 }).build();

assert_eq!(rating.beta(), 1.0);
assert_eq!(history.log_evidence(), 0.0);

HistoryBuilder::drift is the only way to set a history's drift model; there is no gamma() shorthand. The default is ConstantDrift(GAMMA).

Per-competitor drift

A History has one drift model, but individual competitors can scale it. Member::with_drift_scale(s) multiplies the drift variance that competitor accumulates, so s is in the same units as gamma: ConstantDrift(g) at scale s behaves exactly as ConstantDrift(g * s) would, for that competitor alone.

0.0 pins a competitor still. That is what makes a fixed reference point expressible in the same graph as moving competitors — a bot at a known strength, a rating floor, a course difficulty:

use trueskill_tt::{ConstantDrift, Event, History, Member, Outcome, Team};

let mut h = History::builder().drift(ConstantDrift(0.1)).build();

h.add_events(vec![Event {
    time: 0,
    teams: [
        Team::with_members([Member::new("player")]),
        // A course does not improve. Pin it, and the round's evidence
        // lands on the player instead of being split between the two.
        Team::with_members([Member::new("layout_7").with_drift_scale(0.0)]),
    ]
    .into_iter()
    .collect(),
    outcome: Outcome::winner(0, 2),
}])
.unwrap();

h.converge().unwrap();

Like with_prior, the scale is competitor configuration captured at first appearance — setting it on a key the history already knows has no effect. It must be finite and non-negative; ingestion otherwise fails with InferenceError::InvalidParameter.

Note that the fluent EventBuilder (h.event(t).team([...])) sets weights but not drift_scale or prior; those need the typed Event / Team / Member shape shown above.

Scored outcomes

Use Outcome::scores([...]) when you have continuous per-team scores rather than just ranks. Adjacent score margins flow into a MarginFactor that adds soft Gaussian evidence about the latent performance diff. Configure HistoryBuilder::score_sigma(σ) to control how much you trust the margins (smaller σ = more trust).

use trueskill_tt::History;

let mut h = History::builder().score_sigma(2.0).build();
h.event(1)
    .team(["alice"])
    .team(["bob"])
    .scores([21.0, 9.0])
    .commit()
    .unwrap();
h.converge().unwrap();

Todo

  • Implement approx for Gaussian
  • Add more tests from TrueSkillThroughTime.jl
  • Generalise a time axis — Time is now a trait (Untimed, i64), not an enum
  • Add examples (examples/atp.rs, examples/scored.rs)
  • Add Observer (Observer / NullObserver)
  • Benchmark the inference loop (benches/batch.rs, benches/history_converge.rs, benches/ingest.rs)
  • Cross-check quality() against sublee/trueskill — N-group support works and is covered by invariants, but no reference values are asserted

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

S
Description
No description provided
Readme
12 MiB
Languages
Rust 99.6%
Just 0.4%