`EventBuilder` could set weights and nothing else, so `prior` and
`drift_scale` were reachable only through the typed
`Event`/`Team`/`Member` shape plus `add_events`. Which ingestion route a
competitor arrived through decided whether it could be configured.
`members(...)` takes `Member` values directly, so `Member`'s own builder
expresses everything. `team(...)` stays the common case.
One escape hatch rather than `priors` and `drift_scales` setters beside
`weights`, as the issue suggested and then argued against itself: a
parallel array per field means a parallel length check per field, and
each one is a new way to get the lengths wrong. `Member` already has a
builder; this just lets the fluent path reach it.
`record_winner`/`record_draw` are deliberately left alone. They are the
two-argument convenience path, and extending them would be a breaking
signature change. The issue's reason for wanting them extended has also
weakened: it said a competitor arriving through them was "permanently
stuck on the history defaults", and since 8c087ad that is no longer true
— a later `add_events` carrying the `Member` refits the whole history.
Measured, late configuration through that route reaches mu 40.000000000,
identical to configuring from the start.
Refs #37
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hcFjNDmHXZF8URGLku5zZ
182 lines
6.2 KiB
Rust
182 lines
6.2 KiB
Rust
use smallvec::SmallVec;
|
|
|
|
use crate::{
|
|
InferenceError, Outcome,
|
|
drift::Drift,
|
|
event::{Event, Member, Team},
|
|
history::History,
|
|
observer::Observer,
|
|
time::Time,
|
|
};
|
|
|
|
pub struct EventBuilder<'h, T, D, O, K>
|
|
where
|
|
T: Time,
|
|
D: Drift<T>,
|
|
O: Observer<T>,
|
|
K: Eq + std::hash::Hash + Clone,
|
|
{
|
|
history: &'h mut History<T, D, O, K>,
|
|
event: Event<T, K>,
|
|
current_team_idx: Option<usize>,
|
|
/// First validation failure seen while building, surfaced by `commit`.
|
|
///
|
|
/// The setters return `Self` so the chain stays fluent; they cannot return
|
|
/// a `Result` without breaking that. Recording the failure and reporting it
|
|
/// at `commit` keeps the check enforced in release, where the previous
|
|
/// `debug_assert!` was compiled out and a mismatched event was ingested
|
|
/// silently.
|
|
error: Option<InferenceError>,
|
|
}
|
|
|
|
impl<'h, T, D, O, K> EventBuilder<'h, T, D, O, K>
|
|
where
|
|
T: Time,
|
|
D: Drift<T>,
|
|
O: Observer<T>,
|
|
K: Eq + std::hash::Hash + Clone,
|
|
{
|
|
pub(crate) fn new(history: &'h mut History<T, D, O, K>, time: T) -> Self {
|
|
Self {
|
|
history,
|
|
event: Event {
|
|
time,
|
|
teams: SmallVec::new(),
|
|
outcome: Outcome::Ranked(SmallVec::new()),
|
|
},
|
|
current_team_idx: None,
|
|
error: None,
|
|
}
|
|
}
|
|
|
|
/// Add a team by its member keys (weight 1.0 each, no prior overrides).
|
|
///
|
|
/// Use [`EventBuilder::members`] to set `prior` or `drift_scale`.
|
|
pub fn team<I: IntoIterator<Item = K>>(mut self, keys: I) -> Self {
|
|
let members: SmallVec<[Member<K>; 4]> = keys.into_iter().map(Member::new).collect();
|
|
self.event.teams.push(Team { members });
|
|
self.current_team_idx = Some(self.event.teams.len() - 1);
|
|
self
|
|
}
|
|
|
|
/// Add a team from fully-specified [`Member`] values.
|
|
///
|
|
/// [`EventBuilder::team`] is the common case and builds members with
|
|
/// `Member::new`, which leaves `prior` and `drift_scale` unset. This is the
|
|
/// escape hatch for when they matter:
|
|
///
|
|
/// ```
|
|
/// # use trueskill_tt::{Gaussian, History, Member};
|
|
/// # let mut h = History::builder().build();
|
|
/// h.event(0)
|
|
/// .team(["player"])
|
|
/// .members([Member::new("layout_7")
|
|
/// .with_drift_scale(0.0)
|
|
/// .with_prior(Gaussian::from_ms(0.0, 1.0))])
|
|
/// .ranking([0, 1])
|
|
/// .commit()?;
|
|
/// # Ok::<(), trueskill_tt::InferenceError>(())
|
|
/// ```
|
|
///
|
|
/// One method rather than a `priors` and a `drift_scales` setter beside
|
|
/// `weights`: those would have to grow a parallel array — and a parallel
|
|
/// length check — every time `Member` gains a field, and each one would be
|
|
/// a new way to get the lengths wrong. `Member`'s own builder already
|
|
/// expresses all of it.
|
|
///
|
|
/// `prior` and `drift_scale` are competitor configuration rather than
|
|
/// per-event values; see [`Member`] for what that means for a key the
|
|
/// history already knows.
|
|
pub fn members<I: IntoIterator<Item = Member<K>>>(mut self, members: I) -> Self {
|
|
self.event.teams.push(Team::with_members(members));
|
|
self.current_team_idx = Some(self.event.teams.len() - 1);
|
|
self
|
|
}
|
|
|
|
/// Set per-member weights for the most recently added team.
|
|
///
|
|
/// A length mismatch is recorded and returned by [`EventBuilder::commit`]
|
|
/// as `InferenceError::MismatchedShape`, in both debug and release. The
|
|
/// weights are not applied in that case, so a partially-weighted team
|
|
/// cannot reach the history.
|
|
///
|
|
/// # Panics
|
|
///
|
|
/// Panics if called before any `.team(...)`.
|
|
pub fn weights<I: IntoIterator<Item = f64>>(mut self, weights: I) -> Self {
|
|
let idx = self
|
|
.current_team_idx
|
|
.expect(".weights(...) called before any .team(...)");
|
|
|
|
let ws: Vec<f64> = weights.into_iter().collect();
|
|
let team = &mut self.event.teams[idx];
|
|
|
|
if ws.len() != team.members.len() {
|
|
self.error.get_or_insert(InferenceError::MismatchedShape {
|
|
kind: "weights",
|
|
expected: team.members.len(),
|
|
got: ws.len(),
|
|
});
|
|
|
|
return self;
|
|
}
|
|
|
|
for (m, w) in team.members.iter_mut().zip(ws) {
|
|
m.weight = w;
|
|
}
|
|
|
|
self
|
|
}
|
|
|
|
/// Set explicit ranks per team (length must equal number of teams).
|
|
pub fn ranking<I: IntoIterator<Item = u32>>(mut self, ranks: I) -> Self {
|
|
self.event.outcome = Outcome::ranking(ranks);
|
|
self
|
|
}
|
|
|
|
/// Set explicit per-team continuous scores; higher = better.
|
|
pub fn scores<I: IntoIterator<Item = f64>>(mut self, scores: I) -> Self {
|
|
self.event.outcome = crate::Outcome::scores(scores);
|
|
self
|
|
}
|
|
|
|
/// Set explicit per-team continuous scores with a per-event noise override.
|
|
///
|
|
/// `sigma` overrides `HistoryBuilder::score_sigma` for this event only.
|
|
/// Must be `> 0.0`. Constructing the outcome with a non-positive or NaN
|
|
/// sigma is allowed; the value is rejected with
|
|
/// `InferenceError::InvalidParameter` when the event is ingested, so
|
|
/// callers get an error from `commit` rather than a panic.
|
|
pub fn scores_with_sigma<I: IntoIterator<Item = f64>>(mut self, scores: I, sigma: f64) -> Self {
|
|
self.event.outcome = crate::Outcome::scores_with_sigma(scores, sigma);
|
|
self
|
|
}
|
|
|
|
/// Mark team `winner_idx` as winner; others tied for last.
|
|
pub fn winner(mut self, winner_idx: u32) -> Self {
|
|
self.event.outcome = Outcome::winner(winner_idx, self.event.teams.len() as u32);
|
|
self
|
|
}
|
|
|
|
/// All teams tied.
|
|
pub fn draw(mut self) -> Self {
|
|
self.event.outcome = Outcome::draw(self.event.teams.len() as u32);
|
|
self
|
|
}
|
|
|
|
/// Commit the event to the history.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns the first validation failure recorded while building — see
|
|
/// [`EventBuilder::weights`] — otherwise forwards to
|
|
/// [`History::add_events`] and returns its errors.
|
|
pub fn commit(self) -> Result<(), InferenceError> {
|
|
if let Some(error) = self.error {
|
|
return Err(error);
|
|
}
|
|
|
|
self.history.add_events(std::iter::once(self.event))
|
|
}
|
|
}
|