score-set 0.2.0

A Rust library for building static weighted scoring operator sets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use crate::float::Float;
use crate::value::Value01;
use witnessed::Witnessed;

// ---------------------------------------------------------------------------
// Scorable — type-erased metric trait (Layer 3 foundation)
// ---------------------------------------------------------------------------

/// A type-erased metric that can be evaluated against input `I`.
///
/// This trait enables dynamic dispatch over heterogeneous metric types via
/// `Box<dyn Scorable<T, I>>`. It is the core abstraction behind
/// [`DynamicScoreSet`](crate::DynamicScoreSet).
///
/// Any [`Metric`](crate::Metric) can be converted into a
/// `Box<dyn Scorable<T, I>>` through the blanket implementation.
///
/// # Examples
///
/// ```ignore
/// use score_set::*;
///
/// let gc = metric("gc")
///     .measure().by(|dna: &&str| gc_ratio(dna))
///     .map01().by(|raw: &f64, _: &&str| Value01::witness(*raw).unwrap());
///
/// let dyn_metric: Box<dyn Scorable<f64, &str>> = Box::new(gc);
/// assert_eq!(dyn_metric.name(), "gc");
/// let score = dyn_metric.eval(&"ACGT");
/// ```
pub trait Scorable<T: Float, I> {
    /// Evaluate this metric against an input, producing a `[0, 1]` score.
    fn eval(&self, input: &I) -> Witnessed<T, Value01>;

    /// Return the metric's name.
    fn name(&self) -> &str;
}

// ---------------------------------------------------------------------------
// Blanket impl — any Metric is a Scorable
// ---------------------------------------------------------------------------

impl<T, I, Raw, M, F> Scorable<T, I> for crate::Metric<T, I, Raw, M, F>
where
    T: Float,
    M: Fn(&I) -> Raw,
    F: Fn(&Raw, &I) -> Witnessed<T, Value01>,
{
    #[inline]
    fn eval(&self, input: &I) -> Witnessed<T, Value01> {
        crate::Metric::eval(self, input)
    }

    #[inline]
    fn name(&self) -> &str {
        crate::Metric::name(self)
    }
}

// ---------------------------------------------------------------------------
// Scorable impl for Box<dyn Scorable<T, I>> — enables nesting
// ---------------------------------------------------------------------------

impl<T: Float, I> Scorable<T, I> for Box<dyn Scorable<T, I>> {
    #[inline]
    fn eval(&self, input: &I) -> Witnessed<T, Value01> {
        (**self).eval(input)
    }

    #[inline]
    fn name(&self) -> &str {
        (**self).name()
    }
}

// ===========================================================================
// DynamicScoreSet — fully dynamic scoring set (Layer 3)
// ===========================================================================

use crate::breakdown::Breakdown;
use crate::value::{GtZero, NormalizedContainer, NormalizedWeight};

use witnessed::WitnessExt;

// ---------------------------------------------------------------------------
// DynamicMember — a single weighted metric in a DynamicScoreSet
// ---------------------------------------------------------------------------

/// A member of a [`DynamicScoreSet`]: a normalized weight paired with a
/// type-erased metric.
///
/// See [`Member`](crate::Member) for the Layer-1 equivalent and
/// [`FiniteMember`](crate::FiniteMember) for the Layer-2 equivalent.
pub struct DynamicMember<T: Float, I> {
    /// The normalized weight.
    pub weight: Witnessed<T, NormalizedWeight>,
    /// The type-erased metric.
    pub metric: Box<dyn Scorable<T, I>>,
}

impl<T: Float, I> DynamicMember<T, I> {
    /// Compute the weighted contribution of a metric score.
    ///
    /// `contribute(score) = score × normalized_weight`
    #[inline]
    pub fn contribute(&self, value: Witnessed<T, Value01>) -> T {
        value.into_inner() * self.weight.into_inner()
    }

    /// Return a reference to the metric.
    #[inline]
    pub fn metric(&self) -> &dyn Scorable<T, I> {
        &*self.metric
    }
}

// ---------------------------------------------------------------------------
// DynamicScoreSet — fully dynamic scoring set (Layer 3)
// ---------------------------------------------------------------------------

