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
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Design validation: restaurant scoring with three layers.
//!
//! Scenario: rate restaurants on cleanliness (0-100), food quality (0-5 stars),
//! and price (lower = better). The scoring operator set is composed at runtime
//! but the set of *possible* metrics is known at compile time — perfect for
//! Layer 2 (finite enum).

use core::marker::PhantomData;
use score_set::*;

// ===========================================================================
// Test helper — a metric returning a constant [0,1] value
// ===========================================================================

struct ConstMetric<T: Float, I> {
    name: &'static str,
    value: T,
    _phantom: PhantomData<I>,
}

impl<T: Float, I> ConstMetric<T, I> {
    fn new(name: &'static str, value: T) -> Self {
        Self {
            name,
            value,
            _phantom: PhantomData,
        }
    }
    fn eval(&self, _input: &I) -> Witnessed<T, Value01> {
        Value01::witness(self.value.min(T::one()).max(T::zero())).unwrap()
    }
    fn name(&self) -> &str {
        self.name
    }
}

impl<T: Float, I> Scorable<T, I> for ConstMetric<T, I> {
    fn eval(&self, input: &I) -> Witnessed<T, Value01> {
        ConstMetric::eval(self, input)
    }
    fn name(&self) -> &str {
        ConstMetric::name(self)
    }
}

// ===========================================================================
// Domain input type
// ===========================================================================

struct Restaurant {
    cleanliness: f64,  // 0–100
    food_quality: f64, // 0–5
    price: f64,        // $ per meal, lower is better
    wait_minutes: f64, // avg wait time
}

// ===========================================================================
// Concrete metric types — one per scoring dimension.
// Each is a newtype around Metric with named fn-pointer closures.
// ===========================================================================

fn measure_cleanliness(r: &Restaurant) -> f64 {
    r.cleanliness
}
fn map01_linear_100(raw: &f64, _: &Restaurant) -> Witnessed<f64, Value01> {
    Value01::witness((raw / 100.0).min(1.0).max(0.0)).unwrap()
}

struct Cleanliness(
    Metric<
        f64,
        Restaurant,
        f64,
        fn(&Restaurant) -> f64,
        fn(&f64, &Restaurant) -> Witnessed<f64, Value01>,
    >,
);

impl Cleanliness {
    fn new() -> Self {
        Self(
            metric("cleanliness")
                .measure()
                .by(measure_cleanliness as fn(&Restaurant) -> f64)
                .map01()
                .by(map01_linear_100),
        )
    }
    fn eval(&self, r: &Restaurant) -> Witnessed<f64, Value01> {
        self.0.eval(r)
    }
    fn name(&self) -> &str {
        self.0.name()
    }
}

fn measure_quality(r: &Restaurant) -> f64 {
    r.food_quality
}
fn map01_linear_5(raw: &f64, _: &Restaurant) -> Witnessed<f64, Value01> {
    Value01::witness((raw / 5.0).min(1.0).max(0.0)).unwrap()
}

struct FoodQuality(
    Metric<
        f64,
        Restaurant,
        f64,
        fn(&Restaurant) -> f64,
        fn(&f64, &Restaurant) -> Witnessed<f64, Value01>,
    >,
);

impl FoodQuality {
    fn new() -> Self {
        Self(
            metric("food_quality")
                .measure()
                .by(measure_quality as fn(&Restaurant) -> f64)
                .map01()
                .by(map01_linear_5),
        )
    }
    fn eval(&self, r: &Restaurant) -> Witnessed<f64, Value01> {
        self.0.eval(r)
    }
    fn name(&self) -> &str {
        self.0.name()
    }
}

fn measure_price(r: &Restaurant) -> f64 {
    r.price
}
fn map01_invert_50(raw: &f64, _: &Restaurant) -> Witnessed<f64, Value01> {
    // Invert: $0 = best (1.0), $50+ = worst (0.0)
    Value01::witness((1.0 - raw / 50.0).min(1.0).max(0.0)).unwrap()
}

struct PriceScore(
    Metric<
        f64,
        Restaurant,
        f64,
        fn(&Restaurant) -> f64,
        fn(&f64, &Restaurant) -> Witnessed<f64, Value01>,
    >,
);

impl PriceScore {
    fn new() -> Self {
        Self(
            metric("price")
                .measure()
                .by(measure_price as fn(&Restaurant) -> f64)
                .map01()
                .by(map01_invert_50),
        )
    }
    fn eval(&self, r: &Restaurant) -> Witnessed<f64, Value01> {
        self.0.eval(r)
    }
    fn name(&self) -> &str {
        self.0.name()
    }
}

// ===========================================================================
// Layer 2: declare the finite metric enum (concrete form — Restaurant+ f64
// are baked in, no generic noise)
// ===========================================================================

