selen 0.15.5

Constraint Satisfaction Problem (CSP) solver
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Solution representation and solving statistics.
//!
//! This module provides types for representing solutions to CSP problems and
//! collecting statistics about the solving process.
//!
//! # Solution Access
//!
//! Solutions are represented by the `Solution` struct, which allows indexed access
//! to variable values using the original `VarId` handles. Every solution includes
//! statistics about how it was found.
//!
//! # Statistics
//!
//! The solver collects comprehensive statistics about the solving process, including:
//! - **Search metrics**: propagation steps, search nodes, and backtracking operations
//! - **Performance data**: total solve time, time per operation, and memory usage
//! - **Problem characteristics**: number of variables and constraints
//! 
//!
//! # Example
//!
//! ```rust
//! use selen::prelude::*;
//!
//! let mut m = Model::default();
//! let x = m.int(1, 10);
//! let y = m.int(1, 10);
//! let sum = m.add(x, y);
//! m.new(sum.eq(15));
//!
//! // Solve and get solution with enhanced statistics
//! let solution = m.solve().unwrap();
//!
//! // Access solution values
//! println!("x = {:?}", solution[x]);
//! println!("y = {:?}", solution[y]);
//!
//! // Access all enhanced statistics fields
//! let stats = &solution.stats;
//! println!("Propagations: {}", stats.propagation_count);
//! println!("Search nodes: {}", stats.node_count);
//! println!("Solve time: {:.3}ms", stats.solve_time.as_secs_f64() * 1000.0);
//! println!("Peak memory usage: {}MB", stats.peak_memory_mb);
//! println!("Problem size: {} variables, {} constraints", 
//!          stats.variables, stats.constraint_count);
//!
//! // Use convenience analysis methods
//! println!("Search efficiency: {:.1} propagations/node", stats.efficiency());
//! println!("Time per propagation: {:.2}μs", 
//!          stats.time_per_propagation().as_nanos() as f64 / 1000.0);
//! println!("Time per search node: {:.2}μs", 
//!          stats.time_per_node().as_nanos() as f64 / 1000.0);
//!
//! // Display comprehensive summary
//! stats.display_summary();
//! ```
//!
//! # Runtime API Example
//!
//! ```rust
//! use selen::prelude::*;
//!
//! let mut m = Model::default();
//! let x = m.int(1, 10);
//! let y = m.int(1, 10);
//!
//! // Build constraints programmatically
//! m.new(x.add(y).eq(15));
//! m.new(x.mul(2).le(y));
//!
//! // Solve and access solution with comprehensive statistics
//! let solution = m.solve().unwrap();
//! println!("x = {:?}, y = {:?}", solution[x], solution[y]);
//!
//! // Access all enhanced statistics fields
//! let stats = &solution.stats;
//! println!("Core metrics:");
//! println!("  Propagations: {}", stats.propagation_count);
//! println!("  Search nodes: {}", stats.node_count);
//! 
//! println!("Performance metrics:");
//! println!("  Solve time: {:.3}ms", stats.solve_time.as_secs_f64() * 1000.0);
//! println!("  Peak memory: {}MB", stats.peak_memory_mb);
//! 
//! println!("Problem characteristics:");
//! println!("  Variables: {}", stats.variables);
//! println!("  Constraints: {}", stats.constraint_count);
//! 
//! // Use all convenience analysis methods
//! if stats.node_count > 0 {
//!     println!("Efficiency analysis:");
//!     println!("  {:.2} propagations/node", stats.efficiency());
//!     println!("  {:.2}μs/propagation", stats.time_per_propagation().as_nanos() as f64 / 1000.0);
//!     println!("  {:.2}μs/node", stats.time_per_node().as_nanos() as f64 / 1000.0);
//! }
//! 
//! // Display complete formatted summary
//! stats.display_summary();
//! 
//! // Create statistics manually using constructor
//! let custom_stats = SolveStats::new(100, 10, 
//!     std::time::Duration::from_millis(5), 20, 15, 8);
//! println!("Custom stats efficiency: {:.1}", custom_stats.efficiency());
//! ```

use std::borrow::Borrow;
use std::ops::Index;
use std::time::Duration;

use crate::variables::{Val, VarId, VarIdBin};