/// A weighted set of scoring operators using dynamic dispatch.
///
/// `DynamicScoreSet` stores a `Vec` of [`DynamicMember`]s, each holding a
/// `Box<dyn Scorable<T, I>>`. Every evaluation call pays vtable overhead,
/// but the set can contain completely heterogeneous metric types and can be
/// assembled at runtime.
///
/// Construct via [`dynamic_score_set!`](crate::dynamic_score_set!), the
/// [`DynamicScoreSetBuilder`], or call [`.score()`](DynamicScoreSet::score)
/// directly.
///
/// # Type parameters
///
/// - `T: Float` — the floating-point type (`f32` or `f64`).
/// - `I` — the input type passed to each metric.
///
/// # Example
///
/// ```ignore
/// let gc: Box<dyn Scorable<f64, &str>> = Box::new(gc_metric);
/// let len: Box<dyn Scorable<f64, &str>> = Box::new(len_metric);
///
/// let set = DynamicScoreSet::<f64, &str>::normalize(vec![
///     (2.0, gc),
///     (3.0, len),
/// ])?;
///
/// let total = set.sum(&"ACGTACGT");
/// ```
pub struct DynamicScoreSet<T: Float, I> {
    members: Vec<DynamicMember<T, I>>,
}

impl<T: Float, I> DynamicScoreSet<T, I> {
    /// Normalize raw weights and validate the resulting set.
    ///
    /// Each weight must be finite and strictly positive. Weights are normalized
    /// to sum to 1.
    #[doc(hidden)]
    pub fn normalize(entries: Vec<(T, Box<dyn Scorable<T, I>>)>) -> Result<Self, &'static str> {
        if entries.is_empty() {
            return Err("DynamicScoreSet: must have at least one member");
        }

        // Validate all weights are > 0
        for (w, _) in &entries {
            GtZero::witness(*w)?;
        }

        let sum: T = entries.iter().fold(T::zero(), |acc, (w, _)| acc + *w);

        let mut normalized: Vec<T> = entries.iter().map(|(w, _)| *w / sum).collect();

        // Sort a copy for binary search in NormalizedWeight
        let mut sorted = normalized.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
        let container = NormalizedContainer::witness(sorted)?;

        let members: Vec<DynamicMember<T, I>> = entries
            .into_iter()
            .zip(normalized.drain(..))
            .map(|((_, metric), nw)| {
                let weight = nw
                    .witness()
                    .by(|v| NormalizedWeight::from_normalized_container(*v, &container))?;
                Ok(DynamicMember { weight, metric })
            })
            .collect::<Result<Vec<_>, &'static str>>()?;

