1mod fit;
42
43use alloc::boxed::Box;
44use alloc::vec::Vec;
45
46pub use fit::{FitConfig, Fitted, fit, score};
47
48#[derive(Debug, Clone, PartialEq)]
50pub enum Formula {
51 True,
53 AtLeast {
55 signal: usize,
57 threshold: f64,
59 },
60 AtMost {
62 signal: usize,
64 threshold: f64,
66 },
67 Not(Box<Formula>),
69 And(Vec<Formula>),
71 Or(Vec<Formula>),
73 Always {
75 from: usize,
77 to: usize,
79 formula: Box<Formula>,
81 },
82 Eventually {
84 from: usize,
86 to: usize,
88 formula: Box<Formula>,
90 },
91 Until {
93 from: usize,
95 to: usize,
97 left: Box<Formula>,
99 right: Box<Formula>,
101 },
102}
103
104impl Formula {
105 #[must_use]
107 pub fn ge(signal: usize, threshold: f64) -> Self {
108 Self::AtLeast { signal, threshold }
109 }
110
111 #[must_use]
113 pub fn le(signal: usize, threshold: f64) -> Self {
114 Self::AtMost { signal, threshold }
115 }
116
117 #[must_use]
119 #[expect(
120 clippy::should_implement_trait,
121 reason = "a constructor named after the operator, not ops::Not"
122 )]
123 pub fn not(formula: Self) -> Self {
124 Self::Not(Box::new(formula))
125 }
126
127 #[must_use]
129 pub fn and(formulas: Vec<Self>) -> Self {
130 Self::And(formulas)
131 }
132
133 #[must_use]
135 pub fn or(formulas: Vec<Self>) -> Self {
136 Self::Or(formulas)
137 }
138
139 #[must_use]
141 pub fn always(from: usize, to: usize, formula: Self) -> Self {
142 Self::Always {
143 from,
144 to,
145 formula: Box::new(formula),
146 }
147 }
148
149 #[must_use]
151 pub fn eventually(from: usize, to: usize, formula: Self) -> Self {
152 Self::Eventually {
153 from,
154 to,
155 formula: Box::new(formula),
156 }
157 }
158
159 #[must_use]
161 pub fn until(from: usize, to: usize, left: Self, right: Self) -> Self {
162 Self::Until {
163 from,
164 to,
165 left: Box::new(left),
166 right: Box::new(right),
167 }
168 }
169
170 #[must_use]
172 pub fn robustness<S: AsRef<[f64]>>(&self, trace: &[S]) -> f64 {
173 if trace.is_empty() {
174 return self.signal(trace, 1)[0];
175 }
176
177 self.signal(trace, trace.len())[0]
178 }
179
180 #[must_use]
182 pub fn violation<S: AsRef<[f64]>>(&self, trace: &[S]) -> f64 {
183 (-self.robustness(trace)).max(0.0)
184 }
185
186 #[must_use]
188 pub fn signal<S: AsRef<[f64]>>(&self, trace: &[S], len: usize) -> Vec<f64> {
189 let at = |signal: usize, t: usize| {
190 trace
191 .get(t)
192 .and_then(|step| step.as_ref().get(signal))
193 .copied()
194 };
195 match self {
196 Self::True => alloc::vec![f64::INFINITY; len],
197 Self::AtLeast { signal, threshold } => (0..len)
198 .map(|t| at(*signal, t).map_or(f64::NEG_INFINITY, |x| x - threshold))
199 .collect(),
200 Self::AtMost { signal, threshold } => (0..len)
201 .map(|t| at(*signal, t).map_or(f64::NEG_INFINITY, |x| threshold - x))
202 .collect(),
203 Self::Not(inner) => inner.signal(trace, len).into_iter().map(|v| -v).collect(),
204 Self::And(parts) => combine(parts, trace, len, f64::INFINITY, f64::min),
205 Self::Or(parts) => combine(parts, trace, len, f64::NEG_INFINITY, f64::max),
206 Self::Always { from, to, formula } => window(
207 &formula.signal(trace, trace.len()),
208 len,
209 *from,
210 *to,
211 f64::INFINITY,
212 f64::min,
213 ),
214 Self::Eventually { from, to, formula } => window(
215 &formula.signal(trace, trace.len()),
216 len,
217 *from,
218 *to,
219 f64::NEG_INFINITY,
220 f64::max,
221 ),
222 Self::Until {
223 from,
224 to,
225 left,
226 right,
227 } => until(
228 &left.signal(trace, trace.len()),
229 &right.signal(trace, trace.len()),
230 len,
231 *from,
232 *to,
233 ),
234 }
235 }
236
237 #[must_use]
239 pub fn complexity(&self) -> usize {
240 1 + match self {
241 Self::True | Self::AtLeast { .. } | Self::AtMost { .. } => 0,
242 Self::Not(inner)
243 | Self::Always { formula: inner, .. }
244 | Self::Eventually { formula: inner, .. } => inner.complexity(),
245 Self::And(parts) | Self::Or(parts) => parts.iter().map(Self::complexity).sum(),
246 Self::Until { left, right, .. } => left.complexity() + right.complexity(),
247 }
248 }
249
250 #[must_use]
252 pub fn thresholds(&self) -> Vec<f64> {
253 let mut out = Vec::new();
254 self.clone().visit_thresholds(&mut |c| out.push(*c));
255
256 out
257 }
258
259 #[must_use]
262 pub fn with_thresholds(&self, values: &[f64]) -> Self {
263 let mut copy = self.clone();
264 let mut next = values.iter();
265 copy.visit_thresholds(&mut |c| {
266 if let Some(&v) = next.next() {
267 *c = v;
268 }
269 });
270
271 copy
272 }
273
274 fn visit_thresholds(&mut self, f: &mut impl FnMut(&mut f64)) {
276 match self {
277 Self::True => {}
278 Self::AtLeast { threshold, .. } | Self::AtMost { threshold, .. } => f(threshold),
279 Self::Not(inner)
280 | Self::Always { formula: inner, .. }
281 | Self::Eventually { formula: inner, .. } => {
282 inner.visit_thresholds(f);
283 }
284 Self::And(parts) | Self::Or(parts) => {
285 for part in parts.iter_mut() {
286 part.visit_thresholds(f);
287 }
288 }
289 Self::Until { left, right, .. } => {
290 left.visit_thresholds(f);
291 right.visit_thresholds(f);
292 }
293 }
294 }
295}
296
297fn combine<S: AsRef<[f64]>>(
299 parts: &[Formula],
300 trace: &[S],
301 len: usize,
302 identity: f64,
303 op: fn(f64, f64) -> f64,
304) -> Vec<f64> {
305 let mut out = alloc::vec![identity; len];
306 for part in parts {
307 for (o, v) in out.iter_mut().zip(part.signal(trace, len)) {
308 *o = op(*o, v);
309 }
310 }
311
312 out
313}
314
315fn window(
317 inner: &[f64],
318 len: usize,
319 from: usize,
320 to: usize,
321 identity: f64,
322 op: fn(f64, f64) -> f64,
323) -> Vec<f64> {
324 (0..len)
325 .map(|t| {
326 let start = t.saturating_add(from);
327 let end = t.saturating_add(to).min(inner.len().saturating_sub(1));
328 if start >= inner.len() || start > end {
329 return identity;
330 }
331
332 inner[start..=end].iter().copied().fold(identity, op)
333 })
334 .collect()
335}
336
337fn until(left: &[f64], right: &[f64], len: usize, from: usize, to: usize) -> Vec<f64> {
340 (0..len)
341 .map(|t| {
342 let end = t.saturating_add(to).min(right.len().saturating_sub(1));
343 let mut best = f64::NEG_INFINITY;
344 let mut prefix = f64::INFINITY;
345 for t2 in t..=end.max(t) {
346 if t2 >= right.len() {
347 break;
348 }
349 if t2 >= t.saturating_add(from) {
350 best = best.max(right[t2].min(prefix));
351 }
352 prefix = prefix.min(left[t2]);
353 }
354
355 best
356 })
357 .collect()
358}
359
360pub fn shield<A, S: AsRef<[f64]>>(
375 candidates: &[A],
376 mut rollout: impl FnMut(&A) -> Vec<S>,
377 formula: &Formula,
378) -> Option<(usize, f64)> {
379 let mut best: Option<(usize, f64)> = None;
380 for (index, candidate) in candidates.iter().enumerate() {
381 let rho = formula.robustness(&rollout(candidate));
382 if best.is_none_or(|(_, b)| rho > b) {
383 best = Some((index, rho));
384 }
385 }
386
387 best
388}
389
390#[cfg(test)]
391mod tests {
392 use alloc::vec;
393
394 use super::*;
395
396 #[test]
398 fn operator_semantics() {
399 let trace = [[0.0], [2.0], [5.0], [1.0]];
400 let at_least_1 = Formula::ge(0, 1.0);
401
402 assert_eq!(at_least_1.robustness(&trace), -1.0);
403 assert_eq!(Formula::not(at_least_1.clone()).robustness(&trace), 1.0);
404 assert_eq!(
405 Formula::eventually(0, 3, at_least_1.clone()).robustness(&trace),
406 4.0
407 );
408 assert_eq!(
409 Formula::always(1, 3, at_least_1.clone()).robustness(&trace),
410 0.0
411 );
412 assert_eq!(
413 Formula::always(1, 10, at_least_1.clone()).robustness(&trace),
414 0.0
415 );
416 assert_eq!(
417 Formula::always(9, 10, at_least_1.clone()).robustness(&trace),
418 f64::INFINITY
419 );
420 assert_eq!(
421 Formula::eventually(9, 10, at_least_1.clone()).robustness(&trace),
422 f64::NEG_INFINITY
423 );
424 assert_eq!(Formula::and(vec![]).robustness(&trace), f64::INFINITY);
425 assert_eq!(Formula::or(vec![]).robustness(&trace), f64::NEG_INFINITY);
426
427 let until = Formula::until(0, 3, Formula::le(0, 3.0), Formula::ge(0, 5.0));
429 assert_eq!(until.robustness(&trace), 0.0);
430 let strict = Formula::until(0, 3, Formula::le(0, 1.0), Formula::ge(0, 5.0));
432 assert_eq!(strict.robustness(&trace), -1.0);
433 }
434
435 #[test]
437 fn sign_matches_boolean_semantics() {
438 let mut rng = crate::SplitMix64::new(4);
439 let phi = Formula::and(vec![
440 Formula::always(
441 0,
442 4,
443 Formula::or(vec![Formula::le(0, 0.5), Formula::ge(1, 0.2)]),
444 ),
445 Formula::eventually(1, 3, Formula::ge(0, 0.7)),
446 ]);
447 for _ in 0..500 {
448 let trace: Vec<[f64; 2]> = (0..6)
449 .map(|_| [crate::unit_f64(&mut rng), crate::unit_f64(&mut rng)])
450 .collect();
451 let holds = (0..=4).all(|t| trace[t][0] <= 0.5 || trace[t][1] >= 0.2)
452 && (1..=3).any(|t| trace[t][0] >= 0.7);
453 let rho = phi.robustness(&trace);
454 assert_eq!(rho >= 0.0, holds, "{rho} {trace:?}");
455 }
456 }
457
458 #[test]
460 fn thresholds_round_trip() {
461 let phi = Formula::until(
462 0,
463 2,
464 Formula::le(0, 1.0),
465 Formula::and(vec![Formula::ge(1, 2.0), Formula::le(2, 3.0)]),
466 );
467
468 assert_eq!(phi.thresholds(), [1.0, 2.0, 3.0]);
469 assert_eq!(
470 phi.with_thresholds(&[7.0, 8.0, 9.0]).thresholds(),
471 [7.0, 8.0, 9.0]
472 );
473 assert_eq!(phi.complexity(), 5);
474 }
475}