/// Error type for value access operations on solutions
#[derive(Debug, Clone, PartialEq)]
pub enum ValueAccessError {
    /// Attempted to get integer value from a variable containing a float
    ExpectedInteger { variable: VarId, actual_value: Val },
    /// Attempted to get float value from a variable containing an integer
    ExpectedFloat { variable: VarId, actual_value: Val },
    /// Attempted to get boolean value from a variable containing value other than 0 or 1
    ExpectedBoolean { variable: VarId, actual_value: Val },
}

impl std::fmt::Display for ValueAccessError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValueAccessError::ExpectedInteger { variable, actual_value } => {
                write!(f, "Expected integer value for variable {:?}, but found {:?}", variable, actual_value)
            }
            ValueAccessError::ExpectedFloat { variable, actual_value } => {
                write!(f, "Expected float value for variable {:?}, but found {:?}", variable, actual_value)
            }
            ValueAccessError::ExpectedBoolean { variable, actual_value } => {
                write!(f, "Expected boolean value (0 or 1) for variable {:?}, but found {:?}", variable, actual_value)
            }
        }
    }
}

impl std::error::Error for ValueAccessError {}

/// Statistics collected during the solving process.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SolveStats {
    // ===== Search Metrics =====
    /// Number of propagation steps performed during solving
    pub propagation_count: usize,
    /// Number of search nodes (branching points) explored during solving
    pub node_count: usize,

    // ===== Timing =====
    /// Total time spent solving (in seconds)
    pub solve_time: Duration,
    /// Initialisation time (in seconds)
    pub init_time: Duration,

    // ===== Memory =====
    /// Peak memory usage during solving (in MB)
    /// 
    /// This is the TOTAL peak memory used, including:
    /// - CSP solver memory (search stack, variables, propagators)
    /// - LP solver memory (if LP was used)
    /// 
    /// For breakdown of LP-specific memory, see lp_stats.peak_memory_mb
    pub peak_memory_mb: usize,

    // ===== Variable Counts =====
    /// Total number of variables
    pub variables: usize,
    /// Number of integer variables created
    pub int_variables: usize,
    /// Number of bool variables created
    pub bool_variables: usize,
    /// Number of float variables created
    pub float_variables: usize,
    /// Number of set variables created
    pub set_variables: usize,

    // ===== Constraint Metrics =====
    /// Number of constraints in the problem
    pub constraint_count: usize,
    /// Number of propagators created
    pub propagators: usize,

    // ===== Objective =====
    /// Current objective value
    pub objective: f64,
    /// Dual bound on the objective value
    pub objective_bound: f64,

    // ===== LP Solver Integration =====
    /// Whether the LP solver was used during solving
    pub lp_solver_used: bool,
    /// Number of linear constraints extracted for LP solver
    pub lp_constraint_count: usize,
    /// Number of variables used in LP solver (subset of total variables that appear in linear constraints)
    pub lp_variable_count: usize,
    /// Statistics from LP solver (if used)
    pub lp_stats: Option<crate::lpsolver::types::LpStats>,
}

impl SolveStats {
    /// Create new statistics with core fields (for backward compatibility)
    /// 
    /// Other fields are set to default values.
    pub fn new(
        propagation_count: usize,
        node_count: usize,
        solve_time: Duration,
        variable_count: usize,
        constraint_count: usize,
        peak_memory_mb: usize,
    ) -> Self {
        Self {
            propagation_count,
            node_count,
            solve_time,
            variables: variable_count,
            constraint_count,
            peak_memory_mb,
            init_time: Duration::ZERO,
            
            int_variables: 0,
            bool_variables: 0,
            float_variables: 0,
            set_variables: 0,
            
            propagators: 0,
            objective: 0.0,
            objective_bound: 0.0,
            
            lp_solver_used: false,
            lp_constraint_count: 0,
            lp_variable_count: 0,
            lp_stats: None,
        }
    }

    /// Create new statistics with all fields
    pub fn with_all_fields(
        propagation_count: usize,
        node_count: usize,
        solve_time: Duration,
        init_time: Duration,
        variables: usize,
        int_variables: usize,
        bool_variables: usize,
        float_variables: usize,
        set_variables: usize,
        constraint_count: usize,
        propagators: usize,
        peak_memory_mb: usize,
        objective: f64,
        objective_bound: f64,
    ) -> Self {
        Self {
            propagation_count,
            node_count,
            
            solve_time,
            init_time,
            
            peak_memory_mb,
            
            variables,
            int_variables,
            bool_variables,
            float_variables,
            set_variables,
            
            constraint_count,
            propagators,
            
            objective,
            objective_bound,
            
            lp_solver_used: false,
            lp_constraint_count: 0,
            lp_variable_count: 0,
            lp_stats: None,
        }
    }