        Ok(DynamicScoreSet { members })
    }

    /// Evaluate all metrics against `input` and sum their weighted contributions.
    ///
    /// Zero-allocation convenience for the most common aggregation.
    /// For custom aggregation, use [`.score()`](Self::score) instead.
    #[inline]
    pub fn sum(&self, input: &I) -> T {
        self.members
            .iter()
            .fold(T::zero(), |acc, m| acc + m.contribute(m.metric.eval(input)))
    }

    /// Enter the scoring stage, returning a reference to all members.
    ///
    /// Use [`.by()`](DynamicScoreStage::by) on the returned stage to apply a
    /// custom aggregation, or [`.sum()`](Self::sum) for the standard
    /// weighted-sum shortcut.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let total = set.score().by(|members| {
    ///     members.iter().fold(0.0, |acc, m| {
    ///         acc + m.contribute(m.metric().eval(&input))
    ///     })
    /// });
    /// ```
    #[inline]
    pub fn score(&self) -> DynamicScoreStage<'_, T, I> {
        DynamicScoreStage {
            members: &self.members,
        }
    }

    /// Return the number of members in this set.
    #[inline]
    pub fn len(&self) -> usize {
        self.members.len()
    }

    /// Return `true` if the set has no members.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.members.is_empty()
    }

    /// Iterate over the members.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &DynamicMember<T, I>> {
        self.members.iter()
    }

    /// Evaluate all metrics against `input` and return a per-metric breakdown.
    ///
    /// Unlike [`.sum()`](Self::sum) which returns only the aggregate,
    /// `breakdown` returns one [`Breakdown`] row per member with the metric's
    /// name, raw score, normalized weight, and weighted contribution.
    ///
    /// # Example
    ///
    /// ```ignore
    /// for row in set.breakdown(&ctx) {
    ///     println!("{}: {:.3} × {:.3} = {:.3}",
    ///         row.name, row.score, row.weight, row.contribution);
    /// }
    /// ```
    #[inline]
    pub fn breakdown(&self, input: &I) -> Vec<Breakdown<'_, T>> {
        self.members
            .iter()
            .map(|m| {
                let score_witness = m.metric.eval(input);
                let score_val: T = *score_witness;
                Breakdown {
                    name: m.metric.name(),
                    score: score_val,
                    weight: m.weight.into_inner(),
                    contribution: m.contribute(score_witness),
                }
            })
            .collect()
    }

    /// Create a builder for incremental construction of a `DynamicScoreSet`.
    ///
    /// Use this when members are not known up front — push them one by one,
    /// then call [`.build()`](DynamicScoreSetBuilder::build) to finalize.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let set = DynamicScoreSet::<f64, &str>::builder()
    ///     .push(2.0, gc_metric.boxed())?
    ///     .push(3.0, len_metric.boxed())?
    ///     .build()?;
    /// ```
    #[inline]
    pub fn builder() -> DynamicScoreSetBuilder<T, I> {
        DynamicScoreSetBuilder {
            entries: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// DynamicScoreStage — member reference for custom aggregation (Layer 3)
// ---------------------------------------------------------------------------

/// The scoring stage for a [`DynamicScoreSet`], created by
/// [`DynamicScoreSet::score`].
///
/// Holds a reference to the set's members. Call
/// [`.by()`](DynamicScoreStage::by) to apply a custom aggregation over the
/// member slice. For the standard weighted-sum shortcut, use
/// [`DynamicScoreSet::sum`] instead.
///
/// # Examples
///
/// ```ignore
/// // Standard weighted sum via the stage:
/// let total = set.score().by(|members| {
///     members.iter().fold(0.0, |acc, m| {
///         acc + m.contribute(m.metric().eval(&input))
///     })
/// });
///
/// // Custom: geometric mean of contributions
/// let product = set.score().by(|members| {
///     members.iter().map(|m| {
///         m.contribute(m.metric().eval(&input))
///     }).fold(1.0, |a, c| a * c)
/// });
/// ```
pub struct DynamicScoreStage<'a, T: Float, I> {
    members: &'a [DynamicMember<T, I>],
}

impl<'a, T: Float, I> DynamicScoreStage<'a, T, I> {
    /// Apply a custom aggregation to the members.
    ///
    /// The closure receives a `&[DynamicMember<T, I>]` — one entry per member
    /// in insertion order. Each [`DynamicMember`] provides
    /// [`.metric()`](DynamicMember::metric) for evaluation and
    /// [`.contribute()`](DynamicMember::contribute) for weighting. The closure
    /// may return any type `R`.
    #[inline]
    pub fn by<F, R>(self, f: F) -> R
    where
        F: FnOnce(&[DynamicMember<T, I>]) -> R,
    {
        f(self.members)
    }
}

// ---------------------------------------------------------------------------
// DynamicScoreSetBuilder — incremental builder for DynamicScoreSet
// ---------------------------------------------------------------------------

/// Incremental builder for [`DynamicScoreSet`].
///
/// Accumulates raw `(weight, metric)` pairs via [`.push()`](Self::push), then
/// normalizes them into a [`DynamicScoreSet`] via [`.build()`](Self::build).
///
/// Each weight is validated on push (must be finite and > 0). Normalization
/// happens once at build time.
///
/// # Examples
///
/// Chain construction:
///
/// ```ignore
/// let set = DynamicScoreSet::<f64, &str>::builder()
///     .push(2.0, gc_metric.boxed())?
///     .push(3.0, len_metric.boxed())?
///     .build()?;
/// ```
///
/// Conditional construction:
///
/// ```ignore
/// let mut builder = DynamicScoreSet::<f64, &str>::builder();
/// builder = builder.push(2.0, baseline_metric.boxed())?;
/// if enable_extra {
///     builder = builder.push(1.0, extra_metric.boxed())?;
/// }
/// let set = builder.build()?;
/// ```
pub struct DynamicScoreSetBuilder<T: Float, I> {
    entries: Vec<(T, Box<dyn Scorable<T, I>>)>,
}

impl<T: Float, I> DynamicScoreSetBuilder<T, I> {
    /// Push a metric with a raw weight into the builder.
    ///
    /// The weight must be finite and strictly positive. This is validated
    /// immediately (fail-fast). Takes and returns `Self` for chaining.
    ///
    /// For incremental construction, rebind the result:
    ///
    /// ```ignore
    /// let mut builder = DynamicScoreSet::builder();
    /// builder = builder.push(2.0, gc_metric.boxed())?;
    /// if some_condition {
    ///     builder = builder.push(1.0, extra_metric.boxed())?;
    /// }
    /// let set = builder.build()?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if `weight` is zero, negative, or not finite.
    #[inline]
    pub fn push(
        mut self,
        weight: T,
        metric: Box<dyn Scorable<T, I>>,
    ) -> Result<Self, &'static str> {
        GtZero::witness(weight)?;
        self.entries.push((weight, metric));
        Ok(self)
    }

    /// Consume the builder and produce a [`DynamicScoreSet`] with normalized
    /// weights.
    ///
    /// # Errors
    ///
    /// Returns an error if no members were pushed.
    #[inline]
    pub fn build(self) -> Result<DynamicScoreSet<T, I>, &'static str> {
        DynamicScoreSet::normalize(self.entries)
    }
}

#[cfg(test)]
mod tests_for_dynamic;