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    /// Cumulative wall-clock time spent in `set_basis` FFI calls, in seconds.
189    ///
190    /// Accumulated by `solve_with_basis` around the basis installation step.
191    /// `solve()` (without basis) does not increment this counter.
192    pub total_basis_set_time_seconds: f64,
193}
194
195/// Pre-assembled structural LP for one stage, in CSC (column-major) form.
196///
197/// Built once at initialization from resolved internal structures.
198/// Shared read-only across all threads within an MPI rank.
199/// Passed to [`crate::SolverInterface::load_model`] to bulk-load the LP.
200///
201/// Column and row ordering follows the LP layout convention defined in
202/// [Solver Abstraction SS2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
203/// The calling algorithm crate owns construction of this type; `cobre-solver`
204/// treats it as an opaque data holder and does not interpret the LP structure.
205///
206/// See [Solver Interface Trait SS4.4](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md)
207/// and [Solver Abstraction SS11.1](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
208#[derive(Debug, Clone)]
209pub struct StageTemplate {
210    /// Number of columns (decision variables) in the structural LP.
211    pub num_cols: usize,
212
213    /// Number of static rows (structural constraints, excluding dynamic rows).
214    pub num_rows: usize,
215
216    /// Number of non-zero entries in the structural constraint matrix.
217    pub num_nz: usize,
218
219    /// CSC column start offsets (length: `num_cols + 1`; `col_starts[num_cols] == num_nz`).
220    pub col_starts: Vec<i32>,
221
222    /// CSC row indices for each non-zero entry (length: `num_nz`).
223    pub row_indices: Vec<i32>,
224
225    /// CSC non-zero values (length: `num_nz`).
226    pub values: Vec<f64>,
227
228    /// Column lower bounds (length: `num_cols`; use `f64::NEG_INFINITY` for unbounded).
229    pub col_lower: Vec<f64>,
230
231    /// Column upper bounds (length: `num_cols`; use `f64::INFINITY` for unbounded).
232    pub col_upper: Vec<f64>,
233
234    /// Objective coefficients, minimization sense (length: `num_cols`).
235    pub objective: Vec<f64>,
236
237    /// Row lower bounds (length: `num_rows`; set equal to `row_upper` for equality).
238    pub row_lower: Vec<f64>,
239
240    /// Row upper bounds (length: `num_rows`; set equal to `row_lower` for equality).
241    pub row_upper: Vec<f64>,
242
243    /// Number of state variables (contiguous prefix of columns).
244    pub n_state: usize,
245
246    /// Number of state values transferred between consecutive stages.
247    ///
248    /// Equal to `N * L` per
249    /// [Solver Abstraction SS2.1](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
250    /// This is the storage volumes plus all AR lags except the oldest
251    /// (which ages out of the lag window).
252    pub n_transfer: usize,
253
254    /// Number of dual-relevant constraint rows (contiguous prefix of rows).
255    ///
256    /// Equal to `N + N*L + n_fpha + n_gvc` per
257    /// [Solver Abstraction SS2.2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
258    /// For constant-productivity-only hydros (no FPHA), this equals `n_state`.
259    /// Extracting cut coefficients reads `dual[0..n_dual_relevant]`.
260    pub n_dual_relevant: usize,
261
262    /// Number of operating hydros at this stage.
263    pub n_hydro: usize,
264
265    /// Maximum PAR order across all operating hydros at this stage.
266    ///
267    /// Determines the uniform lag stride: all hydros store `max_par_order`
268    /// lag values regardless of their individual PAR order, enabling SIMD
269    /// vectorization with a single contiguous state stride.
270    pub max_par_order: usize,
271
272    /// Per-column scaling factors for numerical conditioning.
273    ///
274    /// When non-empty (length `num_cols`), the constraint matrix, objective
275    /// coefficients, and column bounds have been pre-scaled by these factors.
276    /// The calling algorithm is responsible for unscaling primal values after
277    /// each solve: `x_original[j] = col_scale[j] * x_scaled[j]`.
278    ///
279    /// When empty, no column scaling has been applied and solver results are
280    /// used directly.
281    pub col_scale: Vec<f64>,
282
283    /// Per-row scaling factors for numerical conditioning.
284    ///
285    /// When non-empty (length `num_rows`), the constraint matrix and row bounds
286    /// have been pre-scaled by these factors. The calling algorithm is responsible
287    /// for unscaling dual values after each solve:
288    /// `dual_original[i] = row_scale[i] * dual_scaled[i]`.
289    ///
290    /// When empty, no row scaling has been applied and solver results are
291    /// used directly.
292    pub row_scale: Vec<f64>,
293}
294
295/// Batch of constraint rows for addition to a loaded LP, in CSR (row-major) form.
296///
297/// Assembled from the cut pool activity bitmap before each LP rebuild
298/// and passed to [`crate::SolverInterface::add_rows`] for a single batch call.
299/// Cuts are appended at the bottom of the constraint matrix in the dynamic
300/// constraint region per
301/// [Solver Abstraction SS2.2](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
302///
303/// See [Solver Interface Trait SS4.5](../../../cobre-docs/src/specs/architecture/solver-interface-trait.md)
304/// and the cut pool assembly protocol in
305/// [Solver Abstraction SS5.4](../../../cobre-docs/src/specs/architecture/solver-abstraction.md).
306#[derive(Debug, Clone)]
307pub struct RowBatch {
308    /// Number of active constraint rows (cuts) in this batch.
309    pub num_rows: usize,
310
311    /// CSR row start offsets (`i32` for `HiGHS` FFI compatibility).
312    ///
313    /// Length: `num_rows + 1`. Entry `row_starts[i]` is the index into
314    /// `col_indices` and `values` where row `i` begins.
315    /// `row_starts[num_rows]` equals the total number of non-zeros.
316    pub row_starts: Vec<i32>,
317
318    /// CSR column indices for each non-zero entry (`i32` for `HiGHS` FFI compatibility).
319    ///
320    /// Length: total non-zeros across all rows. Entry `col_indices[k]` is the
321    /// column of the `k`-th non-zero value.
322    pub col_indices: Vec<i32>,
323
324    /// CSR non-zero values.
325    ///
326    /// Length: total non-zeros across all rows. Entry `values[k]` is the
327    /// coefficient at column `col_indices[k]` in its row.
328    pub values: Vec<f64>,
329
330    /// Row lower bounds (cut intercepts for cutting-plane cuts).
331    ///
332    /// Length: `num_rows`. For `>=` cuts, this is the RHS lower bound.
333    pub row_lower: Vec<f64>,
334
335    /// Row upper bounds.
336    ///
337    /// Length: `num_rows`. Use `f64::INFINITY` for `>=` cuts (cutting-plane cuts
338    /// have no finite upper bound).
339    pub row_upper: Vec<f64>,
340}
341
342impl RowBatch {
343    /// Reset all buffers to empty without deallocating.
344    ///
345    /// After `clear()`, `num_rows` is 0 and all `Vec` fields have length 0
346    /// but retain their allocated capacity for reuse.
347    pub fn clear(&mut self) {
348        self.num_rows = 0;
349        self.row_starts.clear();
350        self.col_indices.clear();
351        self.values.clear();
352        self.row_lower.clear();
353        self.row_upper.clear();
354    }
355}
356
357/// Terminal LP solve error returned after all retry attempts are exhausted.
358///
359/// The calling algorithm uses the variant to determine its response:
360/// hard stop (`Infeasible`, `Unbounded`, `InternalError`) or terminate
361/// with a diagnostic error (`NumericalDifficulty`, `TimeLimitExceeded`,
362/// `IterationLimit`).
363///
364/// The six variants correspond to the error categories defined in
365/// Solver Abstraction SS6. Solver-internal errors (e.g., factorization
366/// failures) are resolved by retry logic before reaching this level.
367#[derive(Debug)]
368pub enum SolverError {
369    /// The LP has no feasible solution.
370    ///
371    /// Indicates a data error (inconsistent bounds or constraints) or a
372    /// modeling error. The calling algorithm should perform a hard stop.
373    Infeasible,
374
375    /// The LP objective is unbounded below.
376    ///
377    /// Indicates a modeling error (missing bounds, incorrect objective sign).
378    /// The calling algorithm should perform a hard stop.
379    Unbounded,
380
381    /// Solver encountered numerical difficulties that persisted through all
382    /// retry attempts.
383    ///
384    /// The calling algorithm should log the error and perform a hard stop.
385    NumericalDifficulty {
386        /// Human-readable description of the numerical issue from the solver.
387        message: String,
388    },
389
390    /// Per-solve wall-clock time budget exhausted.
391    TimeLimitExceeded {
392        /// Elapsed wall-clock time in seconds at the point of termination.
393        elapsed_seconds: f64,
394    },
395
396    /// Solver simplex iteration limit reached.
397    IterationLimit {
398        /// Number of simplex iterations performed before the limit was hit.
399        iterations: u64,
400    },
401
402    /// Unrecoverable solver-internal failure.
403    ///
404    /// Covers FFI panics, memory allocation failures within the solver,
405    /// corrupted internal state, or any error not classifiable into the above
406    /// categories. The calling algorithm should log the error and perform a hard stop.
407    InternalError {
408        /// Human-readable error description.
409        message: String,
410        /// Solver-specific error code, if available.
411        error_code: Option<i32>,
412    },
413}
414
415impl fmt::Display for SolverError {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        match self {
418            Self::Infeasible => write!(f, "LP is infeasible"),
419            Self::Unbounded => write!(f, "LP is unbounded"),
420            Self::NumericalDifficulty { message } => {
421                write!(f, "numerical difficulty: {message}")
422            }
423            Self::TimeLimitExceeded { elapsed_seconds } => {
424                write!(f, "time limit exceeded after {elapsed_seconds:.3}s")
425            }
426            Self::IterationLimit { iterations } => {
427                write!(f, "iteration limit reached after {iterations} iterations")
428            }
429            Self::InternalError {
430                message,
431                error_code,
432            } => match error_code {
433                Some(code) => write!(f, "internal solver error (code {code}): {message}"),
434                None => write!(f, "internal solver error: {message}"),
435            },
436        }
437    }
438}
439
440impl std::error::Error for SolverError {}
441
442#[cfg(test)]
443mod tests {
444    use super::{Basis, RowBatch, SolutionView, SolverError, SolverStatistics, StageTemplate};
445
446    #[test]
447    fn test_basis_new_dimensions_and_zero_fill() {
448        let rb = Basis::new(3, 2);
449        assert_eq!(rb.col_status.len(), 3);
450        assert_eq!(rb.row_status.len(), 2);
451        assert!(rb.col_status.iter().all(|&v| v == 0_i32));
452        assert!(rb.row_status.iter().all(|&v| v == 0_i32));
453    }
454
455    #[test]
456    fn test_basis_new_empty() {
457        let rb = Basis::new(0, 0);
458        assert!(rb.col_status.is_empty());
459        assert!(rb.row_status.is_empty());
460    }
461
462    #[test]
463    fn test_basis_debug_and_clone() {
464        let rb = Basis::new(2, 1);
465        assert!(!format!("{rb:?}").is_empty());
466        let cloned = rb.clone();
467        assert_eq!(cloned.col_status, rb.col_status);
468        assert_eq!(cloned.row_status, rb.row_status);
469        let mut cloned2 = rb.clone();
470        cloned2.col_status[0] = 1_i32;
471        assert_eq!(rb.col_status[0], 0_i32);
472    }
473
474    #[test]
475    fn test_solver_error_display_infeasible() {
476        let msg = format!("{}", SolverError::Infeasible);
477        assert!(msg.contains("infeasible"));
478    }
479
480    #[test]
481    fn test_solver_error_display_all_variants() {
482        let variants = [
483            SolverError::Infeasible,
484            SolverError::Unbounded,
485            SolverError::NumericalDifficulty {
486                message: "factorization failed".to_string(),
487            },
488            SolverError::TimeLimitExceeded {
489                elapsed_seconds: 60.0,
490            },
491            SolverError::IterationLimit { iterations: 10_000 },
492            SolverError::InternalError {
493                message: "segfault in HiGHS".to_string(),
494                error_code: Some(-1),
495            },
496        ];
497
498        let messages: Vec<String> = variants.iter().map(|err| format!("{err}")).collect();
499        for i in 0..messages.len() {
500            for j in (i + 1)..messages.len() {
501                assert_ne!(messages[i], messages[j]);
502            }
503        }
504    }
505
506    #[test]
507    fn test_solver_error_is_std_error() {
508        let err = SolverError::InternalError {
509            message: "test".to_string(),
510            error_code: None,
511        };
512        let _: &dyn std::error::Error = &err;
513    }
514
515    #[test]
516    fn test_solver_statistics_default_all_zero() {
517        let stats = SolverStatistics::default();
518        assert_eq!(stats.solve_count, 0);
519        assert_eq!(stats.success_count, 0);
520        assert_eq!(stats.failure_count, 0);
521        assert_eq!(stats.total_iterations, 0);
522        assert_eq!(stats.retry_count, 0);
523        assert_eq!(stats.total_solve_time_seconds, 0.0);
524        assert_eq!(stats.basis_rejections, 0);
525        assert_eq!(stats.first_try_successes, 0);
526        assert_eq!(stats.basis_offered, 0);
527        assert_eq!(stats.total_load_model_time_seconds, 0.0);
528        assert_eq!(stats.total_add_rows_time_seconds, 0.0);
529        assert_eq!(stats.total_set_bounds_time_seconds, 0.0);
530    }
531
532    fn make_fixture_stage_template() -> StageTemplate {
533        StageTemplate {
534            num_cols: 3,
535            num_rows: 2,
536            num_nz: 3,
537            col_starts: vec![0_i32, 2, 2, 3],
538            row_indices: vec![0_i32, 1, 1],
539            values: vec![1.0, 2.0, 1.0],
540            col_lower: vec![0.0, 0.0, 0.0],
541            col_upper: vec![10.0, f64::INFINITY, 8.0],
542            objective: vec![0.0, 1.0, 50.0],
543            row_lower: vec![6.0, 14.0],
544            row_upper: vec![6.0, 14.0],
545            n_state: 1,
546            n_transfer: 0,
547            n_dual_relevant: 1,
548            n_hydro: 1,
549            max_par_order: 0,
550            col_scale: Vec::new(),
551            row_scale: Vec::new(),
552        }
553    }
554
555    #[test]
556    fn test_stage_template_construction() {
557        let tmpl = make_fixture_stage_template();
558
559        assert_eq!(tmpl.num_cols, 3);
560        assert_eq!(tmpl.num_rows, 2);
561        assert_eq!(tmpl.num_nz, 3);
562        assert_eq!(tmpl.col_starts, vec![0_i32, 2, 2, 3]);
563        assert_eq!(tmpl.row_indices, vec![0_i32, 1, 1]);
564        assert_eq!(tmpl.values, vec![1.0, 2.0, 1.0]);
565
566        assert_eq!(tmpl.col_lower, vec![0.0, 0.0, 0.0]);
567        assert_eq!(tmpl.col_upper[0], 10.0);
568        assert!(tmpl.col_upper[1].is_infinite() && tmpl.col_upper[1] > 0.0);
569        assert_eq!(tmpl.col_upper[2], 8.0);
570
571        assert_eq!(tmpl.objective, vec![0.0, 1.0, 50.0]);
572        assert_eq!(tmpl.row_lower, vec![6.0, 14.0]);
573        assert_eq!(tmpl.row_upper, vec![6.0, 14.0]);
574
575        assert_eq!(tmpl.n_state, 1);
576        assert_eq!(tmpl.n_transfer, 0);
577        assert_eq!(tmpl.n_dual_relevant, 1);
578        assert_eq!(tmpl.n_hydro, 1);
579        assert_eq!(tmpl.max_par_order, 0);
580    }
581
582    #[test]
583    fn test_solver_error_display_all_branches() {
584        let cases = vec![
585            ("Infeasible", SolverError::Infeasible, "infeasible"),
586            ("Unbounded", SolverError::Unbounded, "unbounded"),
587            (
588                "NumericalDifficulty",
589                SolverError::NumericalDifficulty {
590                    message: "singular matrix".to_string(),
591                },
592                "singular matrix",
593            ),
594            (
595                "TimeLimitExceeded",
596                SolverError::TimeLimitExceeded {
597                    elapsed_seconds: 60.0,
598                },
599                "60.000s",
600            ),
601            (
602                "IterationLimit",
603                SolverError::IterationLimit { iterations: 10_000 },
604                "10000 iterations",
605            ),
606            (
607                "InternalError/None",
608                SolverError::InternalError {
609                    message: "unknown failure".to_string(),
610                    error_code: None,
611                },
612                "unknown failure",
613            ),
614            (
615                "InternalError/Some",
616                SolverError::InternalError {
617                    message: "segfault in HiGHS".to_string(),
618                    error_code: Some(-1),
619                },
620                "code -1",
621            ),
622        ];
623
624        for (name, err, expected_text) in cases {
625            let msg = format!("{err}");
626            assert!(!msg.is_empty());
627            assert!(
628                msg.contains(expected_text),
629                "{name} missing '{expected_text}'"
630            );
631        }
632    }
633
634    #[test]
635    fn test_solver_error_is_std_error_all_variants() {
636        let errors: Vec<SolverError> = vec![
637            SolverError::Infeasible,
638            SolverError::Unbounded,
639            SolverError::NumericalDifficulty {
640                message: "test".to_string(),
641            },
642            SolverError::TimeLimitExceeded {
643                elapsed_seconds: 1.0,
644            },
645            SolverError::IterationLimit { iterations: 1 },
646            SolverError::InternalError {
647                message: "test".to_string(),
648                error_code: None,
649            },
650            SolverError::InternalError {
651                message: "test".to_string(),
652                error_code: Some(-1),
653            },
654        ];
655
656        for err in &errors {
657            let _: &dyn std::error::Error = err;
658        }
659    }
660
661    #[test]
662    fn test_solution_view_to_owned() {
663        let primal = [1.0, 2.0];
664        let dual = [3.0];
665        let rc = [4.0, 5.0];
666        let view = SolutionView {
667            objective: 42.0,
668            primal: &primal,
669            dual: &dual,
670            reduced_costs: &rc,
671            iterations: 7,
672            solve_time_seconds: 0.5,
673        };
674        let owned = view.to_owned();
675        assert_eq!(owned.objective, 42.0);
676        assert_eq!(owned.primal, vec![1.0, 2.0]);
677        assert_eq!(owned.dual, vec![3.0]);
678        assert_eq!(owned.reduced_costs, vec![4.0, 5.0]);
679        assert_eq!(owned.iterations, 7);
680        assert_eq!(owned.solve_time_seconds, 0.5);
681    }
682
683    #[test]
684    fn test_solution_view_is_copy() {
685        let primal = [1.0];
686        let dual = [2.0];
687        let rc = [3.0];
688        let view = SolutionView {
689            objective: 0.0,
690            primal: &primal,
691            dual: &dual,
692            reduced_costs: &rc,
693            iterations: 0,
694            solve_time_seconds: 0.0,
695        };
696        let copy = view;
697        assert_eq!(view.objective, copy.objective);
698    }
699
700    #[test]
701    fn test_row_batch_construction() {
702        let batch = RowBatch {
703            num_rows: 2,
704            row_starts: vec![0_i32, 2, 4],
705            col_indices: vec![0_i32, 1, 0, 1],
706            values: vec![-5.0, 1.0, 3.0, 1.0],
707            row_lower: vec![20.0, 80.0],
708            row_upper: vec![f64::INFINITY, f64::INFINITY],
709        };
710
711        assert_eq!(batch.num_rows, 2);
712        assert_eq!(batch.row_starts.len(), 3);
713        assert_eq!(batch.row_starts, vec![0_i32, 2, 4]);
714        assert_eq!(batch.col_indices, vec![0_i32, 1, 0, 1]);
715        assert_eq!(batch.values, vec![-5.0, 1.0, 3.0, 1.0]);
716        assert_eq!(batch.row_lower, vec![20.0, 80.0]);
717        assert!(batch.row_upper[0].is_infinite() && batch.row_upper[0] > 0.0);
718        assert!(batch.row_upper[1].is_infinite() && batch.row_upper[1] > 0.0);
719    }
720}