    /// Get solving efficiency as propagations per node
    pub fn efficiency(&self) -> f64 {
        if self.node_count > 0 {
            self.propagation_count as f64 / self.node_count as f64
        } else {
            0.0
        }
    }

    /// Get average time per propagation step
    pub fn time_per_propagation(&self) -> Duration {
        if self.propagation_count > 0 {
            self.solve_time / self.propagation_count as u32
        } else {
            Duration::ZERO
        }
    }

    /// Get average time per search node
    pub fn time_per_node(&self) -> Duration {
        if self.node_count > 0 {
            self.solve_time / self.node_count as u32
        } else {
            Duration::ZERO
        }
    }

    /// Display a summary of the solving statistics
    pub fn display_summary(&self) {
        println!("=== Solving Statistics ===");
        
        // Timing
        println!("Timing:");
        println!("  Solve time: {:.3}ms", self.solve_time.as_secs_f64() * 1000.0);
        println!("  Init time: {:.3}ms", self.init_time.as_secs_f64() * 1000.0);
        
        // Memory
        println!("Memory:");
        println!("  Total peak usage: {}MB", self.peak_memory_mb);
        
        // LP Solver information (if used)
        if self.lp_solver_used {
            if let Some(ref lp_stats) = self.lp_stats {
                println!("    (includes LP solver: {:.2}MB)", lp_stats.peak_memory_mb);
            }
        }
        
        // Problem characteristics
        println!("Problem:");
        println!("  Total variables: {}", self.variables);
        if self.int_variables > 0 {
            println!("    - Integer: {}", self.int_variables);
        }
        if self.bool_variables > 0 {
            println!("    - Bool: {}", self.bool_variables);
        }
        if self.float_variables > 0 {
            println!("    - Float: {}", self.float_variables);
        }
        if self.set_variables > 0 {
            println!("    - Set: {}", self.set_variables);
        }
        println!("  Constraints: {}", self.constraint_count);
        println!("  Propagators: {}", self.propagators);
        
        // LP Solver information (if used)
        if self.lp_solver_used {
            println!("LP Solver:");
            println!("  Linear constraints: {}", self.lp_constraint_count);
            println!("  Linear variables: {}", self.lp_variable_count);
        }
        
        // Search metrics
        println!("Search:");
        println!("  Nodes: {}", self.node_count);
        println!("  Propagations: {}", self.propagation_count);
        
        // Objective (if applicable)
        if self.objective != 0.0 || self.objective_bound != 0.0 {
            println!("Objective:");
            println!("  Current value: {}", self.objective);
            println!("  Bound: {}", self.objective_bound);
        }
        
        // Efficiency analysis
        if self.node_count > 0 {
            println!("Efficiency:");
            println!("  {:.1} propagations/node", self.efficiency());
            println!("  {:.2}μs/propagation", 
                     self.time_per_propagation().as_nanos() as f64 / 1000.0);
            println!("  {:.2}μs/node", 
                     self.time_per_node().as_nanos() as f64 / 1000.0);
        } else if self.propagation_count > 0 {
            println!("Efficiency: Pure propagation (no search required)");
            println!("  {:.2}μs/propagation", 
                     self.time_per_propagation().as_nanos() as f64 / 1000.0);
        }
        println!("==========================");
    }
}

/// Assignment for decision variables that satisfies all constraints.
#[derive(Debug, PartialEq)]
pub struct Solution {
    values: Vec<Val>,
    /// Statistics collected during the solving process
    pub stats: SolveStats,
}

impl Index<VarId> for Solution {
    type Output = Val;

    fn index(&self, index: VarId) -> &Self::Output {
        &self.values[index]
    }
}

impl Solution {
    /// Create a new solution with values and statistics
    pub fn new(values: Vec<Val>, stats: SolveStats) -> Self {
        Self { values, stats }
    }

    /// Create a solution from values with default (empty) statistics
    pub fn from_values(values: Vec<Val>) -> Self {
        Self {
            values,
            stats: SolveStats::default(),
        }
    }