finite_metric! {
    metric     => RestaurantMetric,
    float      => f64,
    subject    => Restaurant,
    dimensions =>
        Clean(Cleanliness),
        Quality(FoodQuality),
        Price(PriceScore),
}

// ===========================================================================
// Layer 2 usage
// ===========================================================================

#[test]
fn restaurant_scoring_layer2() -> Result<(), &'static str> {
    // Compose a scoring set at runtime.
    // In a real app, this configuration might come from a config file or user
    // preferences — but the *set of possible metrics* is known at compile time.
    let set = FiniteScoreSet::normalize(vec![
        (3.0, RestaurantMetric::Clean(Cleanliness::new())),
        (5.0, RestaurantMetric::Quality(FoodQuality::new())),
        (2.0, RestaurantMetric::Price(PriceScore::new())),
    ])?;

    let r = Restaurant {
        cleanliness: 85.0,
        food_quality: 4.2,
        price: 18.0,
        wait_minutes: 12.0,
    };

    let total = set.sum(&r);
    // cleanliness: 85/100 = 0.85    (weight 3/10 = 0.3)
    // quality:     4.2/5 = 0.84    (weight 5/10 = 0.5)
    // price:       1-18/50 = 0.64  (weight 2/10 = 0.2)
    // total = 0.3*0.85 + 0.5*0.84 + 0.2*0.64 = 0.255 + 0.42 + 0.128 = 0.803
    let expected = 0.3 * 0.85 + 0.5 * 0.84 + 0.2 * 0.64;
    assert!((total - expected).abs() < 1e-10);

    Ok(())
}

#[test]
fn restaurant_scoring_layer2_inspect() -> Result<(), &'static str> {
    let set = FiniteScoreSet::normalize(vec![
        (1.0, RestaurantMetric::Clean(Cleanliness::new())),
        (1.0, RestaurantMetric::Quality(FoodQuality::new())),
    ])?;

    let r = Restaurant {
        cleanliness: 90.0,
        food_quality: 3.0,
        price: 25.0,
        wait_minutes: 5.0,
    };

    // Can inspect individual metric results before aggregation
    let mut results: Vec<(&str, f64, f64)> = vec![];
    for m in set.iter() {
        let name = m.metric().name();
        let score = *m.metric().eval(&r);
        let weight = m.weight.into_inner();
        results.push((name, weight, score));
    }
    assert_eq!(results[0].0, "cleanliness");
    assert_eq!(results[1].0, "food_quality");
    assert!((results[0].1 - 0.5).abs() < 1e-10); // equal weights
    assert!((results[1].1 - 0.5).abs() < 1e-10);

    Ok(())
}

#[test]
fn restaurant_scoring_layer2_custom_escape_hatch() -> Result<(), &'static str> {
    // When you need the Custom escape hatch for a one-off dynamic metric,
    // use the generic form of `finite_metric!` and declare `Custom` explicitly.
    // (The concrete form no longer auto-generates Custom — no dead-code warning
    // when you don't need it.)
    finite_metric! {
        metric => DemoMetricWithCustom<T, I>,
        dimensions =>
            AlwaysZero(ConstMetric<T, I>),
            AlwaysOne(ConstMetric<T, I>),
            Custom(Box<dyn Scorable<T, I>>),
    }

    let wait_metric: Box<dyn Scorable<f64, Restaurant>> = metric("wait_time")
        .measure()
        .by(|r: &Restaurant| r.wait_minutes)
        .map01()
        .linear(30.0)
        .boxed();

    // Generic form requires turbofish at each variant constructor and in the
    // FiniteScoreSet type annotation.
    use DemoMetricWithCustom as D;
    let set = FiniteScoreSet::normalize(vec![
        (
            1.0,
            D::<f64, Restaurant>::AlwaysZero(ConstMetric::new("zero", 0.0)),
        ),
        (
            1.0,
            D::<f64, Restaurant>::AlwaysOne(ConstMetric::new("one", 1.0)),
        ),
        (1.0, D::<f64, Restaurant>::Custom(wait_metric)),
    ])?;

    let r = Restaurant {
        cleanliness: 100.0,
        food_quality: 5.0,
        price: 0.0,
        wait_minutes: 15.0,
    };
    let total = set.sum(&r);
    // Weights: 1/3 each. zero=0 → 0, one=1 → 1/3, wait=0.5 → 1/3*0.5=1/6
    // total = 0 + 1/3 + 1/6 = 0.5
    assert!((total - 0.5).abs() < 1e-10);

    Ok(())
}

// ===========================================================================
// Layer 3: fully dynamic — same scenario but with Box<dyn> for everything
// ===========================================================================

