rssn 0.2.9

A comprehensive scientific computing library for Rust, aiming for feature parity with NumPy and SymPy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Computation engine for managing and executing asynchronous computations.
//!
//! The `ComputeEngine` provides a high-level interface for submitting, tracking,
//! and managing computational tasks. It handles:
//! - Expression parsing and caching
//! - Asynchronous computation execution
//! - Progress tracking and status monitoring
//! - Pause/resume/cancel operations
//! - Result caching
//!
//! # Examples
//!
//! ```
//! use rssn::compute::engine::ComputeEngine;
//!
//! let engine = ComputeEngine::new();
//!
//! // Submit a computation
//! let id = engine.parse_and_submit("2 + 2").unwrap();
//!
//! // Check status
//! if let Some(status) = engine.get_status(&id) {
//!     println!("Status: {:?}", status);
//! }
//!
//! // Get result when complete
//! std::thread::sleep(std::time::Duration::from_secs(1));
//!
//! if let Some(result) = engine.get_result(&id) {
//!     println!("Result: {}", result);
//! }
//! ```

#![allow(unused_imports)]

use std::collections::HashMap;
use std::io::prelude::*;
use std::sync::Arc;
use std::sync::Condvar;
use std::sync::Mutex;
use std::sync::RwLock;
use std::sync::atomic::AtomicBool;

/// Development in place.
use rayon::prelude::*;
use uuid::Uuid;

use crate::compute::cache::ComputationResultCache;
use crate::compute::cache::ParsingCache;
use crate::compute::computation::Computation;
use crate::compute::computation::ComputationProgress;
use crate::compute::computation::ComputationStatus;
use crate::compute::computation::Value;
use crate::compute::state::State;
use crate::symbolic::core::Expr;

/// A computation engine for managing asynchronous computations.
///
/// `ComputeEngine` maintains a registry of active computations and provides
/// methods for submitting new computations, querying their status, and
/// controlling their execution (pause/resume/cancel).
///
/// # Thread Safety
///
/// `ComputeEngine` is thread-safe and can be shared across multiple threads.
/// All internal state is protected by appropriate synchronization primitives.
///
/// # Caching
///
/// The engine maintains two caches:
/// - **Parsing cache**: Stores parsed expressions to avoid re-parsing
/// - **Result cache**: Stores computation results for reuse
#[allow(dead_code)]
#[derive(Clone)]
pub struct ComputeEngine {
    /// Registry of active computations, indexed by computation ID.
    computations: Arc<RwLock<HashMap<String, Arc<Mutex<Computation>>>>>,
    /// Cache for parsed expressions.
    parsing_cache: Arc<ParsingCache>,
    /// Cache for computation results.
    result_cache: Arc<ComputationResultCache>,
}