    /// Get a reference to the solving statistics
    pub fn stats(&self) -> &SolveStats {
        &self.stats
    }

    /// Get assignments for the decision variables provided as a slice.
    #[must_use]
    pub fn get_values(&self, vs: &[VarId]) -> Vec<Val> {
        self.get_values_iter(vs.iter().copied()).collect()
    }

    /// Get assignments for the decision variables provided as a reference to an array.
    #[must_use]
    pub fn get_values_array<const N: usize>(&self, vs: &[VarId; N]) -> [Val; N] {
        vs.map(|v| self[v])
    }

    /// Get assignments for the provided decision variables.
    pub fn get_values_iter<'a, I>(&'a self, vs: I) -> impl Iterator<Item = Val> + 'a
    where
        I: IntoIterator + 'a,
        I::Item: Borrow<VarId>,
    {
        vs.into_iter().map(|v| self[*v.borrow()])
    }

    /// Get binary assignment for the provided decision variable.
    #[must_use]
    pub fn get_value_binary(&self, v: impl Borrow<VarIdBin>) -> bool {
        self.values[v.borrow().0] == Val::ValI(1)
    }

    /// Get binary assignments for the decision variables provided as a slice.
    #[must_use]
    pub fn get_values_binary(&self, vs: &[VarIdBin]) -> Vec<bool> {
        self.get_values_binary_iter(vs.iter().copied()).collect()
    }

    /// Get binary assignments for the decision variables provided as a reference to an array.
    #[must_use]
    pub fn get_values_binary_array<const N: usize>(&self, vs: &[VarIdBin; N]) -> [bool; N] {
        vs.map(|v| self.get_value_binary(v))
    }

    /// Get binary assignments for the provided decision variables.
    pub fn get_values_binary_iter<'a, I>(&'a self, vs: I) -> impl Iterator<Item = bool> + 'a
    where
        I: IntoIterator + 'a,
        I::Item: Borrow<VarIdBin>,
    {
        vs.into_iter().map(|v| self.get_value_binary(v))
    }
    
    /// Get the integer value for a variable (backward compatible panicking version)
    /// **Warning**: This method panics if the variable doesn't contain an integer.
    /// Use `try_get_int()` for safe error handling.
    #[must_use]
    pub fn get_int(&self, var: VarId) -> i32 {
        self.try_get_int(var).unwrap()
    }
    
    /// Get the float value for a variable (backward compatible panicking version)
    /// **Warning**: This method panics if the variable doesn't contain a float.
    /// Use `try_get_float()` for safe error handling.
    #[must_use] 
    pub fn get_float(&self, var: VarId) -> f64 {
        self.try_get_float(var).unwrap()
    }
    
    /// Get the boolean value for a variable
    /// Booleans are represented as integers: 0 = false, 1 = true
    /// Returns an error if the variable doesn't contain 0 or 1.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use selen::prelude::*;
    /// 
    /// let mut m = Model::default();
    /// let b = m.bool();
    /// m.new(b.eq(bool(true)));
    /// 
    /// let solution = m.solve().unwrap();
    /// assert_eq!(solution.get_bool(b).unwrap(), true);
    /// ```
    #[must_use]
    pub fn get_bool(&self, var: VarId) -> Result<bool, ValueAccessError> {
        match self[var] {
            Val::ValI(0) => Ok(false),
            Val::ValI(1) => Ok(true),
            actual_value => Err(ValueAccessError::ExpectedBoolean {
                variable: var,
                actual_value,
            }),
        }
    }
    
    /// Get the integer value for a variable (safe version)
    /// Returns the integer value if the variable contains an integer, returns an error otherwise
    #[must_use]
    pub fn try_get_int(&self, var: VarId) -> Result<i32, ValueAccessError> {
        match self[var] {
            Val::ValI(i) => Ok(i),
            actual_value => Err(ValueAccessError::ExpectedInteger { 
                variable: var, 
                actual_value 
            }),
        }
    }
    
    /// Get the float value for a variable (safe version)
    /// Returns the float value if the variable contains a float, returns an error otherwise
    #[must_use] 
    pub fn try_get_float(&self, var: VarId) -> Result<f64, ValueAccessError> {
        match self[var] {
            Val::ValF(f) => Ok(f),
            actual_value => Err(ValueAccessError::ExpectedFloat { 
                variable: var, 
                actual_value 
            }),
        }
    }
    
    /// Get the boolean value for a variable (safe version)
    /// Returns the boolean value if the variable contains 0 or 1, returns an error otherwise
    #[must_use]
    pub fn try_get_bool(&self, var: VarId) -> Result<bool, ValueAccessError> {
        match self[var] {
            Val::ValI(0) => Ok(false),
            Val::ValI(1) => Ok(true),
            actual_value => Err(ValueAccessError::ExpectedBoolean { 
                variable: var, 
                actual_value 
            }),
        }
    }
    
    /// Get the integer value for a variable (explicit unchecked version)  
    /// **Warning**: This method panics if the variable doesn't contain an integer.
    /// Same as `get_int()` but more explicit about the risk.
    #[must_use]
    pub fn get_int_unchecked(&self, var: VarId) -> i32 {
        self.get_int(var)
    }
    
    /// Get the float value for a variable (explicit unchecked version)
    /// **Warning**: This method panics if the variable doesn't contain a float.
    /// Same as `get_float()` but more explicit about the risk.
    #[must_use] 
    pub fn get_float_unchecked(&self, var: VarId) -> f64 {
        self.get_float(var)
    }
    
    /// Get the value for a variable as an integer if possible (Option-based)
    /// Returns Some(i32) if the value is an integer, None otherwise
    #[must_use]
    pub fn as_int(&self, var: VarId) -> Option<i32> {
        match self[var] {
            Val::ValI(i) => Some(i),
            Val::ValF(_) => None,
        }
    }
    
    /// Get the value for a variable as a float if possible (Option-based)
    /// Returns Some(f64) if the value is a float, None otherwise
    #[must_use]
    pub fn as_float(&self, var: VarId) -> Option<f64> {
        match self[var] {
            Val::ValF(f) => Some(f),
            Val::ValI(_) => None,
        }
    }
    
    /// Get the value for a variable as a boolean if possible (Option-based)
    /// Returns Some(bool) if the value is 0 or 1, None otherwise
    #[must_use]
    pub fn as_bool(&self, var: VarId) -> Option<bool> {
        match self[var] {
            Val::ValI(0) => Some(false),
            Val::ValI(1) => Some(true),
            _ => None,
        }
    }
    
    /// Generic get method using type inference (panicking version)
    /// This allows `let x: i32 = solution.get(var);` syntax
    /// **Warning**: This method may panic. Consider using `try_get()` instead.
    pub fn get<T>(&self, var: VarId) -> T 
    where 
        Self: GetValue<T>
    {
        self.get_value(var)
    }
    
    /// Generic safe get method using type inference
    /// This allows `let x: Result<i32, _> = solution.try_get(var);` syntax
    pub fn try_get<T>(&self, var: VarId) -> Result<T, ValueAccessError>
    where 
        Self: TryGetValue<T>
    {
        self.try_get_value(var)
    }
}