#[test]
fn restaurant_scoring_layer3() -> Result<(), &'static str> {
    let set = DynamicScoreSet::normalize(vec![
        (
            3.0,
            metric("cleanliness")
                .measure()
                .by(|r: &Restaurant| r.cleanliness)
                .map01()
                .linear(100.0)
                .boxed(),
        ),
        (
            5.0,
            metric("food_quality")
                .measure()
                .by(|r: &Restaurant| r.food_quality)
                .map01()
                .linear(5.0)
                .boxed(),
        ),
        (
            2.0,
            metric("price")
                .measure()
                .by(|r: &Restaurant| r.price)
                .map01()
                .by(|raw: &f64, _: &Restaurant| {
                    Value01::witness((1.0 - raw / 50.0).min(1.0).max(0.0)).unwrap()
                })
                .boxed(),
        ),
    ])?;

    let r = Restaurant {
        cleanliness: 85.0,
        food_quality: 4.2,
        price: 18.0,
        wait_minutes: 12.0,
    };
    let total = set.sum(&r);
    let expected = 0.3 * 0.85 + 0.5 * 0.84 + 0.2 * 0.64;
    assert!((total - expected).abs() < 1e-10);

    Ok(())
}

// ===========================================================================
// Design analysis: why Layer 2 exists (it's not just a worse Layer 3)
// ===========================================================================

// Layer 3 (DynamicScoreSet) is fully dynamic — every .eval() call goes
// through two levels of indirection:
//   1. vtable lookup on Box<dyn Scorable>
//   2. vtable lookup on Box<dyn Fn> (inside the Metric's closures)
//
// Layer 2 (FiniteScoreSet) with finite_metric! eliminates BOTH:
//   - The enum's match compiles to a jump table (zero indirection)
//   - Variant types use fn pointers (zero indirection)
//
// In hot loops (e.g., scoring millions of items), the difference is real.
// But Layer 2 requires the set of possible metric *types* to be known at
// compile time. Layer 3 can load arbitrary metrics at runtime.

// ===========================================================================
// Comparison: manual enum (what users would write without finite_metric!)
// ===========================================================================

// Without finite_metric!, a user who wants zero-vtable dispatch must write:
//
//   enum RestaurantMetricManual {
//       Clean(Cleanliness),
//       Quality(FoodQuality),
//       Price(PriceScore),
//       Custom(Box<dyn Scorable<f64, Restaurant>>),
//   }
//
//   impl Scorable<f64, Restaurant> for RestaurantMetricManual {
//       fn eval(&self, input: &Restaurant) -> Witnessed<f64, Value01> {
//           match self {
//               Self::Clean(m) => m.eval(input),
//               Self::Quality(m) => m.eval(input),
//               Self::Price(m) => m.eval(input),
//               Self::Custom(c) => c.eval(input),
//           }
//       }
//       fn name(&self) -> &str {
//           match self {
//               Self::Clean(m) => m.name(),
//               Self::Quality(m) => m.name(),
//               Self::Price(m) => m.name(),
//               Self::Custom(c) => c.name(),
//           }
//       }
//   }
//
// finite_metric! collapses this to 6 lines with named keys:
//
//   finite_metric! {
//       metric     => RestaurantMetric,
//       float      => f64,
//       subject    => Restaurant,
//       dimensions =>
//           Clean(Cleanliness),
//           Quality(FoodQuality),
//           Price(PriceScore),
//   }
//
// And when you add a 4th metric, it's 1 line vs 4 (variant + 3 match arms).

// ===========================================================================
// Demonstration: generic form (when metric types ARE generic)
// ===========================================================================

// Generic form: enum is parameterized over T and I.
// Useful when the same metric types work for multiple input types.
finite_metric! {
    pub
    metric => GenericKind<T, I>,
    dimensions =>
        Yes(ConstMetric<T, I>),
        No(ConstMetric<T, I>),
        Custom(Box<dyn Scorable<T, I>>),
}

#[test]
fn generic_form_works_across_types() -> Result<(), &'static str> {
    // Same enum, different T/I combinations:

    // f64 with &str input
    let yes_f64: GenericKind<f64, &str> = GenericKind::Yes(ConstMetric::new("yes", 1.0_f64));
    assert_eq!(yes_f64.name(), "yes");
    assert!((*yes_f64.eval(&"ignored") - 1.0).abs() < 1e-10);

    // f32 with i32 input
    let no_f32: GenericKind<f32, i32> = GenericKind::No(ConstMetric::new("no", 0.0_f32));
    assert_eq!(no_f32.name(), "no");
    assert!((*no_f32.eval(&42) - 0.0).abs() < 1e-6);

    Ok(())
}