impl ComputeEngine {
    /// Creates a new `ComputeEngine`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            computations: Arc::new(RwLock::new(HashMap::new())),
            parsing_cache: Arc::new(ParsingCache::new()),
            result_cache: Arc::new(ComputationResultCache::new()),
        }
    }

    /// Parses an input string and submits it as a computation.
    ///
    /// This method first attempts to retrieve the parsed expression from the
    /// parsing cache. If not found, it parses the input and caches the result.
    /// The parsed expression is then submitted for computation.
    ///
    /// # Arguments
    ///
    /// * `input` - The input string to parse and compute
    ///
    /// # Returns
    ///
    /// * `Ok(String)` - The computation ID on success
    /// * `Err(String)` - An error message if parsing fails
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// match engine.parse_and_submit("x + 1") {
    ///     | Ok(id) => {
    ///         println!("Computation ID: {}", id)
    ///     },
    ///     | Err(e) => eprintln!("Parse error: {}", e),
    /// }
    /// ```
    ///
    /// # Errors
    /// Returns an error string if the parsing fails.
    pub fn parse_and_submit(
        &self,
        input: &str,
    ) -> Result<String, String> {
        let expr = match self.parsing_cache.get(input) {
            | Some(expr) => expr,
            | None => {
                match crate::input::parser::parse_expr(input) {
                    | Ok((_, expr)) => {
                        let expr = Arc::new(expr);

                        self.parsing_cache.set(input.to_string(), expr.clone());

                        expr
                    },
                    | Err(e) => return Err(e.to_string()),
                }
            },
        };

        Ok(self.submit(expr))
    }

    /// Gets the current status of a computation.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Returns
    ///
    /// * `Some(ComputationStatus)` - The current status if the computation exists
    /// * `None` - If the computation ID is not found
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// if let Some(status) = engine.get_status(&id) {
    ///     println!("Status: {:?}", status);
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    #[must_use]
    pub fn get_status(
        &self,
        id: &str,
    ) -> Option<ComputationStatus> {
        let computations = self.computations.read().expect(
            "ComputeEngine \
                 computations lock \
                 poisoned",
        );

        computations.get(id).map(|comp| {
            comp.lock()
                .expect(
                    "Computation \
                         lock poisoned",
                )
                .status
                .clone()
        })
    }

    /// Gets the current progress of a computation.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Returns
    ///
    /// * `Some(ComputationProgress)` - The current progress if the computation exists
    /// * `None` - If the computation ID is not found
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// if let Some(progress) = engine.get_progress(&id) {
    ///     println!("Progress: {}%", progress.percentage);
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    #[must_use]
    pub fn get_progress(
        &self,
        id: &str,
    ) -> Option<ComputationProgress> {
        let computations = self.computations.read().expect(
            "ComputeEngine \
                 computations lock \
                 poisoned",
        );

        computations.get(id).map(|comp| {
            comp.lock()
                .expect(
                    "Computation \
                         lock poisoned",
                )
                .progress
                .clone()
        })
    }

    /// Gets the result of a completed computation.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Returns
    ///
    /// * `Some(Value)` - The result if the computation is complete
    /// * `None` - If the computation is not found or not yet complete
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// // Wait for completion
    /// std::thread::sleep(std::time::Duration::from_secs(6));
    ///
    /// if let Some(result) = engine.get_result(&id) {
    ///     println!("Result: {}", result);
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    #[must_use]
    pub fn get_result(
        &self,
        id: &str,
    ) -> Option<Value> {
        let computations = self.computations.read().expect(
            "ComputeEngine \
                 computations lock \
                 poisoned",
        );

        computations.get(id).and_then(|comp| {
            comp.lock()
                .expect(
                    "Computation \
                         lock poisoned",
                )
                .result
                .clone()
        })
    }

    /// Submits an expression for asynchronous computation.
    ///
    /// This method creates a new computation task and executes it asynchronously
    /// using Rayon's thread pool. The computation can be monitored, paused,
    /// resumed, or cancelled using the returned ID.
    ///
    /// # Arguments
    ///
    /// * `expr` - The expression to compute
    ///
    /// # Returns
    ///
    /// A unique computation ID (UUID) as a string
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use rssn::compute::engine::ComputeEngine;
    /// use rssn::symbolic::core::Expr;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let expr = Arc::new(Expr::Constant(42.0));
    ///
    /// let id = engine.submit(expr);
    ///
    /// println!("Submitted computation: {}", id);
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn submit(
        &self,
        expr: Arc<Expr>,
    ) -> String {
        let id = Uuid::new_v4().to_string();

        let pause = Arc::new((Mutex::new(false), Condvar::new()));

        let computation = Arc::new(Mutex::new(Computation {
            id: id.clone(),
            expr,
            status: ComputationStatus::Pending,
            progress: ComputationProgress {
                percentage: 0.0,
                description: "Pending".to_string(),
            },
            result: None,
            cancel_signal: Arc::new(AtomicBool::new(false)),
            state: State {
                intermediate_value: String::new(),
            },
            pause: pause.clone(),
        }));

        {
            let mut computations = self.computations.write().expect(
                "ComputeEngine \
                     computations \
                     lock poisoned",
            );

            computations.insert(id.clone(), computation.clone());
        }

        let _engine = self.clone();

        let result_cache = self.result_cache.clone();

        rayon::spawn(move || {
            let (lock, cvar) = &*pause;

            let mut comp_guard = computation.lock().expect(
                "Computation \
                         lock poisoned",
            );

            comp_guard.status = ComputationStatus::Running;

            // Simulate work
            for i in 0u8..100u8 {
                let mut paused = lock.lock().expect(
                    "Pause lock \
                         poisoned",
                );

                while *paused {
                    comp_guard.status = ComputationStatus::Paused;

                    println!(
                        "Computation \
                         {} paused.",
                        comp_guard.id
                    );

                    paused = cvar.wait(paused).expect("Condition variable wait failed");
                }

                drop(paused);

                comp_guard.status = ComputationStatus::Running;

                if comp_guard.status == ComputationStatus::Failed("Cancelled".to_string()) {
                    println!("Computation {} cancelled.", comp_guard.id);

                    return;
                }

                std::thread::sleep(std::time::Duration::from_millis(50));

                comp_guard.progress.percentage = f32::from(i); // i is 0..99, safe to use From for f32

                comp_guard.progress.description = format!("{i}% complete");
            }

            comp_guard.status = ComputationStatus::Completed;

            comp_guard.progress.percentage = 100.0;

            comp_guard.progress.description = "Completed".to_string();

            let result = "Result of the \
                 computation"
                .to_string();

            comp_guard.result = Some(result.clone());

            result_cache.set(comp_guard.expr.clone(), result);
        });

        id
    }

    /// Pauses a running computation.
    ///
    /// The computation will pause at the next checkpoint and can be resumed
    /// using the `resume` method.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// // Pause the computation
    /// engine.pause(&id);
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    pub fn pause(
        &self,
        id: &str,
    ) {
        let computation = self
            .computations
            .read()
            .expect(
                "ComputeEngine \
                 computations lock \
                 poisoned",
            )
            .get(id)
            .cloned();

        if let Some(computation) = computation {
            let pause = {
                let comp = computation.lock().expect(
                    "Computation \
                         lock poisoned",
                );

                comp.pause.clone()
            };

            {
                let mut paused = pause.0.lock().expect(
                    "Pause lock \
                         poisoned",
                );

                *paused = true;
            }

            pause.1.notify_one();
        }
    }

    /// Resumes a paused computation.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// engine.pause(&id);
    ///
    /// // ... later ...
    /// engine.resume(&id);
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    pub fn resume(
        &self,
        id: &str,
    ) {
        let computation = self
            .computations
            .read()
            .expect(
                "ComputeEngine \
                 computations lock \
                 poisoned",
            )
            .get(id)
            .cloned();

        if let Some(computation) = computation {
            let pause = {
                let comp = computation.lock().expect(
                    "Computation \
                         lock poisoned",
                );

                comp.pause.clone()
            };

            {
                let mut paused = pause.0.lock().expect(
                    "Pause lock \
                         poisoned",
                );

                *paused = false;
            }

            pause.1.notify_one();
        }
    }

    /// Cancels a computation and removes it from the registry.
    ///
    /// The computation will be marked as failed with status "Cancelled" and
    /// removed from the active computations.
    ///
    /// # Arguments
    ///
    /// * `id` - The computation ID
    ///
    /// # Examples
    ///
    /// ```
    /// use rssn::compute::engine::ComputeEngine;
    ///
    /// let engine = ComputeEngine::new();
    ///
    /// let id = engine.parse_and_submit("2 + 2").unwrap();
    ///
    /// // Cancel the computation
    /// engine.cancel(&id);
    /// ```
    ///
    /// # Panics
    /// Panics if the internal cache lock is poisoned.
    pub fn cancel(
        &self,
        id: &str,
    ) {
        let computation = self
            .computations
            .read()
            .expect(
                "ComputeEngine \
                 computations lock \
                 poisoned",
            )
            .get(id)
            .cloned();

        if let Some(computation) = computation {
            let pause = {
                let mut comp = computation.lock().expect(
                    "Computation \
                         lock poisoned",
                );

                comp.status = ComputationStatus::Failed("Cancelled".to_string());

                comp.pause.clone()
            };

            {
                let mut paused = pause.0.lock().expect(
                    "Pause lock \
                         poisoned",
                );

                *paused = false;
            }

            pause.1.notify_one();
        }

        self.computations
            .write()
            .expect(
                "ComputeEngine \
                 computations lock \
                 poisoned",
            )
            .remove(id);
    }
}

impl Default for ComputeEngine {
    fn default() -> Self {
        Self::new()
    }
}