Skip to main content

evolutionary_planning/
stl.rs

1//! Finite-trace signal temporal logic (STL) with quantitative semantics, for evolutionary
2//! search under temporal-logic constraints (after EvoPlan, Nukapotula et al. 2026).
3//!
4//! A trace is a sequence of time steps, each a slice of named signals (by index). The
5//! robustness `ρ(φ, trace, t)` of a formula is positive when the trace satisfies it at `t`,
6//! negative when it violates it, and its magnitude says by how much (Donzé and Maler 2010):
7//!
8//! | Formula | Robustness at `t` |
9//! |---|---|
10//! | `x_i ≥ c` | `x_i(t) - c` |
11//! | `x_i ≤ c` | `c - x_i(t)` |
12//! | `¬φ` | `-ρ(φ, t)` |
13//! | `φ ∧ ψ`, `φ ∨ ψ` | `min`, `max` |
14//! | `G[a,b] φ` | `min` of `ρ(φ, t')` over `t' ∈ [t+a, t+b]` |
15//! | `F[a,b] φ` | `max` over the same window |
16//! | `φ U[a,b] ψ` | `max` over `t'` of `min(ρ(ψ, t'), min over t'' ∈ [t, t') of ρ(φ, t''))` |
17//!
18//! Windows are clipped to the trace (finite-trace semantics): `G` over an empty window is
19//! `+∞` (vacuously true), `F` and `U` are `-∞`; a predicate past the end of the trace is
20//! `-∞` (no evidence). Robustness is computed bottom-up as a signal over all time steps, so
21//! a formula costs `O(nodes · length · window)`.
22//!
23//! Uses: an objective (`-ρ`), a graded constraint violation `max(0, -ρ)` (Jakob's rule
24//! against flat penalties), a [`shield`] that picks the candidate action whose rollout is most
25//! robust, and [`fit()`] to learn thresholds from demonstrations.
26//!
27//! ```
28//! use evolutionary_planning::stl::Formula;
29//!
30//! // "Always within the first 3 steps, speed (signal 0) stays at most 2, and eventually
31//! // clearance (signal 1) reaches at least 1."
32//! let phi = Formula::and(vec![
33//!     Formula::always(0, 3, Formula::le(0, 2.0)),
34//!     Formula::eventually(0, 5, Formula::ge(1, 1.0)),
35//! ]);
36//! let trace = [[1.0, 0.0], [1.5, 0.5], [1.8, 1.4], [0.5, 2.0]];
37//! assert!((phi.robustness(&trace) - 0.2).abs() < 1e-12);
38//! assert_eq!(phi.violation(&trace), 0.0);
39//! ```
40
41mod fit;
42
43use alloc::boxed::Box;
44use alloc::vec::Vec;
45
46pub use fit::{FitConfig, Fitted, fit, score};
47
48/// An STL formula over signals indexed `0..`.
49#[derive(Debug, Clone, PartialEq)]
50pub enum Formula {
51    /// Always true (`ρ = +∞`).
52    True,
53    /// `x_signal ≥ threshold`.
54    AtLeast {
55        /// The signal index.
56        signal: usize,
57        /// The threshold `c`.
58        threshold: f64,
59    },
60    /// `x_signal ≤ threshold`.
61    AtMost {
62        /// The signal index.
63        signal: usize,
64        /// The threshold `c`.
65        threshold: f64,
66    },
67    /// Negation.
68    Not(Box<Formula>),
69    /// Conjunction; empty is `True`.
70    And(Vec<Formula>),
71    /// Disjunction; empty is false (`-∞`).
72    Or(Vec<Formula>),
73    /// `G[from, to] φ`: `φ` holds at every step of the window.
74    Always {
75        /// The window start, relative to the current step.
76        from: usize,
77        /// The window end (inclusive), `>= from`.
78        to: usize,
79        /// The formula that must hold throughout.
80        formula: Box<Formula>,
81    },
82    /// `F[from, to] φ`: `φ` holds at some step of the window.
83    Eventually {
84        /// The window start, relative to the current step.
85        from: usize,
86        /// The window end (inclusive), `>= from`.
87        to: usize,
88        /// The formula that must hold once.
89        formula: Box<Formula>,
90    },
91    /// `φ U[from, to] ψ`: `ψ` holds at some step of the window and `φ` at every step before.
92    Until {
93        /// The window start, relative to the current step.
94        from: usize,
95        /// The window end (inclusive), `>= from`.
96        to: usize,
97        /// The formula that must hold until `right` does.
98        left: Box<Formula>,
99        /// The formula that must eventually hold.
100        right: Box<Formula>,
101    },
102}
103
104impl Formula {
105    /// `x_signal ≥ threshold`.
106    #[must_use]
107    pub fn ge(signal: usize, threshold: f64) -> Self {
108        Self::AtLeast { signal, threshold }
109    }
110
111    /// `x_signal ≤ threshold`.
112    #[must_use]
113    pub fn le(signal: usize, threshold: f64) -> Self {
114        Self::AtMost { signal, threshold }
115    }
116
117    /// `¬φ`.
118    #[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    /// `φ_1 ∧ … ∧ φ_k`.
128    #[must_use]
129    pub fn and(formulas: Vec<Self>) -> Self {
130        Self::And(formulas)
131    }
132
133    /// `φ_1 ∨ … ∨ φ_k`.
134    #[must_use]
135    pub fn or(formulas: Vec<Self>) -> Self {
136        Self::Or(formulas)
137    }
138
139    /// `G[from, to] φ`.
140    #[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    /// `F[from, to] φ`.
150    #[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    /// `φ U[from, to] ψ`.
160    #[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    /// The robustness at the first step of `trace`.
171    #[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    /// The constraint violation `max(0, -ρ)` at the first step: `0` when satisfied.
181    #[must_use]
182    pub fn violation<S: AsRef<[f64]>>(&self, trace: &[S]) -> f64 {
183        (-self.robustness(trace)).max(0.0)
184    }
185
186    /// The robustness at every step `0..len` (steps past the trace see an empty future).
187    #[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    /// The number of nodes, the complexity term of [`fit()`].
238    #[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    /// The predicate thresholds in depth-first order: the parameters [`fit()`] tunes.
251    #[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    /// A copy with the thresholds replaced, in the order of [`Formula::thresholds`]; missing
260    /// values leave thresholds unchanged.
261    #[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    /// Calls `f` on every threshold in depth-first order.
275    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
297/// Combines the signals of `parts` point-wise with `op`, starting from `identity`.
298fn 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
315/// Folds `inner` over the clipped window `[t + from, t + to]` for each `t < len`.
316fn 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
337/// The bounded until: `max` over `t' ∈ [t + from, t + to]` of
338/// `min(right(t'), min over t'' ∈ [t, t') of left(t''))`.
339fn 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
360/// Picks the candidate whose rollout trace is most robust for `formula`: EvoPlan's shield,
361/// which vetoes a policy's action when its short-horizon rollout violates the constraint and
362/// substitutes the most robust candidate. Returns `(index, robustness)` of the best candidate
363/// (the first among equals), or `None` if there are no candidates.
364///
365/// ```
366/// use evolutionary_planning::stl::{Formula, shield};
367///
368/// // Keep speed (signal 0) at most 1 for the next two steps.
369/// let phi = Formula::always(0, 2, Formula::le(0, 1.0));
370/// let speeds = [0.5, 1.5, 0.9];
371/// let best = shield(&speeds, |&v: &f64| vec![[v], [v], [v]], &phi);
372/// assert_eq!(best.map(|(i, _)| i), Some(0));
373/// ```
374pub 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    /// Hand-checked robustness values for every operator, including clipped windows.
397    #[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        // "x <= 3 until x >= 5": x(2) = 5 is reached with x <= 3 before: min(0, min(3, 1)) = 0.
428        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        // Requiring x <= 1 before fails at step 1 (x = 2): robustness -1.
431        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    /// The sign of robustness agrees with Boolean satisfaction checked by brute force.
436    #[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    /// Threshold extraction and replacement round-trip in depth-first order.
459    #[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}