/// Trait for type-safe value extraction (panicking version)
pub trait GetValue<T> {
    fn get_value(&self, var: VarId) -> T;
}

/// Trait for type-safe value extraction (safe version)
pub trait TryGetValue<T> {
    fn try_get_value(&self, var: VarId) -> Result<T, ValueAccessError>;
}

impl GetValue<i32> for Solution {
    fn get_value(&self, var: VarId) -> i32 {
        self.get_int_unchecked(var)
    }
}

impl GetValue<f64> for Solution {
    fn get_value(&self, var: VarId) -> f64 {
        self.get_float_unchecked(var)
    }
}

impl GetValue<Option<i32>> for Solution {
    fn get_value(&self, var: VarId) -> Option<i32> {
        self.as_int(var)
    }
}

impl GetValue<Option<f64>> for Solution {
    fn get_value(&self, var: VarId) -> Option<f64> {
        self.as_float(var)
    }
}

impl TryGetValue<i32> for Solution {
    fn try_get_value(&self, var: VarId) -> Result<i32, ValueAccessError> {
        self.try_get_int(var)
    }
}

impl TryGetValue<f64> for Solution {
    fn try_get_value(&self, var: VarId) -> Result<f64, ValueAccessError> {
        self.try_get_float(var)
    }
}

impl From<Vec<Val>> for Solution {
    fn from(values: Vec<Val>) -> Self {
        Self::from_values(values)
    }
}