Skip to main content

sva_formula/
hash.rs

1// Concern: content-addresses a SpectralSum under the table version, and draws a seed at a step | Non-concern: what a hash keys (sva-engine) | IO: (&SpectralSum) -> Hash
2
3use std::fmt;
4
5use crate::closed_form::{
6    Body, Bound, ClosedForm, Edge, Excitation, Fold, ModalBank, Mode, Part, Rational, Series,
7    Unary, Var,
8};
9use crate::complex::{C64, canonical};
10use crate::env::NodeId;
11use crate::lanes::Lanes;
12use crate::run::Mirror;
13use crate::spectral_sum::atom::{Singular, SpectralAtom};
14use crate::spectral_sum::{Lane, SpectralSum};
15use crate::table::TABLE_VERSION;
16
17/// Two independently primed FNV-1a lanes: serving one closed form's samples for another is silent
18/// corruption, so the width is set against birthday collisions rather than speed.
19#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
20pub struct Hash(pub u64, pub u64);
21
22impl fmt::Display for Hash {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "{:016x}{:016x}", self.0, self.1)
25    }
26}
27
28pub fn hash_spectral_sum(n: &SpectralSum) -> Hash {
29    hash_spectral_sum_under(n, TABLE_VERSION)
30}
31
32pub fn hash_closed_form(t: &ClosedForm) -> Hash {
33    hash_closed_form_under(t, TABLE_VERSION)
34}
35
36/// The version is the first field after the tag, so a table bump retires every entry keyed
37/// by one of these.
38pub fn hash_spectral_sum_under(n: &SpectralSum, table_version: u64) -> Hash {
39    let mut s = Sink::new(0x01, table_version);
40    s.var(n.var);
41    s.u64(n.lanes.len() as u64);
42    for lane in &n.lanes {
43        s.lane(lane);
44    }
45    s.finish()
46}
47
48pub fn hash_closed_form_under(t: &ClosedForm, table_version: u64) -> Hash {
49    let mut s = Sink::new(0x02, table_version);
50    s.var(t.var);
51    s.formula(&t.body);
52    s.finish()
53}
54
55/// A closed form that reads other nodes, each ref hashed as what `node` names it: the node's
56/// own content, never the number a graph gave it.
57pub fn hash_closed_form_with(t: &ClosedForm, node: &mut dyn FnMut(NodeId) -> Hash) -> Hash {
58    let mut s = Sink::new(0x04, TABLE_VERSION);
59    s.node = Some(node);
60    s.var(t.var);
61    s.formula(&t.body);
62    s.finish()
63}
64
65/// The unit-interval value one seed draws at one whole step, wherever the pair is written.
66pub fn draw(seed: u64, step: i64) -> f64 {
67    mix(mix(seed ^ DRAWN) ^ step as u64) as f64 / u64::MAX as f64
68}
69
70const DRAWN: u64 = 0x9e37_79b9_7f4a_7c15;
71
72/// The draw at the whole step nearest `key`, ties to even; `None` past any `i64` step.
73pub fn draw_nearest(seed: u64, key: f64) -> Option<f64> {
74    let step = key.round_ties_even();
75    let held = step >= i64::MIN as f64 && step < i64::MAX as f64;
76    held.then(|| draw(seed, step as i64))
77}
78
79struct Sink<'a> {
80    lanes: Lanes<0>,
81    node: Option<&'a mut dyn FnMut(NodeId) -> Hash>,
82}
83
84impl<'a> Sink<'a> {
85    fn new(tag: u8, table_version: u64) -> Sink<'a> {
86        let mut s = Sink {
87            lanes: Lanes::default(),
88            node: None,
89        };
90        s.byte(tag);
91        s.u64(table_version);
92        s
93    }
94
95    fn byte(&mut self, b: u8) {
96        self.lanes.word(u64::from(b));
97    }
98
99    fn u64(&mut self, v: u64) {
100        for b in v.to_le_bytes() {
101            self.byte(b);
102        }
103    }
104
105    fn i64(&mut self, v: i64) {
106        self.u64(v as u64);
107    }
108
109    fn f64(&mut self, v: f64) {
110        self.u64(canonical(v));
111    }
112
113    fn c64(&mut self, v: C64) {
114        let (re, im) = v.bits();
115        self.u64(re);
116        self.u64(im);
117    }
118
119    fn var(&mut self, v: Var) {
120        self.byte(match v {
121            Var::T => 0,
122            Var::F => 1,
123        });
124    }
125
126    fn edge(&mut self, e: Edge) {
127        match e {
128            Edge::NegInf => self.byte(0),
129            Edge::At(bits) => {
130                self.byte(1);
131                self.u64(bits);
132            }
133            Edge::PosInf => self.byte(2),
134        }
135    }
136
137    fn lane(&mut self, lane: &Lane) {
138        self.u64(lane.atoms.len() as u64);
139        for a in &lane.atoms {
140            self.atom(a);
141        }
142        self.u64(lane.series.len() as u64);
143        for s in &lane.series {
144            self.series(s);
145        }
146        self.u64(lane.modal.len() as u64);
147        for m in &lane.modal {
148            self.modal(m);
149        }
150    }
151
152    /// `Origin` is excluded: two spellings from different files must hash alike.
153    fn atom(&mut self, a: &SpectralAtom) {
154        self.c64(a.c);
155        self.u64(u64::from(a.poly));
156        match a.exp {
157            None => self.byte(0),
158            Some(e) => {
159                self.byte(1);
160                self.f64(e.sigma);
161                self.f64(e.omega);
162            }
163        }
164        match a.gauss {
165            None => self.byte(0),
166            Some(g) => {
167                self.byte(1);
168                self.f64(g.a);
169                self.f64(g.mu);
170            }
171        }
172        match a.ind {
173            None => self.byte(0),
174            Some(i) => {
175                self.byte(1);
176                self.edge(i.l);
177                self.edge(i.r);
178            }
179        }
180        match a.pole {
181            None => self.byte(0),
182            Some(p) => {
183                self.byte(1);
184                self.c64(p.at);
185                self.u64(u64::from(p.order));
186                self.byte(u8::from(p.pv));
187            }
188        }
189        match a.sing {
190            Singular::Regular => self.byte(0),
191            Singular::Delta { at, order } => {
192                self.byte(1);
193                self.f64(at);
194                self.u64(u64::from(order));
195            }
196        }
197    }
198
199    fn series(&mut self, s: &Series) {
200        self.u64(u64::from(s.index.0));
201        self.i64(s.lo);
202        match s.hi {
203            Bound::Finite(n) => {
204                self.byte(0);
205                self.i64(n);
206            }
207            Bound::Infinite => self.byte(1),
208        }
209        self.formula(&s.term.body);
210    }
211
212    fn amps(&mut self, amps: &[C64]) {
213        self.u64(amps.len() as u64);
214        for a in amps {
215            self.c64(*a);
216        }
217    }
218
219    fn modal(&mut self, m: &ModalBank) {
220        self.u64(m.modes.len() as u64);
221        for Mode {
222            omega,
223            tau,
224            amp,
225            phase,
226        } in &m.modes
227        {
228            self.f64(*omega);
229            self.f64(*tau);
230            self.f64(*amp);
231            self.f64(*phase);
232        }
233        match m.excite {
234            Excitation::HammerPulse { f0, t0, contact } => {
235                self.byte(0);
236                self.f64(f0);
237                self.f64(t0);
238                self.f64(contact);
239            }
240            Excitation::Impulse { t0 } => {
241                self.byte(1);
242                self.f64(t0);
243            }
244        }
245    }
246
247    fn parts(&mut self, parts: &[Part]) {
248        self.u64(parts.len() as u64);
249        for p in parts {
250            self.formula(&p.body);
251        }
252    }
253
254    fn rational(&mut self, r: &Rational) {
255        self.u64(r.zeros.len() as u64);
256        for z in &r.zeros {
257            self.c64(*z);
258        }
259        self.u64(r.poles.len() as u64);
260        for p in &r.poles {
261            self.c64(*p);
262        }
263        self.c64(r.gain);
264    }
265
266    fn formula(&mut self, f: &Body) {
267        match f {
268            Body::Const(c) => {
269                self.byte(0x10);
270                self.c64(*c);
271            }
272            Body::Line => self.byte(0x11),
273            Body::Index(i) => {
274                self.byte(0x12);
275                self.u64(u64::from(i.0));
276            }
277            Body::Param(p) => {
278                self.byte(0x13);
279                self.u64(u64::from(p.0));
280            }
281            Body::Node(n) => {
282                self.byte(0x14);
283                match self.node.as_mut().map(|named| named(*n)) {
284                    Some(held) => {
285                        self.u64(held.0);
286                        self.u64(held.1);
287                    }
288                    None => self.u64(u64::from(n.0)),
289                }
290            }
291            Body::Add(parts) => {
292                self.byte(0x15);
293                self.parts(parts);
294            }
295            Body::Mul(parts) => {
296                self.byte(0x16);
297                self.parts(parts);
298            }
299            Body::Div(a, b) => {
300                self.byte(0x17);
301                self.formula(&a.body);
302                self.formula(&b.body);
303            }
304            Body::Pow(base, n) => {
305                self.byte(0x18);
306                self.formula(&base.body);
307                self.i64(i64::from(*n));
308            }
309            Body::Apply(op, arg) => {
310                self.byte(0x19);
311                self.byte(unary_tag(*op));
312                self.formula(&arg.body);
313            }
314            Body::Fold(op, args) => {
315                self.byte(0x1a);
316                self.byte(match op {
317                    Fold::Max => 0,
318                    Fold::Min => 1,
319                    Fold::Mod => 2,
320                });
321                self.parts(args);
322            }
323            Body::Delta { at, order } => {
324                self.byte(0x1b);
325                self.formula(&at.body);
326                self.u64(u64::from(*order));
327            }
328            Body::Pv(at) => {
329                self.byte(0x1c);
330                self.formula(&at.body);
331            }
332            Body::Warp { at, of } => {
333                self.byte(0x27);
334                self.formula(&at.body);
335                self.formula(&of.body);
336            }
337            Body::Shift { by, of } => {
338                self.byte(0x1d);
339                self.f64(*by);
340                self.formula(&of.body);
341            }
342            Body::Deriv { order, of } => {
343                self.byte(0x1e);
344                self.u64(u64::from(*order));
345                self.formula(&of.body);
346            }
347            Body::Crop {
348                of,
349                l,
350                r,
351                rise,
352                fall,
353            } => {
354                self.byte(0x1f);
355                self.formula(&of.body);
356                self.edge(*l);
357                self.edge(*r);
358                self.f64(*rise);
359                self.f64(*fall);
360            }
361            Body::Join(parts) => {
362                self.byte(0x21);
363                self.parts(parts);
364            }
365            Body::Channel(of, k) => {
366                self.byte(0x22);
367                self.formula(&of.body);
368                self.byte(*k);
369            }
370            Body::Rational(r) => {
371                self.byte(0x23);
372                self.rational(r);
373            }
374            Body::Series(s) => {
375                self.byte(0x24);
376                self.series(s);
377            }
378            Body::Modal(m) => {
379                self.byte(0x25);
380                self.modal(m);
381            }
382            Body::Run(run) => {
383                self.byte(0x28);
384                self.f64(run.offset);
385                self.f64(run.step);
386                self.i64(run.first);
387                self.amps(&run.amps);
388                match &run.mirror {
389                    Mirror::None => self.byte(0),
390                    Mirror::Conjugate => self.byte(1),
391                    Mirror::Held(amps) => {
392                        self.byte(2);
393                        self.amps(amps);
394                    }
395                }
396            }
397            Body::Keyed { seed, of } => {
398                self.byte(0x26);
399                self.u64(*seed);
400                self.formula(&of.body);
401            }
402        }
403    }
404
405    /// One avalanche past the lanes, so a short input still fills both words.
406    fn finish(&self) -> Hash {
407        let Hash(a, b) = self.lanes.finish();
408        Hash(mix(a), mix(b))
409    }
410}
411
412fn unary_tag(op: Unary) -> u8 {
413    match op {
414        Unary::Sin => 0,
415        Unary::Cos => 1,
416        Unary::Exp => 2,
417        Unary::Tanh => 3,
418        Unary::Sat => 4,
419        Unary::Abs => 5,
420        Unary::Log => 6,
421        Unary::Sqrt => 7,
422        Unary::Step => 8,
423    }
424}
425
426fn mix(mut z: u64) -> u64 {
427    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
428    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
429    z ^ (z >> 31)
430}