Skip to main content

cobre_solver/
types.rs

1//! Core types for the solver abstraction layer.
2//!
3//! Defines the canonical representations of LP solutions, basis management,
4//! and terminal solver errors used throughout the solver interface.
5
6use core::fmt;
7
8/// Simplex basis storing solver-native `i32` status codes for zero-copy round-trip
9/// basis management.
10///
11/// `Basis` stores the raw solver `i32` status codes directly, enabling zero-copy
12/// round-trip warm-starting via `copy_from_slice` (memcpy). This avoids per-element
13/// translation overhead when the caller only needs to save and restore the basis
14/// without inspecting individual statuses.
15///
16/// `HiGHS` uses `HighsInt` (4 bytes) for status codes; CLP uses `unsigned char`
17/// (1 byte, widened to `i32` in this representation). The caller is responsible
18/// for matching the buffer dimensions to the LP model before use.
19///
20/// See Solver Abstraction SS9.
21#[derive(Debug, Clone)]
22pub struct Basis {
23    /// Solver-native `i32` status codes for each column (length must equal `num_cols`).
24    pub col_status: Vec<i32>,
25
26    /// Solver-native `i32` status codes for each row, including structural and dynamic rows.
27    pub row_status: Vec<i32>,
28}
29
30impl Basis {
31    /// Creates a new `Basis` with pre-allocated, zero-filled status code buffers.
32    ///
33    /// Both `col_status` and `row_status` are allocated to the requested lengths
34    /// and filled with `0_i32`. The caller reuses this buffer across solves by
35    /// passing it to [`crate::SolverInterface::get_basis`] on each iteration.
36    #[must_use]
37    pub fn new(num_cols: usize, num_rows: usize) -> Self {
38        Self {
39            col_status: vec![0_i32; num_cols],
40            row_status: vec![0_i32; num_rows],
41        }
42    }
43}
44
45/// Complete solution from a successful LP solve.
46///
47/// All values are in the original (unscaled) problem space. Dual values
48/// are pre-normalized to the canonical sign convention defined in
49/// [Solver Abstraction SS8](../../../cobre-docs/src/specs/architecture/solver-abstraction.md)
50/// before this struct is returned -- solver-specific sign differences are
51/// resolved within the [`crate::SolverInterface`] implementation.
52///
53/// See [Solver Interface Trait SS4.1](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md).
54#[derive(Debug, Clone)]
55pub struct LpSolution {
56    /// Optimal objective value (minimization sense).
57    pub objective: f64,
58
59    /// Primal variable values, indexed by column (length equals `num_cols`).
60    pub primal: Vec<f64>,
61
62    /// Dual multipliers (shadow prices), indexed by row (length equals `num_rows`).
63    /// Normalized to canonical sign convention.
64    pub dual: Vec<f64>,
65
66    /// Reduced costs, indexed by column (length equals `num_cols`).
67    pub reduced_costs: Vec<f64>,
68
69    /// Number of simplex iterations performed for this solve.
70    pub iterations: u64,
71
72    /// Wall-clock solve time in seconds (excluding retry overhead).
73    pub solve_time_seconds: f64,
74}
75
76/// Zero-copy view of an LP solution, borrowing directly from solver-internal buffers.
77///
78/// Valid until the next mutating method call on the solver (any `&mut self` call).
79/// This is enforced at compile time by the Rust borrow checker: the lifetime `'a`
80/// ties the view to the solver instance that produced it.
81///
82/// Use [`SolutionView::to_owned`] to convert to an owned [`LpSolution`] when the
83/// solution data must outlive the current borrow, or when the same data will be
84/// accessed after a subsequent solver call.
85///
86/// See [Solver Interface Trait SS4.1](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md).
87#[derive(Debug, Clone, Copy)]
88pub struct SolutionView<'a> {
89    /// Optimal objective value (minimization sense).
90    pub objective: f64,
91
92    /// Primal variable values, indexed by column (length equals `num_cols`).
93    pub primal: &'a [f64],
94
95    /// Dual multipliers (shadow prices), indexed by row (length equals `num_rows`).
96    /// Normalized to canonical sign convention.
97    pub dual: &'a [f64],
98
99    /// Reduced costs, indexed by column (length equals `num_cols`).
100    pub reduced_costs: &'a [f64],
101
102    /// Number of simplex iterations performed for this solve.
103    pub iterations: u64,
104
105    /// Wall-clock solve time in seconds (excluding retry overhead).
106    pub solve_time_seconds: f64,
107}
108
109impl SolutionView<'_> {
110    /// Clones the borrowed slices into owned [`Vec`]s, producing an [`LpSolution`].
111    ///
112    /// Use this when the solution data must outlive the current solver borrow,
113    /// or when the same solution will be read after a subsequent solver call.
114    #[must_use]
115    pub fn to_owned(&self) -> LpSolution {
116        LpSolution {
117            objective: self.objective,
118            primal: self.primal.to_vec(),
119            dual: self.dual.to_vec(),
120            reduced_costs: self.reduced_costs.to_vec(),
121            iterations: self.iterations,
122            solve_time_seconds: self.solve_time_seconds,
123        }
124    }
125}
126
127/// Accumulated solve metrics for a single solver instance.
128///
129/// Counters grow monotonically from construction. They are thread-local --
130/// each thread owns one solver instance and accumulates its own statistics.
131/// Statistics are aggregated across threads via reduction after training
132/// completes.
133///
134/// `reset()` does **not** zero statistics counters. They persist across
135/// model reloads for the lifetime of the solver instance.
136///
137/// See [Solver Interface Trait SS4.3](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md).
138#[derive(Debug, Clone, Default)]
139pub struct SolverStatistics {
140    /// Total number of `solve` and `solve_with_basis` calls.
141    pub solve_count: u64,
142
143    /// Number of solves that returned `Ok` (optimal solution found).
144    pub success_count: u64,
145
146    /// Number of solves that returned `Err` (terminal failure after retries).
147    pub failure_count: u64,
148
149    /// Total simplex iterations summed across all solves.
150    pub total_iterations: u64,
151
152    /// Total retry attempts summed across all failed solves.
153    pub retry_count: u64,
154
155    /// Cumulative wall-clock time spent in solver calls, in seconds.
156    pub total_solve_time_seconds: f64,
157
158    /// Number of times `solve_with_basis` fell back to cold-start due to basis rejection.
159    pub basis_rejections: u64,
160
161    /// Number of solves that returned optimal on the first attempt (before any retry).
162    ///
163    /// Enables first-try rate computation: `first_try_rate = first_try_successes / solve_count`.
164    /// The complement `success_count - first_try_successes` gives the number of retried solves.
165    pub first_try_successes: u64,
166
167    /// Total number of `solve_with_basis` calls (basis offers).
168    ///
169    /// Combined with `basis_rejections`, enables basis hit rate computation:
170    /// `basis_hit_rate = 1 - basis_rejections / basis_offered`.
171    pub basis_offered: u64,
172
173    /// Total number of `load_model` calls.
174    pub load_model_count: u64,
175
176    /// Total number of `add_rows` calls.
177    pub add_rows_count: u64,
178
179    /// Cumulative wall-clock time spent in `load_model` calls, in seconds.
180    pub total_load_model_time_seconds: f64,
181
182    /// Cumulative wall-clock time spent in `add_rows` calls, in seconds.
183    pub total_add_rows_time_seconds: f64,
184
185    /// Cumulative wall-clock time spent in `set_row_bounds` and `set_col_bounds` calls, in seconds.
186    pub total_set_bounds_time_seconds: f64,
187}
188
189/// Pre-assembled structural LP for one stage, in CSC (column-major) form.
190///
191/// Built once at initialization from resolved internal structures.
192/// Shared read-only across all threads within an MPI rank.
193/// Passed to [`crate::SolverInterface::load_model`] to bulk-load the LP.
194///
195/// Column and row ordering follows the LP layout convention defined in
196/// [Solver Abstraction SS2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
197/// The calling algorithm crate owns construction of this type; `cobre-solver`
198/// treats it as an opaque data holder and does not interpret the LP structure.
199///
200/// See [Solver Interface Trait SS4.4](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md)
201/// and [Solver Abstraction SS11.1](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
202#[derive(Debug, Clone)]
203pub struct StageTemplate {
204    /// Number of columns (decision variables) in the structural LP.
205    pub num_cols: usize,
206
207    /// Number of static rows (structural constraints, excluding dynamic rows).
208    pub num_rows: usize,
209
210    /// Number of non-zero entries in the structural constraint matrix.
211    pub num_nz: usize,
212
213    /// CSC column start offsets (length: `num_cols + 1`; `col_starts[num_cols] == num_nz`).
214    pub col_starts: Vec<i32>,
215
216    /// CSC row indices for each non-zero entry (length: `num_nz`).
217    pub row_indices: Vec<i32>,
218
219    /// CSC non-zero values (length: `num_nz`).
220    pub values: Vec<f64>,
221
222    /// Column lower bounds (length: `num_cols`; use `f64::NEG_INFINITY` for unbounded).
223    pub col_lower: Vec<f64>,
224
225    /// Column upper bounds (length: `num_cols`; use `f64::INFINITY` for unbounded).
226    pub col_upper: Vec<f64>,
227
228    /// Objective coefficients, minimization sense (length: `num_cols`).
229    pub objective: Vec<f64>,
230
231    /// Row lower bounds (length: `num_rows`; set equal to `row_upper` for equality).
232    pub row_lower: Vec<f64>,
233
234    /// Row upper bounds (length: `num_rows`; set equal to `row_lower` for equality).
235    pub row_upper: Vec<f64>,
236
237    /// Number of state variables (contiguous prefix of columns).
238    pub n_state: usize,
239
240    /// Number of state values transferred between consecutive stages.
241    ///
242    /// Equal to `N * L` per
243    /// [Solver Abstraction SS2.1](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
244    /// This is the storage volumes plus all AR lags except the oldest
245    /// (which ages out of the lag window).
246    pub n_transfer: usize,
247
248    /// Number of dual-relevant constraint rows (contiguous prefix of rows).
249    ///
250    /// Equal to `N + N*L + n_fpha + n_gvc` per
251    /// [Solver Abstraction SS2.2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
252    /// For constant-productivity-only hydros (no FPHA), this equals `n_state`.
253    /// Extracting cut coefficients reads `dual[0..n_dual_relevant]`.
254    pub n_dual_relevant: usize,
255
256    /// Number of operating hydros at this stage.
257    pub n_hydro: usize,
258
259    /// Maximum PAR order across all operating hydros at this stage.
260    ///
261    /// Determines the uniform lag stride: all hydros store `max_par_order`
262    /// lag values regardless of their individual PAR order, enabling SIMD
263    /// vectorization with a single contiguous state stride.
264    pub max_par_order: usize,
265
266    /// Per-column scaling factors for numerical conditioning.
267    ///
268    /// When non-empty (length `num_cols`), the constraint matrix, objective
269    /// coefficients, and column bounds have been pre-scaled by these factors.
270    /// The calling algorithm is responsible for unscaling primal values after
271    /// each solve: `x_original[j] = col_scale[j] * x_scaled[j]`.
272    ///
273    /// When empty, no column scaling has been applied and solver results are
274    /// used directly.
275    pub col_scale: Vec<f64>,
276
277    /// Per-row scaling factors for numerical conditioning.
278    ///
279    /// When non-empty (length `num_rows`), the constraint matrix and row bounds
280    /// have been pre-scaled by these factors. The calling algorithm is responsible
281    /// for unscaling dual values after each solve:
282    /// `dual_original[i] = row_scale[i] * dual_scaled[i]`.
283    ///
284    /// When empty, no row scaling has been applied and solver results are
285    /// used directly.
286    pub row_scale: Vec<f64>,
287}
288
289/// Batch of constraint rows for addition to a loaded LP, in CSR (row-major) form.
290///
291/// Assembled from the cut pool activity bitmap before each LP rebuild
292/// and passed to [`crate::SolverInterface::add_rows`] for a single batch call.
293/// Cuts are appended at the bottom of the constraint matrix in the dynamic
294/// constraint region per
295/// [Solver Abstraction SS2.2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
296///
297/// See [Solver Interface Trait SS4.5](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md)
298/// and the cut pool assembly protocol in
299/// [Solver Abstraction SS5.4](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
300#[derive(Debug, Clone)]
301pub struct RowBatch {
302    /// Number of active constraint rows (cuts) in this batch.
303    pub num_rows: usize,
304
305    /// CSR row start offsets (`i32` for `HiGHS` FFI compatibility).
306    ///
307    /// Length: `num_rows + 1`. Entry `row_starts[i]` is the index into
308    /// `col_indices` and `values` where row `i` begins.
309    /// `row_starts[num_rows]` equals the total number of non-zeros.
310    pub row_starts: Vec<i32>,
311
312    /// CSR column indices for each non-zero entry (`i32` for `HiGHS` FFI compatibility).
313    ///
314    /// Length: total non-zeros across all rows. Entry `col_indices[k]` is the
315    /// column of the `k`-th non-zero value.
316    pub col_indices: Vec<i32>,
317
318    /// CSR non-zero values.
319    ///
320    /// Length: total non-zeros across all rows. Entry `values[k]` is the
321    /// coefficient at column `col_indices[k]` in its row.
322    pub values: Vec<f64>,
323
324    /// Row lower bounds (cut intercepts for cutting-plane cuts).
325    ///
326    /// Length: `num_rows`. For `>=` cuts, this is the RHS lower bound.
327    pub row_lower: Vec<f64>,
328
329    /// Row upper bounds.
330    ///
331    /// Length: `num_rows`. Use `f64::INFINITY` for `>=` cuts (cutting-plane cuts
332    /// have no finite upper bound).
333    pub row_upper: Vec<f64>,
334}
335
336impl RowBatch {
337    /// Reset all buffers to empty without deallocating.
338    ///
339    /// After `clear()`, `num_rows` is 0 and all `Vec` fields have length 0
340    /// but retain their allocated capacity for reuse.
341    pub fn clear(&mut self) {
342        self.num_rows = 0;
343        self.row_starts.clear();
344        self.col_indices.clear();
345        self.values.clear();
346        self.row_lower.clear();
347        self.row_upper.clear();
348    }
349}
350
351/// Terminal LP solve error returned after all retry attempts are exhausted.
352///
353/// The calling algorithm uses the variant to determine its response:
354/// hard stop (`Infeasible`, `Unbounded`, `InternalError`) or terminate
355/// with a diagnostic error (`NumericalDifficulty`, `TimeLimitExceeded`,
356/// `IterationLimit`).
357///
358/// The six variants correspond to the error categories defined in
359/// Solver Abstraction SS6. Solver-internal errors (e.g., factorization
360/// failures) are resolved by retry logic before reaching this level.
361#[derive(Debug)]
362pub enum SolverError {
363    /// The LP has no feasible solution.
364    ///
365    /// Indicates a data error (inconsistent bounds or constraints) or a
366    /// modeling error. The calling algorithm should perform a hard stop.
367    Infeasible,
368
369    /// The LP objective is unbounded below.
370    ///
371    /// Indicates a modeling error (missing bounds, incorrect objective sign).
372    /// The calling algorithm should perform a hard stop.
373    Unbounded,
374
375    /// Solver encountered numerical difficulties that persisted through all
376    /// retry attempts.
377    ///
378    /// The calling algorithm should log the error and perform a hard stop.
379    NumericalDifficulty {
380        /// Human-readable description of the numerical issue from the solver.
381        message: String,
382    },
383
384    /// Per-solve wall-clock time budget exhausted.
385    TimeLimitExceeded {
386        /// Elapsed wall-clock time in seconds at the point of termination.
387        elapsed_seconds: f64,
388    },
389
390    /// Solver simplex iteration limit reached.
391    IterationLimit {
392        /// Number of simplex iterations performed before the limit was hit.
393        iterations: u64,
394    },
395
396    /// Unrecoverable solver-internal failure.
397    ///
398    /// Covers FFI panics, memory allocation failures within the solver,
399    /// corrupted internal state, or any error not classifiable into the above
400    /// categories. The calling algorithm should log the error and perform a hard stop.
401    InternalError {
402        /// Human-readable error description.
403        message: String,
404        /// Solver-specific error code, if available.
405        error_code: Option<i32>,
406    },
407}
408
409impl fmt::Display for SolverError {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        match self {
412            Self::Infeasible => write!(f, "LP is infeasible"),
413            Self::Unbounded => write!(f, "LP is unbounded"),
414            Self::NumericalDifficulty { message } => {
415                write!(f, "numerical difficulty: {message}")
416            }
417            Self::TimeLimitExceeded { elapsed_seconds } => {
418                write!(f, "time limit exceeded after {elapsed_seconds:.3}s")
419            }
420            Self::IterationLimit { iterations } => {
421                write!(f, "iteration limit reached after {iterations} iterations")
422            }
423            Self::InternalError {
424                message,
425                error_code,
426            } => match error_code {
427                Some(code) => write!(f, "internal solver error (code {code}): {message}"),
428                None => write!(f, "internal solver error: {message}"),
429            },
430        }
431    }
432}
433
434impl std::error::Error for SolverError {}
435
436#[cfg(test)]
437mod tests {
438    use super::{Basis, RowBatch, SolutionView, SolverError, SolverStatistics, StageTemplate};
439
440    #[test]
441    fn test_basis_new_dimensions_and_zero_fill() {
442        let rb = Basis::new(3, 2);
443        assert_eq!(rb.col_status.len(), 3);
444        assert_eq!(rb.row_status.len(), 2);
445        assert!(rb.col_status.iter().all(|&v| v == 0_i32));
446        assert!(rb.row_status.iter().all(|&v| v == 0_i32));
447    }
448
449    #[test]
450    fn test_basis_new_empty() {
451        let rb = Basis::new(0, 0);
452        assert!(rb.col_status.is_empty());
453        assert!(rb.row_status.is_empty());
454    }
455
456    #[test]
457    fn test_basis_debug_and_clone() {
458        let rb = Basis::new(2, 1);
459        assert!(!format!("{rb:?}").is_empty());
460        let cloned = rb.clone();
461        assert_eq!(cloned.col_status, rb.col_status);
462        assert_eq!(cloned.row_status, rb.row_status);
463        let mut cloned2 = rb.clone();
464        cloned2.col_status[0] = 1_i32;
465        assert_eq!(rb.col_status[0], 0_i32);
466    }
467
468    #[test]
469    fn test_solver_error_display_infeasible() {
470        let msg = format!("{}", SolverError::Infeasible);
471        assert!(msg.contains("infeasible"));
472    }
473
474    #[test]
475    fn test_solver_error_display_all_variants() {
476        let variants = [
477            SolverError::Infeasible,
478            SolverError::Unbounded,
479            SolverError::NumericalDifficulty {
480                message: "factorization failed".to_string(),
481            },
482            SolverError::TimeLimitExceeded {
483                elapsed_seconds: 60.0,
484            },
485            SolverError::IterationLimit { iterations: 10_000 },
486            SolverError::InternalError {
487                message: "segfault in HiGHS".to_string(),
488                error_code: Some(-1),
489            },
490        ];
491
492        let messages: Vec<String> = variants.iter().map(|err| format!("{err}")).collect();
493        for i in 0..messages.len() {
494            for j in (i + 1)..messages.len() {
495                assert_ne!(messages[i], messages[j]);
496            }
497        }
498    }
499
500    #[test]
501    fn test_solver_error_is_std_error() {
502        let err = SolverError::InternalError {
503            message: "test".to_string(),
504            error_code: None,
505        };
506        let _: &dyn std::error::Error = &err;
507    }
508
509    #[test]
510    fn test_solver_statistics_default_all_zero() {
511        let stats = SolverStatistics::default();
512        assert_eq!(stats.solve_count, 0);
513        assert_eq!(stats.success_count, 0);
514        assert_eq!(stats.failure_count, 0);
515        assert_eq!(stats.total_iterations, 0);
516        assert_eq!(stats.retry_count, 0);
517        assert_eq!(stats.total_solve_time_seconds, 0.0);
518        assert_eq!(stats.basis_rejections, 0);
519        assert_eq!(stats.first_try_successes, 0);
520        assert_eq!(stats.basis_offered, 0);
521        assert_eq!(stats.total_load_model_time_seconds, 0.0);
522        assert_eq!(stats.total_add_rows_time_seconds, 0.0);
523        assert_eq!(stats.total_set_bounds_time_seconds, 0.0);
524    }
525
526    fn make_fixture_stage_template() -> StageTemplate {
527        StageTemplate {
528            num_cols: 3,
529            num_rows: 2,
530            num_nz: 3,
531            col_starts: vec![0_i32, 2, 2, 3],
532            row_indices: vec![0_i32, 1, 1],
533            values: vec![1.0, 2.0, 1.0],
534            col_lower: vec![0.0, 0.0, 0.0],
535            col_upper: vec![10.0, f64::INFINITY, 8.0],
536            objective: vec![0.0, 1.0, 50.0],
537            row_lower: vec![6.0, 14.0],
538            row_upper: vec![6.0, 14.0],
539            n_state: 1,
540            n_transfer: 0,
541            n_dual_relevant: 1,
542            n_hydro: 1,
543            max_par_order: 0,
544            col_scale: Vec::new(),
545            row_scale: Vec::new(),
546        }
547    }
548
549    #[test]
550    fn test_stage_template_construction() {
551        let tmpl = make_fixture_stage_template();
552
553        assert_eq!(tmpl.num_cols, 3);
554        assert_eq!(tmpl.num_rows, 2);
555        assert_eq!(tmpl.num_nz, 3);
556        assert_eq!(tmpl.col_starts, vec![0_i32, 2, 2, 3]);
557        assert_eq!(tmpl.row_indices, vec![0_i32, 1, 1]);
558        assert_eq!(tmpl.values, vec![1.0, 2.0, 1.0]);
559
560        assert_eq!(tmpl.col_lower, vec![0.0, 0.0, 0.0]);
561        assert_eq!(tmpl.col_upper[0], 10.0);
562        assert!(tmpl.col_upper[1].is_infinite() && tmpl.col_upper[1] > 0.0);
563        assert_eq!(tmpl.col_upper[2], 8.0);
564
565        assert_eq!(tmpl.objective, vec![0.0, 1.0, 50.0]);
566        assert_eq!(tmpl.row_lower, vec![6.0, 14.0]);
567        assert_eq!(tmpl.row_upper, vec![6.0, 14.0]);
568
569        assert_eq!(tmpl.n_state, 1);
570        assert_eq!(tmpl.n_transfer, 0);
571        assert_eq!(tmpl.n_dual_relevant, 1);
572        assert_eq!(tmpl.n_hydro, 1);
573        assert_eq!(tmpl.max_par_order, 0);
574    }
575
576    #[test]
577    fn test_solver_error_display_all_branches() {
578        let cases = vec![
579            ("Infeasible", SolverError::Infeasible, "infeasible"),
580            ("Unbounded", SolverError::Unbounded, "unbounded"),
581            (
582                "NumericalDifficulty",
583                SolverError::NumericalDifficulty {
584                    message: "singular matrix".to_string(),
585                },
586                "singular matrix",
587            ),
588            (
589                "TimeLimitExceeded",
590                SolverError::TimeLimitExceeded {
591                    elapsed_seconds: 60.0,
592                },
593                "60.000s",
594            ),
595            (
596                "IterationLimit",
597                SolverError::IterationLimit { iterations: 10_000 },
598                "10000 iterations",
599            ),
600            (
601                "InternalError/None",
602                SolverError::InternalError {
603                    message: "unknown failure".to_string(),
604                    error_code: None,
605                },
606                "unknown failure",
607            ),
608            (
609                "InternalError/Some",
610                SolverError::InternalError {
611                    message: "segfault in HiGHS".to_string(),
612                    error_code: Some(-1),
613                },
614                "code -1",
615            ),
616        ];
617
618        for (name, err, expected_text) in cases {
619            let msg = format!("{err}");
620            assert!(!msg.is_empty());
621            assert!(
622                msg.contains(expected_text),
623                "{name} missing '{expected_text}'"
624            );
625        }
626    }
627
628    #[test]
629    fn test_solver_error_is_std_error_all_variants() {
630        let errors: Vec<SolverError> = vec![
631            SolverError::Infeasible,
632            SolverError::Unbounded,
633            SolverError::NumericalDifficulty {
634                message: "test".to_string(),
635            },
636            SolverError::TimeLimitExceeded {
637                elapsed_seconds: 1.0,
638            },
639            SolverError::IterationLimit { iterations: 1 },
640            SolverError::InternalError {
641                message: "test".to_string(),
642                error_code: None,
643            },
644            SolverError::InternalError {
645                message: "test".to_string(),
646                error_code: Some(-1),
647            },
648        ];
649
650        for err in &errors {
651            let _: &dyn std::error::Error = err;
652        }
653    }
654
655    #[test]
656    fn test_solution_view_to_owned() {
657        let primal = [1.0, 2.0];
658        let dual = [3.0];
659        let rc = [4.0, 5.0];
660        let view = SolutionView {
661            objective: 42.0,
662            primal: &primal,
663            dual: &dual,
664            reduced_costs: &rc,
665            iterations: 7,
666            solve_time_seconds: 0.5,
667        };
668        let owned = view.to_owned();
669        assert_eq!(owned.objective, 42.0);
670        assert_eq!(owned.primal, vec![1.0, 2.0]);
671        assert_eq!(owned.dual, vec![3.0]);
672        assert_eq!(owned.reduced_costs, vec![4.0, 5.0]);
673        assert_eq!(owned.iterations, 7);
674        assert_eq!(owned.solve_time_seconds, 0.5);
675    }
676
677    #[test]
678    fn test_solution_view_is_copy() {
679        let primal = [1.0];
680        let dual = [2.0];
681        let rc = [3.0];
682        let view = SolutionView {
683            objective: 0.0,
684            primal: &primal,
685            dual: &dual,
686            reduced_costs: &rc,
687            iterations: 0,
688            solve_time_seconds: 0.0,
689        };
690        let copy = view;
691        assert_eq!(view.objective, copy.objective);
692    }
693
694    #[test]
695    fn test_row_batch_construction() {
696        let batch = RowBatch {
697            num_rows: 2,
698            row_starts: vec![0_i32, 2, 4],
699            col_indices: vec![0_i32, 1, 0, 1],
700            values: vec![-5.0, 1.0, 3.0, 1.0],
701            row_lower: vec![20.0, 80.0],
702            row_upper: vec![f64::INFINITY, f64::INFINITY],
703        };
704
705        assert_eq!(batch.num_rows, 2);
706        assert_eq!(batch.row_starts.len(), 3);
707        assert_eq!(batch.row_starts, vec![0_i32, 2, 4]);
708        assert_eq!(batch.col_indices, vec![0_i32, 1, 0, 1]);
709        assert_eq!(batch.values, vec![-5.0, 1.0, 3.0, 1.0]);
710        assert_eq!(batch.row_lower, vec![20.0, 80.0]);
711        assert!(batch.row_upper[0].is_infinite() && batch.row_upper[0] > 0.0);
712        assert!(batch.row_upper[1].is_infinite() && batch.row_upper[1] > 0.0);
713    }
714}