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