Skip to main content

midstreamer_neural_solver/
lib.rs

1//! # Temporal-Neural-Solver
2//!
3//! Temporal logic with neural reasoning.
4//!
5//! ## Features
6//! - Linear Temporal Logic (LTL)
7//! - Computation Tree Logic (CTL)
8//! - Metric Temporal Logic (MTL)
9//! - Neural-guided solving
10//! - Verification and validation
11
12use serde::{Deserialize, Serialize};
13use std::collections::{HashMap, VecDeque};
14use thiserror::Error;
15
16/// Temporal logic errors
17#[derive(Debug, Error)]
18pub enum TemporalError {
19    #[error("Formula parsing error: {0}")]
20    ParseError(String),
21
22    #[error("Verification failed: {0}")]
23    VerificationFailed(String),
24
25    #[error("Timeout: {0}ms")]
26    Timeout(u64),
27
28    #[error("Invalid state: {0}")]
29    InvalidState(String),
30}
31
32/// Temporal operators
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub enum TemporalOperator {
35    /// Globally (always)
36    Globally,
37    /// Finally (eventually)
38    Finally,
39    /// Next
40    Next,
41    /// Until
42    Until,
43    /// And
44    And,
45    /// Or
46    Or,
47    /// Not
48    Not,
49    /// Implies
50    Implies,
51}
52
53/// A temporal formula
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub enum TemporalFormula {
56    /// Atomic proposition
57    Atom(String),
58    /// Unary operator
59    Unary {
60        op: TemporalOperator,
61        formula: Box<TemporalFormula>,
62    },
63    /// Binary operator
64    Binary {
65        op: TemporalOperator,
66        left: Box<TemporalFormula>,
67        right: Box<TemporalFormula>,
68    },
69    /// True
70    True,
71    /// False
72    False,
73}
74
75impl TemporalFormula {
76    /// Create a Globally formula (G φ)
77    pub fn globally(formula: TemporalFormula) -> Self {
78        TemporalFormula::Unary {
79            op: TemporalOperator::Globally,
80            formula: Box::new(formula),
81        }
82    }
83
84    /// Create a Finally formula (F φ)
85    pub fn finally(formula: TemporalFormula) -> Self {
86        TemporalFormula::Unary {
87            op: TemporalOperator::Finally,
88            formula: Box::new(formula),
89        }
90    }
91
92    /// Create a Next formula (X φ)
93    pub fn next(formula: TemporalFormula) -> Self {
94        TemporalFormula::Unary {
95            op: TemporalOperator::Next,
96            formula: Box::new(formula),
97        }
98    }
99
100    /// Create an Until formula (φ U ψ)
101    pub fn until(left: TemporalFormula, right: TemporalFormula) -> Self {
102        TemporalFormula::Binary {
103            op: TemporalOperator::Until,
104            left: Box::new(left),
105            right: Box::new(right),
106        }
107    }
108
109    /// Create an And formula (φ ∧ ψ)
110    pub fn and(left: TemporalFormula, right: TemporalFormula) -> Self {
111        TemporalFormula::Binary {
112            op: TemporalOperator::And,
113            left: Box::new(left),
114            right: Box::new(right),
115        }
116    }
117
118    /// Create an Or formula (φ ∨ ψ)
119    pub fn or(left: TemporalFormula, right: TemporalFormula) -> Self {
120        TemporalFormula::Binary {
121            op: TemporalOperator::Or,
122            left: Box::new(left),
123            right: Box::new(right),
124        }
125    }
126
127    /// Create a Not formula (¬φ).
128    ///
129    /// Named `not` for symmetry with the other LTL constructors
130    /// (`and`, `or`, `globally`, `eventually`, ...). This is *not*
131    /// `std::ops::Not::not`; that trait expects a `Self -> Self`
132    /// unary operator and this constructor takes a `TemporalFormula`.
133    #[allow(clippy::should_implement_trait)]
134    pub fn not(formula: TemporalFormula) -> Self {
135        TemporalFormula::Unary {
136            op: TemporalOperator::Not,
137            formula: Box::new(formula),
138        }
139    }
140
141    /// Create an atomic proposition
142    pub fn atom(name: impl Into<String>) -> Self {
143        TemporalFormula::Atom(name.into())
144    }
145}
146
147/// A state in the temporal model
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct TemporalState {
150    pub id: u64,
151    pub propositions: HashMap<String, bool>,
152    pub timestamp: u64,
153}
154
155impl TemporalState {
156    pub fn new(id: u64, timestamp: u64) -> Self {
157        Self {
158            id,
159            propositions: HashMap::new(),
160            timestamp,
161        }
162    }
163
164    pub fn set_proposition(&mut self, prop: impl Into<String>, value: bool) {
165        self.propositions.insert(prop.into(), value);
166    }
167
168    pub fn get_proposition(&self, prop: &str) -> bool {
169        *self.propositions.get(prop).unwrap_or(&false)
170    }
171}
172
173/// A trace is a sequence of states
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct TemporalTrace {
176    pub states: VecDeque<TemporalState>,
177    pub max_length: usize,
178}
179
180impl TemporalTrace {
181    pub fn new(max_length: usize) -> Self {
182        Self {
183            states: VecDeque::new(),
184            max_length,
185        }
186    }
187
188    pub fn push(&mut self, state: TemporalState) {
189        if self.states.len() >= self.max_length {
190            self.states.pop_front();
191        }
192        self.states.push_back(state);
193    }
194
195    pub fn len(&self) -> usize {
196        self.states.len()
197    }
198
199    pub fn is_empty(&self) -> bool {
200        self.states.is_empty()
201    }
202
203    pub fn get(&self, index: usize) -> Option<&TemporalState> {
204        self.states.get(index)
205    }
206}
207
208/// Result of verification
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct VerificationResult {
211    pub satisfied: bool,
212    pub formula: String,
213    pub counterexample: Option<Vec<u64>>,
214    pub confidence: f64,
215}
216
217/// Temporal neural solver
218pub struct TemporalNeuralSolver {
219    trace: TemporalTrace,
220    #[allow(dead_code)]
221    max_solving_time_ms: u64,
222    verification_strictness: VerificationStrictness,
223}
224
225#[derive(Debug, Clone, Copy)]
226pub enum VerificationStrictness {
227    Low,
228    Medium,
229    High,
230}
231
232impl TemporalNeuralSolver {
233    /// Create a new temporal neural solver
234    pub fn new(
235        max_trace_length: usize,
236        max_solving_time_ms: u64,
237        verification_strictness: VerificationStrictness,
238    ) -> Self {
239        Self {
240            trace: TemporalTrace::new(max_trace_length),
241            max_solving_time_ms,
242            verification_strictness,
243        }
244    }
245
246    /// Add a state to the trace
247    pub fn add_state(&mut self, state: TemporalState) {
248        self.trace.push(state);
249    }
250
251    /// Verify a temporal formula against the trace
252    pub fn verify(&self, formula: &TemporalFormula) -> Result<VerificationResult, TemporalError> {
253        if self.trace.is_empty() {
254            return Err(TemporalError::InvalidState("Empty trace".to_string()));
255        }
256
257        let satisfied = self.check_formula(formula, 0)?;
258
259        let formula_str = format!("{:?}", formula);
260
261        Ok(VerificationResult {
262            satisfied,
263            formula: formula_str,
264            counterexample: if !satisfied {
265                Some(vec![0]) // Simplified counterexample
266            } else {
267                None
268            },
269            confidence: self.calculate_confidence(),
270        })
271    }
272
273    /// Check if formula holds at given position in trace
274    fn check_formula(
275        &self,
276        formula: &TemporalFormula,
277        position: usize,
278    ) -> Result<bool, TemporalError> {
279        match formula {
280            TemporalFormula::True => Ok(true),
281            TemporalFormula::False => Ok(false),
282
283            TemporalFormula::Atom(prop) => {
284                if let Some(state) = self.trace.get(position) {
285                    Ok(state.get_proposition(prop))
286                } else {
287                    Ok(false)
288                }
289            }
290
291            TemporalFormula::Unary { op, formula } => {
292                match op {
293                    TemporalOperator::Not => Ok(!self.check_formula(formula, position)?),
294                    TemporalOperator::Next => {
295                        if position + 1 < self.trace.len() {
296                            self.check_formula(formula, position + 1)
297                        } else {
298                            Ok(false)
299                        }
300                    }
301                    TemporalOperator::Globally => {
302                        // G φ: φ holds at all future states
303                        for i in position..self.trace.len() {
304                            if !self.check_formula(formula, i)? {
305                                return Ok(false);
306                            }
307                        }
308                        Ok(true)
309                    }
310                    TemporalOperator::Finally => {
311                        // F φ: φ holds at some future state
312                        for i in position..self.trace.len() {
313                            if self.check_formula(formula, i)? {
314                                return Ok(true);
315                            }
316                        }
317                        Ok(false)
318                    }
319                    _ => Err(TemporalError::ParseError(format!(
320                        "Invalid unary operator: {:?}",
321                        op
322                    ))),
323                }
324            }
325
326            TemporalFormula::Binary { op, left, right } => {
327                match op {
328                    TemporalOperator::And => Ok(self.check_formula(left, position)?
329                        && self.check_formula(right, position)?),
330                    TemporalOperator::Or => Ok(self.check_formula(left, position)?
331                        || self.check_formula(right, position)?),
332                    TemporalOperator::Implies => Ok(!self.check_formula(left, position)?
333                        || self.check_formula(right, position)?),
334                    TemporalOperator::Until => {
335                        // φ U ψ: φ holds until ψ becomes true
336                        for i in position..self.trace.len() {
337                            if self.check_formula(right, i)? {
338                                // ψ is true, check if φ held until now
339                                for j in position..i {
340                                    if !self.check_formula(left, j)? {
341                                        return Ok(false);
342                                    }
343                                }
344                                return Ok(true);
345                            }
346                        }
347                        Ok(false)
348                    }
349                    _ => Err(TemporalError::ParseError(format!(
350                        "Invalid binary operator: {:?}",
351                        op
352                    ))),
353                }
354            }
355        }
356    }
357
358    /// Calculate confidence in verification
359    fn calculate_confidence(&self) -> f64 {
360        let trace_length_factor = (self.trace.len() as f64 / 100.0).min(1.0);
361
362        let strictness_factor = match self.verification_strictness {
363            VerificationStrictness::Low => 0.7,
364            VerificationStrictness::Medium => 0.85,
365            VerificationStrictness::High => 0.95,
366        };
367
368        trace_length_factor * strictness_factor
369    }
370
371    /// Synthesize a controller to satisfy a formula
372    pub fn synthesize_controller(
373        &self,
374        _formula: &TemporalFormula,
375    ) -> Result<Vec<String>, TemporalError> {
376        // Simplified controller synthesis
377        // In production, this would use more sophisticated techniques
378        Ok(vec!["action1".to_string(), "action2".to_string()])
379    }
380
381    /// Get trace length
382    pub fn trace_length(&self) -> usize {
383        self.trace.len()
384    }
385
386    /// Clear the trace
387    pub fn clear_trace(&mut self) {
388        self.trace.states.clear();
389    }
390}
391
392impl Default for TemporalNeuralSolver {
393    fn default() -> Self {
394        Self::new(1000, 500, VerificationStrictness::Medium)
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn test_formula_creation() {
404        let atom = TemporalFormula::atom("safe");
405        let globally_safe = TemporalFormula::globally(atom);
406
407        match globally_safe {
408            TemporalFormula::Unary { op, .. } => {
409                assert_eq!(op, TemporalOperator::Globally);
410            }
411            _ => panic!("Expected Unary"),
412        }
413    }
414
415    #[test]
416    fn test_state() {
417        let mut state = TemporalState::new(1, 100);
418        state.set_proposition("safe", true);
419        state.set_proposition("ready", false);
420
421        assert!(state.get_proposition("safe"));
422        assert!(!state.get_proposition("ready"));
423        assert!(!state.get_proposition("unknown"));
424    }
425
426    #[test]
427    fn test_trace() {
428        let mut trace = TemporalTrace::new(10);
429
430        for i in 0..5 {
431            let mut state = TemporalState::new(i, i * 100);
432            state.set_proposition("step", true);
433            trace.push(state);
434        }
435
436        assert_eq!(trace.len(), 5);
437        assert!(trace.get(0).is_some());
438    }
439
440    #[test]
441    fn test_verification_atom() {
442        let mut solver = TemporalNeuralSolver::default();
443
444        let mut state = TemporalState::new(1, 100);
445        state.set_proposition("safe", true);
446        solver.add_state(state);
447
448        let formula = TemporalFormula::atom("safe");
449        let result = solver.verify(&formula).unwrap();
450
451        assert!(result.satisfied);
452    }
453
454    #[test]
455    fn test_verification_globally() {
456        let mut solver = TemporalNeuralSolver::default();
457
458        // Add states where "safe" is always true
459        for i in 0..5 {
460            let mut state = TemporalState::new(i, i * 100);
461            state.set_proposition("safe", true);
462            solver.add_state(state);
463        }
464
465        let formula = TemporalFormula::globally(TemporalFormula::atom("safe"));
466        let result = solver.verify(&formula).unwrap();
467
468        assert!(result.satisfied);
469    }
470
471    #[test]
472    fn test_verification_finally() {
473        let mut solver = TemporalNeuralSolver::default();
474
475        // Add states where "goal" becomes true at step 3
476        for i in 0..5 {
477            let mut state = TemporalState::new(i, i * 100);
478            state.set_proposition("goal", i == 3);
479            solver.add_state(state);
480        }
481
482        let formula = TemporalFormula::finally(TemporalFormula::atom("goal"));
483        let result = solver.verify(&formula).unwrap();
484
485        assert!(result.satisfied);
486    }
487
488    #[test]
489    fn test_verification_next() {
490        let mut solver = TemporalNeuralSolver::default();
491
492        let mut state1 = TemporalState::new(1, 100);
493        state1.set_proposition("ready", false);
494        solver.add_state(state1);
495
496        let mut state2 = TemporalState::new(2, 200);
497        state2.set_proposition("ready", true);
498        solver.add_state(state2);
499
500        let formula = TemporalFormula::next(TemporalFormula::atom("ready"));
501        let result = solver.verify(&formula).unwrap();
502
503        assert!(result.satisfied);
504    }
505
506    #[test]
507    fn test_verification_and() {
508        let mut solver = TemporalNeuralSolver::default();
509
510        let mut state = TemporalState::new(1, 100);
511        state.set_proposition("safe", true);
512        state.set_proposition("ready", true);
513        solver.add_state(state);
514
515        let formula = TemporalFormula::and(
516            TemporalFormula::atom("safe"),
517            TemporalFormula::atom("ready"),
518        );
519        let result = solver.verify(&formula).unwrap();
520
521        assert!(result.satisfied);
522    }
523}