e84ad6d0d2
Session, LinComb, and CostSum — the three builders the roster scope doc
excludes — re-shape onto the args seam (refs #271): builder() is now
zero-arg and returns a pending recipe (Session: tz + open; LinComb:
arity; CostSum: n_costs), the full signature forms in make, and
configured(...) is the Rust-path convenience producing the identical
recipe (twin-pinned). Session's period_minutes becomes a real ParamSpec
bound by configured instead of a baked struct field — same behaviour,
now sweepable when left open. Session::new and SessionFrankfurt are
untouched.
All builder(n)-form call sites move mechanically to configured(n):
aura-runner member.rs (wrap_r), aura-composites (vol_stop/cost_graph),
aura-engine blueprint.rs + e2e tests, aura-ingest breakout example,
and the crates' own tests. aura-std drops its unused chrono/chrono-tz
deps (stale since the b39fd63 session move).
The roster is deliberately untouched here: rostering before the op
seam lands would expose unconfigured pending builders to add_node.
232 lines
9.3 KiB
Rust
232 lines
9.3 KiB
Rust
//! `LinComb` — weighted sum of `N` f64 inputs (`Σ weights[i] · input[i]`), the
|
|
//! general combinator for the north-star "combine signals with weights" move
|
|
//! (C10). `LinComb([1.0, 1.0])` is `Add`; `LinComb([1.0, -1.0])` is `Sub`. The
|
|
//! weights are construction parameters that configure the node and fix its
|
|
//! arity (`weights.len()` inputs); they are also the combination's tunable
|
|
//! params, declared in the schema (cycle 0015) as `weights[0..N]` — N flat
|
|
//! indexed `F64` knobs that `Composite::param_space` aggregates (C8/C12/C19).
|
|
|
|
use aura_core::{
|
|
ArgKind, ArgSpec, ArgValue, Cell, Ctx, FieldSpec, Firing, Node, NodeSchema, ParamSpec, PortSpec,
|
|
PrimitiveBuilder, ScalarKind,
|
|
};
|
|
|
|
/// The declared construction args of a `LinComb` recipe: `arity` fixes the
|
|
/// node's input/param count (topology, C19), taken through the `args`
|
|
/// channel instead of a Rust-side builder parameter.
|
|
const LINCOMB_ARGS: &[ArgSpec] = &[ArgSpec { name: "arity", kind: ArgKind::Count }];
|
|
|
|
/// Weighted sum of `N` f64 inputs: `Σ weights[i] · input[i]`. The `weights` are
|
|
/// construction parameters that configure the node and fix its arity
|
|
/// (`weights.len()` inputs, in slot order). Emits `None` until *all* inputs
|
|
/// have a value.
|
|
///
|
|
/// # Firing and warm-up
|
|
///
|
|
/// Every input is [`Firing::Any`](aura_core::Firing::Any) — a *mode-A as-of
|
|
/// join*: the node fires on every cycle in which any leg is fresh (once all
|
|
/// legs have produced a value), pairing each fresh leg with the held value of
|
|
/// the others. Until every leg has a value it emits `None` (no cold-leg-as-
|
|
/// `0.0`). With heterogeneous sources sharing a timestamp (same `ts` from two
|
|
/// sources = two distinct cycles, C4), a fired node emits one row per *cycle*,
|
|
/// so a recorded combined stream may carry more than one row per timestamp.
|
|
pub struct LinComb {
|
|
weights: Vec<f64>,
|
|
out: [Cell; 1],
|
|
}
|
|
|
|
impl LinComb {
|
|
/// Build a `LinComb` with one weight per input (at least one required).
|
|
///
|
|
/// # Panics
|
|
/// Panics if `weights` is empty.
|
|
pub fn new(weights: Vec<f64>) -> Self {
|
|
assert!(!weights.is_empty(), "LinComb needs at least one weight");
|
|
Self { weights, out: [Cell::from_f64(0.0)] }
|
|
}
|
|
|
|
/// Roster factory: zero-arg, arg-bearing. `arity` is topology (fixed per
|
|
/// blueprint, C19), now taken through the `args` channel instead of a
|
|
/// Rust-side parameter.
|
|
pub fn builder() -> PrimitiveBuilder {
|
|
PrimitiveBuilder::pending(
|
|
"LinComb",
|
|
"linear combination of its inputs with constant weights",
|
|
LINCOMB_ARGS,
|
|
Self::make,
|
|
)
|
|
}
|
|
|
|
/// Turn a validated `arity` into the real, arity-sized signature; only
|
|
/// the weight *values* are injected, slot by slot, through `LinComb::new`
|
|
/// (the single sizing gate) once params are bound/built.
|
|
fn make(values: &[(String, ArgValue)]) -> PrimitiveBuilder {
|
|
let arity = values
|
|
.iter()
|
|
.find_map(|(n, v)| match (n.as_str(), v) {
|
|
("arity", ArgValue::Count(n)) => Some(*n),
|
|
_ => None,
|
|
})
|
|
.expect("try_args validated `arity` as ArgKind::Count before calling make");
|
|
let inputs = (0..arity)
|
|
.map(|i| PortSpec { kind: ScalarKind::F64, firing: Firing::Any, name: format!("term[{i}]") })
|
|
.collect();
|
|
let params = (0..arity)
|
|
.map(|i| ParamSpec { name: format!("weights[{i}]"), kind: ScalarKind::F64 })
|
|
.collect();
|
|
PrimitiveBuilder::new(
|
|
"LinComb",
|
|
NodeSchema {
|
|
inputs,
|
|
output: vec![FieldSpec { name: "value".into(), kind: ScalarKind::F64 }],
|
|
params,
|
|
doc: "linear combination of its inputs with constant weights",
|
|
},
|
|
|p| Box::new(LinComb::new(
|
|
p.iter().map(|c| c.f64()).collect(),
|
|
)),
|
|
)
|
|
}
|
|
|
|
/// Rust-path convenience — same recipe as the data path (twin identity).
|
|
pub fn configured(arity: usize) -> PrimitiveBuilder {
|
|
Self::builder()
|
|
.try_args(&[("arity".to_string(), arity.to_string())])
|
|
.expect("configured: a positive arity is always the canonical strict-form Count string")
|
|
}
|
|
}
|
|
|
|
impl Node for LinComb {
|
|
fn lookbacks(&self) -> Vec<usize> {
|
|
vec![1; self.weights.len()]
|
|
}
|
|
|
|
fn eval(&mut self, ctx: Ctx<'_>) -> Option<&[Cell]> {
|
|
let mut acc = 0.0;
|
|
for (i, &w) in self.weights.iter().enumerate() {
|
|
let w_in = ctx.f64_in(i);
|
|
if w_in.is_empty() {
|
|
return None; // not yet warmed up — withhold until every leg is present
|
|
}
|
|
acc += w * w_in[0];
|
|
}
|
|
self.out[0] = Cell::from_f64(acc);
|
|
Some(&self.out)
|
|
}
|
|
|
|
fn label(&self) -> String {
|
|
"LinComb".to_string()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use aura_core::{AnyColumn, Scalar, Timestamp};
|
|
|
|
#[test]
|
|
fn lincomb_weighted_sum_once_all_present() {
|
|
let mut lc = LinComb::new(vec![0.5, 2.0]);
|
|
let mut inputs = vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
];
|
|
|
|
// only input 0 present -> None
|
|
inputs[0].push(Scalar::f64(10.0)).unwrap();
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), None);
|
|
|
|
// both present -> 0.5*10 + 2.0*3 = 11.0
|
|
inputs[1].push(Scalar::f64(3.0)).unwrap();
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), Some([Cell::from_f64(11.0)].as_slice()));
|
|
}
|
|
|
|
#[test]
|
|
fn lincomb_unit_weights_equal_add() {
|
|
let mut lc = LinComb::new(vec![1.0, 1.0]);
|
|
let mut inputs = vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
];
|
|
inputs[0].push(Scalar::f64(7.0)).unwrap();
|
|
inputs[1].push(Scalar::f64(5.0)).unwrap();
|
|
// unit weights reproduce Add: 7 + 5
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), Some([Cell::from_f64(12.0)].as_slice()));
|
|
}
|
|
|
|
#[test]
|
|
fn lincomb_three_inputs_warm_up() {
|
|
let mut lc = LinComb::new(vec![1.0, 1.0, 1.0]);
|
|
let mut inputs = vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
];
|
|
inputs[0].push(Scalar::f64(1.0)).unwrap();
|
|
inputs[1].push(Scalar::f64(2.0)).unwrap();
|
|
// third leg still cold -> None (withheld until every leg is present)
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), None);
|
|
|
|
inputs[2].push(Scalar::f64(3.0)).unwrap();
|
|
// all warm -> 1 + 2 + 3
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), Some([Cell::from_f64(6.0)].as_slice()));
|
|
}
|
|
|
|
#[test]
|
|
#[should_panic(expected = "LinComb needs at least one weight")]
|
|
fn lincomb_empty_weights_panics() {
|
|
let _ = LinComb::new(vec![]);
|
|
}
|
|
|
|
#[test]
|
|
fn input_slots_are_named_term_index() {
|
|
let lc = LinComb::configured(3);
|
|
let names: Vec<String> = lc.schema().inputs.iter().map(|p| p.name.clone()).collect();
|
|
assert_eq!(names, ["term[0]", "term[1]", "term[2]"]);
|
|
}
|
|
|
|
#[test]
|
|
fn chained_bind_reconstructs_positional_vector() {
|
|
// bind BOTH weights, in reverse slot order, to DISTINCT values; build empty.
|
|
let builder = LinComb::configured(2)
|
|
.bind("weights[1]", Scalar::f64(2.0))
|
|
.bind("weights[0]", Scalar::f64(0.5));
|
|
assert!(builder.params().is_empty());
|
|
let mut lc = builder.build(&[]);
|
|
let mut inputs = vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
];
|
|
inputs[0].push(Scalar::f64(10.0)).unwrap();
|
|
inputs[1].push(Scalar::f64(3.0)).unwrap();
|
|
// 0.5*10 + 2.0*3 = 11.0 — holds ONLY if each weight landed in its right slot
|
|
// (a swap would give 2.0*10 + 0.5*3 = 21.5)
|
|
assert_eq!(lc.eval(Ctx::new(&inputs, Timestamp(0))), Some([Cell::from_f64(11.0)].as_slice()));
|
|
|
|
// partial: bind weights[0], leave weights[1] open → inject it at build
|
|
let partial = LinComb::configured(2).bind("weights[0]", Scalar::f64(0.5));
|
|
assert_eq!(
|
|
partial.params().iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
|
|
["weights[1]"],
|
|
);
|
|
let mut lc2 = partial.build(&[Cell::from_f64(2.0)]); // weights[1] = 2.0 injected
|
|
let mut inputs2 = vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
];
|
|
inputs2[0].push(Scalar::f64(10.0)).unwrap();
|
|
inputs2[1].push(Scalar::f64(3.0)).unwrap();
|
|
assert_eq!(lc2.eval(Ctx::new(&inputs2, Timestamp(0))), Some([Cell::from_f64(11.0)].as_slice()));
|
|
}
|
|
|
|
/// Twin identity (spec §aura-std): `configured(arity)` is exactly
|
|
/// `builder().try_args([("arity", arity)])`.
|
|
#[test]
|
|
fn lincomb_configured_twin_equals_builder_try_args() {
|
|
let via_configured = LinComb::configured(3);
|
|
let via_try_args = LinComb::builder().try_args(&[("arity".into(), "3".into())]).expect("valid arity configures");
|
|
assert_eq!(via_configured.construction_args(), via_try_args.construction_args());
|
|
assert_eq!(via_configured.schema(), via_try_args.schema());
|
|
}
|
|
}
|