maryada 0.2.0

No-std binary64 real interval arithmetic conforming to IEEE 1788.1
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
//! Matrix and vector storage types used by linear-algebra operations.
//!
//! Fixed-size types are available with the `linalg` feature. Dynamically sized
//! types additionally require the `alloc` feature.
//!
//! The majority of the algorithmic work here was written by following the thesis of Jaroslav Horáček (see reference).
//!
//! # References
//!
//! J. Horáček, *Interval Linear and Nonlinear Systems*, Ph.D. thesis, Charles University, 2019. [https://dspace.cuni.cz/handle/20.500.11956/111301](https://dspace.cuni.cz/handle/20.500.11956/111301)

use core::{
    fmt,
    fmt::Write as _,
    ops::{Index, IndexMut, Mul},
};

use nalgebra::{
    ArrayStorage, Const, DefaultAllocator, Dim, DimMin, Matrix, OMatrix, OVector, Scalar, Storage,
    StorageMut,
    allocator::{Allocator, SameShapeAllocator, SameShapeC, SameShapeR},
    constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint},
    iter::{ColumnIter, ColumnIterMut, MatrixIter, MatrixIterMut, RowIter, RowIterMut},
    storage::Owned,
};

#[cfg(feature = "alloc")]
use nalgebra::{Dyn, VecStorage};

use crate::{
    IntervalOps,
    rounding::{self, Direction},
};

/// A nalgebra matrix whose entries are real intervals.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IntervalMatrix<T, R, C, S>(Matrix<T, R, C, S>)
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>;

/// An owned interval matrix with allocator-selected storage.
pub type OIntervalMatrix<T, R, C> = IntervalMatrix<T, R, C, Owned<T, R, C>>;
/// An owned interval column vector with allocator-selected storage.
pub type OIntervalVector<T, D> = OIntervalMatrix<T, D, Const<1>>;
/// An owned interval row vector with allocator-selected storage.
pub type OIntervalRowVector<T, D> = OIntervalMatrix<T, Const<1>, D>;
/// A statically sized interval matrix.
pub type SIntervalMatrix<T, const R: usize, const C: usize> =
    IntervalMatrix<T, Const<R>, Const<C>, ArrayStorage<T, R, C>>;
/// A statically sized interval column vector.
pub type SIntervalVector<T, const D: usize> = SIntervalMatrix<T, D, 1>;
/// A statically sized interval row vector.
pub type SIntervalRowVector<T, const D: usize> = SIntervalMatrix<T, 1, D>;

/// A dynamically sized interval matrix.
#[cfg(feature = "alloc")]
pub type DIntervalMatrix<T> = IntervalMatrix<T, Dyn, Dyn, VecStorage<T, Dyn, Dyn>>;
/// A dynamically sized interval column vector.
#[cfg(feature = "alloc")]
pub type DIntervalVector<T> = IntervalMatrix<T, Dyn, Const<1>, VecStorage<T, Dyn, Const<1>>>;
/// A dynamically sized interval row vector.
#[cfg(feature = "alloc")]
pub type DIntervalRowVector<T> = IntervalMatrix<T, Const<1>, Dyn, VecStorage<T, Const<1>, Dyn>>;

impl<T, R, C, S> IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    /// Wraps a nalgebra matrix whose scalar type is an interval type.
    pub const fn from_inner(inner: Matrix<T, R, C, S>) -> Self {
        Self(inner)
    }

    /// Borrows the underlying nalgebra matrix.
    pub const fn as_inner(&self) -> &Matrix<T, R, C, S> {
        &self.0
    }

    /// Unwraps this value into its underlying nalgebra matrix.
    pub fn into_inner(self) -> Matrix<T, R, C, S> {
        self.0
    }

    /// Returns the number of rows and columns.
    pub fn shape(&self) -> (usize, usize) {
        self.0.shape()
    }

    /// Returns the row and column dimensions at the type level.
    pub fn shape_generic(&self) -> (R, C) {
        self.0.shape_generic()
    }

    /// Returns the number of rows.
    pub fn nrows(&self) -> usize {
        self.0.nrows()
    }

    /// Returns the number of columns.
    pub fn ncols(&self) -> usize {
        self.0.ncols()
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether this matrix has no entries.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns whether this matrix has the same number of rows and columns.
    pub fn is_square(&self) -> bool {
        self.0.is_square()
    }

    /// Returns an entry, or `None` if the row or column is out of bounds.
    pub fn get(&self, row: usize, column: usize) -> Option<&T> {
        self.0.get((row, column))
    }

    /// Iterates over entries in column-major order.
    pub fn iter(&self) -> MatrixIter<'_, T, R, C, S> {
        self.0.iter()
    }

    /// Iterates over rows.
    pub const fn row_iter(&self) -> RowIter<'_, T, R, C, S> {
        self.0.row_iter()
    }

    /// Iterates over columns.
    pub fn column_iter(&self) -> ColumnIter<'_, T, R, C, S> {
        self.0.column_iter()
    }
}

struct CharCounter(usize);

impl fmt::Write for CharCounter {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        self.0 = self.0.saturating_add(text.chars().count());
        Ok(())
    }
}

macro_rules! impl_matrix_format {
    ($trait:path, $without_precision:literal, $with_precision:literal) => {
        impl<T, R, C, S> $trait for IntervalMatrix<T, R, C, S>
        where
            T: IntervalOps + Scalar + $trait,
            R: Dim,
            C: Dim,
            S: Storage<T, R, C>,
        {
            #[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                fn value_width<T: $trait>(
                    value: &T,
                    precision: Option<usize>,
                ) -> Result<usize, fmt::Error> {
                    let mut counter = CharCounter(0);
                    match precision {
                        Some(precision) => {
                            write!(&mut counter, $with_precision, value, precision)?;
                        }
                        None => {
                            write!(&mut counter, $without_precision, value)?;
                        }
                    }
                    Ok(counter.0)
                }

                let (rows, columns) = self.shape();
                if rows == 0 || columns == 0 {
                    return formatter.write_str("[ ]");
                }

                let precision = formatter.precision();
                let mut element_width = 0;
                for row in 0..rows {
                    for column in 0..columns {
                        element_width =
                            element_width.max(value_width(&self[(row, column)], precision)?);
                    }
                }
                let cell_width = element_width + 1;
                let interior_width = cell_width * columns - 1;

                writeln!(formatter)?;
                writeln!(formatter, "  ┌ {:>interior_width$} ┐", "")?;
                for row in 0..rows {
                    formatter.write_str("")?;
                    for column in 0..columns {
                        let value = &self[(row, column)];
                        let padding = element_width - value_width(value, precision)?;
                        write!(formatter, " {:padding$}", "")?;
                        match precision {
                            Some(precision) => {
                                write!(formatter, $with_precision, value, precision)?;
                            }
                            None => write!(formatter, $without_precision, value)?,
                        }
                    }
                    writeln!(formatter, "")?;
                }
                writeln!(formatter, "  └ {:>interior_width$} ┘", "")?;
                writeln!(formatter)
            }
        }
    };
}

impl_matrix_format!(fmt::Display, "{}", "{:.1$}");
impl_matrix_format!(fmt::LowerExp, "{:e}", "{:.1$e}");
impl_matrix_format!(fmt::UpperExp, "{:E}", "{:.1$E}");
impl_matrix_format!(fmt::LowerHex, "{:x}", "{:.1$x}");
impl_matrix_format!(fmt::UpperHex, "{:X}", "{:.1$X}");

impl<T, R, C, S> IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: StorageMut<T, R, C>,
{
    /// Mutably borrows the underlying nalgebra matrix.
    pub const fn as_inner_mut(&mut self) -> &mut Matrix<T, R, C, S> {
        &mut self.0
    }

    /// Returns a mutable entry, or `None` if the row or column is out of bounds.
    pub fn get_mut(&mut self, row: usize, column: usize) -> Option<&mut T> {
        self.0.get_mut((row, column))
    }

    /// Mutably iterates over entries in column-major order.
    pub fn iter_mut(&mut self) -> MatrixIterMut<'_, T, R, C, S> {
        self.0.iter_mut()
    }

    /// Mutably iterates over rows.
    pub const fn row_iter_mut(&mut self) -> RowIterMut<'_, T, R, C, S> {
        self.0.row_iter_mut()
    }

    /// Mutably iterates over columns.
    pub fn column_iter_mut(&mut self) -> ColumnIterMut<'_, T, R, C, S> {
        self.0.column_iter_mut()
    }
}

impl<T, R, C, S> AsRef<Matrix<T, R, C, S>> for IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    fn as_ref(&self) -> &Matrix<T, R, C, S> {
        self.as_inner()
    }
}

impl<T, R, C, S> AsMut<Matrix<T, R, C, S>> for IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: StorageMut<T, R, C>,
{
    fn as_mut(&mut self) -> &mut Matrix<T, R, C, S> {
        self.as_inner_mut()
    }
}

impl<'a, T, R, C, S> IntoIterator for &'a IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    type Item = &'a T;
    type IntoIter = MatrixIter<'a, T, R, C, S>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T, R, C, S> IntoIterator for &'a mut IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: StorageMut<T, R, C>,
{
    type Item = &'a mut T;
    type IntoIter = MatrixIterMut<'a, T, R, C, S>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T, R, C, S> Index<(usize, usize)> for IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    type Output = T;

    #[allow(clippy::indexing_slicing)]
    fn index(&self, index: (usize, usize)) -> &Self::Output {
        &self.0[index]
    }
}

impl<T, R, C, S> IndexMut<(usize, usize)> for IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: StorageMut<T, R, C>,
{
    #[allow(clippy::indexing_slicing)]
    fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T, R, S> Index<usize> for IntervalMatrix<T, R, Const<1>, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    S: Storage<T, R, Const<1>>,
{
    type Output = T;

    #[allow(clippy::indexing_slicing)]
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl<T, R, S> IndexMut<usize> for IntervalMatrix<T, R, Const<1>, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    S: StorageMut<T, R, Const<1>>,
{
    #[allow(clippy::indexing_slicing)]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T, R, C, S> From<Matrix<T, R, C, S>> for IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    fn from(value: Matrix<T, R, C, S>) -> Self {
        Self(value)
    }
}

impl<T, R, C, S> From<Matrix<f64, R, C, S>> for OIntervalMatrix<T, R, C>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<f64, R, C>,
    DefaultAllocator: Allocator<R, C>,
{
    fn from(value: Matrix<f64, R, C, S>) -> Self {
        Self(value.map(T::from))
    }
}

impl<T, R, C> OIntervalMatrix<T, R, C>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    DefaultAllocator: Allocator<R, C>,
{
    /// Creates an owned interval matrix filled with one value.
    pub fn from_element_generic(nrows: R, ncols: C, element: T) -> Self {
        OMatrix::from_element_generic(nrows, ncols, element).into()
    }

    /// Creates an owned interval matrix by calling `f` for each `(row, column)`.
    pub fn from_fn_generic<F>(nrows: R, ncols: C, f: F) -> Self
    where
        F: FnMut(usize, usize) -> T,
    {
        OMatrix::from_fn_generic(nrows, ncols, f).into()
    }

    /// Creates an owned interval matrix from a column-major iterator.
    pub fn from_iterator_generic<I>(nrows: R, ncols: C, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        OMatrix::from_iterator_generic(nrows, ncols, iter).into()
    }

    /// Creates an owned interval matrix from a row-major iterator.
    pub fn from_row_iterator_generic<I>(nrows: R, ncols: C, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        OMatrix::from_row_iterator_generic(nrows, ncols, iter).into()
    }

    /// Creates an owned interval matrix from a row-major slice.
    pub fn from_row_slice_generic(nrows: R, ncols: C, entries: &[T]) -> Self {
        OMatrix::from_row_slice_generic(nrows, ncols, entries).into()
    }

    /// Creates an owned interval matrix from a column-major slice.
    pub fn from_column_slice_generic(nrows: R, ncols: C, entries: &[T]) -> Self {
        OMatrix::from_column_slice_generic(nrows, ncols, entries).into()
    }

    /// Creates an owned interval matrix from interval row vectors.
    ///
    /// # Panics
    ///
    /// Panics if the supplied dimensions do not match the number or width of the rows.
    #[allow(clippy::indexing_slicing)]
    pub fn from_rows_generic<SR>(
        nrows: R,
        ncols: C,
        rows: &[IntervalMatrix<T, Const<1>, C, SR>],
    ) -> Self
    where
        SR: Storage<T, Const<1>, C>,
    {
        assert_eq!(
            rows.len(),
            nrows.value(),
            "interval matrix row count mismatch"
        );
        assert!(
            rows.iter().all(|row| row.ncols() == ncols.value()),
            "interval matrix row width mismatch",
        );
        Self::from_fn_generic(nrows, ncols, |i, j| rows[i][(0, j)])
    }

    /// Creates an owned interval matrix from interval column vectors.
    ///
    /// # Panics
    ///
    /// Panics if the supplied dimensions do not match the number or height of the columns.
    #[allow(clippy::indexing_slicing)]
    pub fn from_columns_generic<SC>(
        nrows: R,
        ncols: C,
        columns: &[IntervalMatrix<T, R, Const<1>, SC>],
    ) -> Self
    where
        SC: Storage<T, R, Const<1>>,
    {
        assert_eq!(
            columns.len(),
            ncols.value(),
            "interval matrix column count mismatch",
        );
        assert!(
            columns.iter().all(|column| column.nrows() == nrows.value()),
            "interval matrix column height mismatch",
        );
        Self::from_fn_generic(nrows, ncols, |i, j| columns[j][i])
    }

    /// Creates singleton intervals from an ordinary real matrix.
    pub fn from_singletons<S2>(values: &Matrix<f64, R, C, S2>) -> Self
    where
        S2: Storage<f64, R, C>,
    {
        let (nrows, ncols) = values.shape_generic();
        Self::from_iterator_generic(nrows, ncols, values.iter().copied().map(T::singleton))
    }

    /// Creates intervals from corresponding lower- and upper-bound matrices.
    ///
    /// # Panics
    ///
    /// Panics if `lower` and `upper` have different dimensions.
    pub fn from_bounds<SL, SU>(lower: &Matrix<f64, R, C, SL>, upper: &Matrix<f64, R, C, SU>) -> Self
    where
        SL: Storage<f64, R, C>,
        SU: Storage<f64, R, C>,
    {
        assert_eq!(
            lower.shape(),
            upper.shape(),
            "interval matrix bounds dimension mismatch"
        );
        let (nrows, ncols) = lower.shape_generic();
        let entries = lower
            .iter()
            .copied()
            .zip(upper.iter().copied())
            .map(|(lower, upper)| T::new(lower, upper));
        Self::from_iterator_generic(nrows, ncols, entries)
    }

    /// Creates intervals from corresponding midpoint and radius matrices.
    ///
    /// # Panics
    ///
    /// Panics if `midpoint` and `radius` have different dimensions.
    pub fn from_mid_rad<SM, SR>(
        midpoint: &Matrix<f64, R, C, SM>,
        radius: &Matrix<f64, R, C, SR>,
    ) -> Self
    where
        SM: Storage<f64, R, C>,
        SR: Storage<f64, R, C>,
    {
        assert_eq!(
            midpoint.shape(),
            radius.shape(),
            "interval matrix midpoint-radius dimension mismatch",
        );
        let (nrows, ncols) = midpoint.shape_generic();
        let entries =
            midpoint
                .iter()
                .copied()
                .zip(radius.iter().copied())
                .map(|(midpoint, radius)| {
                    T::new(
                        rounding::sub(midpoint, radius, Direction::Down),
                        rounding::add(midpoint, radius, Direction::Up),
                    )
                });
        Self::from_iterator_generic(nrows, ncols, entries)
    }

    /// Creates an owned interval matrix filled with singleton zero intervals.
    pub fn zeros_generic(nrows: R, ncols: C) -> Self {
        Self::from_element_generic(nrows, ncols, T::ZERO)
    }
}

impl<T, D> OIntervalMatrix<T, D, D>
where
    T: IntervalOps + Scalar,
    D: Dim,
    DefaultAllocator: Allocator<D, D>,
{
    /// Creates an identity interval matrix.
    pub fn identity_generic(dim: D) -> Self {
        OMatrix::from_fn_generic(dim, dim, |i, j| if i == j { T::ONE } else { T::ZERO }).into()
    }
}

impl<T, D> OIntervalMatrix<T, D, D>
where
    T: IntervalOps + Scalar,
    D: Dim,
    DefaultAllocator: Allocator<D, D> + Allocator<D>,
{
    /// Creates a square interval matrix from its diagonal.
    pub fn from_diagonal<S>(diagonal: &IntervalMatrix<T, D, Const<1>, S>) -> Self
    where
        S: Storage<T, D, Const<1>>,
    {
        let (dim, _) = diagonal.shape_generic();
        Self::from_fn_generic(dim, dim, |i, j| if i == j { diagonal[i] } else { T::ZERO })
    }
}

impl<T, const R: usize, const C: usize> SIntervalMatrix<T, R, C>
where
    T: IntervalOps + Scalar,
{
    /// Creates a statically sized interval matrix filled with one value.
    pub fn from_element(element: T) -> Self {
        Self::from_element_generic(Const::<R>, Const::<C>, element)
    }

    /// Creates a statically sized interval matrix by calling `f` for each coordinate.
    pub fn from_fn<F>(f: F) -> Self
    where
        F: FnMut(usize, usize) -> T,
    {
        Self::from_fn_generic(Const::<R>, Const::<C>, f)
    }

    /// Creates a statically sized interval matrix from a column-major iterator.
    pub fn from_iterator<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_iterator_generic(Const::<R>, Const::<C>, iter)
    }

    /// Creates a statically sized interval matrix from a row-major iterator.
    pub fn from_row_iterator<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_row_iterator_generic(Const::<R>, Const::<C>, iter)
    }

    /// Creates a statically sized interval matrix from a row-major slice.
    pub fn from_row_slice(entries: &[T]) -> Self {
        Self::from_row_slice_generic(Const::<R>, Const::<C>, entries)
    }

    /// Creates a statically sized interval matrix from a column-major slice.
    pub fn from_column_slice(entries: &[T]) -> Self {
        Self::from_column_slice_generic(Const::<R>, Const::<C>, entries)
    }

    /// Creates a statically sized interval matrix from row vectors.
    pub fn from_rows<SR>(rows: &[IntervalMatrix<T, Const<1>, Const<C>, SR>]) -> Self
    where
        SR: Storage<T, Const<1>, Const<C>>,
    {
        Self::from_rows_generic(Const::<R>, Const::<C>, rows)
    }

    /// Creates a statically sized interval matrix from column vectors.
    pub fn from_columns<SC>(columns: &[IntervalMatrix<T, Const<R>, Const<1>, SC>]) -> Self
    where
        SC: Storage<T, Const<R>, Const<1>>,
    {
        Self::from_columns_generic(Const::<R>, Const::<C>, columns)
    }

    /// Creates a statically sized zero interval matrix.
    #[must_use]
    pub fn zeros() -> Self {
        Self::zeros_generic(Const::<R>, Const::<C>)
    }
}

impl<T, const D: usize> SIntervalMatrix<T, D, D>
where
    T: IntervalOps + Scalar,
{
    /// Creates a statically sized identity interval matrix.
    #[must_use]
    pub fn identity() -> Self {
        Self::identity_generic(Const::<D>)
    }
}

#[cfg(feature = "alloc")]
impl<T> DIntervalMatrix<T>
where
    T: IntervalOps + Scalar,
{
    /// Creates a dynamically sized interval matrix filled with one value.
    pub fn from_element(nrows: usize, ncols: usize, element: T) -> Self {
        Self::from_element_generic(Dyn(nrows), Dyn(ncols), element)
    }

    /// Creates a dynamically sized interval matrix by calling `f` for each coordinate.
    pub fn from_fn<F>(nrows: usize, ncols: usize, f: F) -> Self
    where
        F: FnMut(usize, usize) -> T,
    {
        Self::from_fn_generic(Dyn(nrows), Dyn(ncols), f)
    }

    /// Creates a dynamically sized interval matrix from a column-major iterator.
    pub fn from_iterator<I>(nrows: usize, ncols: usize, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_iterator_generic(Dyn(nrows), Dyn(ncols), iter)
    }

    /// Creates a dynamically sized interval matrix from a row-major iterator.
    pub fn from_row_iterator<I>(nrows: usize, ncols: usize, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_row_iterator_generic(Dyn(nrows), Dyn(ncols), iter)
    }

    /// Creates a dynamically sized interval matrix from a row-major slice.
    pub fn from_row_slice(nrows: usize, ncols: usize, entries: &[T]) -> Self {
        Self::from_row_slice_generic(Dyn(nrows), Dyn(ncols), entries)
    }

    /// Creates a dynamically sized interval matrix from a column-major slice.
    pub fn from_column_slice(nrows: usize, ncols: usize, entries: &[T]) -> Self {
        Self::from_column_slice_generic(Dyn(nrows), Dyn(ncols), entries)
    }

    /// Creates a dynamically sized interval matrix from row vectors.
    pub fn from_rows(rows: &[DIntervalRowVector<T>]) -> Self {
        let ncols = rows.first().map_or(0, IntervalMatrix::ncols);
        Self::from_rows_generic(Dyn(rows.len()), Dyn(ncols), rows)
    }

    /// Creates a dynamically sized interval matrix from column vectors.
    pub fn from_columns(columns: &[DIntervalVector<T>]) -> Self {
        let nrows = columns.first().map_or(0, IntervalMatrix::nrows);
        Self::from_columns_generic(Dyn(nrows), Dyn(columns.len()), columns)
    }

    /// Creates a dynamically sized zero interval matrix.
    #[must_use]
    pub fn zeros(nrows: usize, ncols: usize) -> Self {
        Self::zeros_generic(Dyn(nrows), Dyn(ncols))
    }

    /// Creates a dynamically sized identity interval matrix.
    #[must_use]
    pub fn identity(dim: usize) -> Self {
        Self::identity_generic(Dyn(dim))
    }
}

#[cfg(feature = "alloc")]
impl<T> DIntervalVector<T>
where
    T: IntervalOps + Scalar,
{
    /// Creates a dynamically sized interval column vector filled with one value.
    pub fn from_element(nrows: usize, element: T) -> Self {
        Self::from_element_generic(Dyn(nrows), Const::<1>, element)
    }

    /// Creates a dynamically sized interval column vector by calling `f` for each row.
    pub fn from_fn<F>(nrows: usize, mut f: F) -> Self
    where
        F: FnMut(usize) -> T,
    {
        Self::from_fn_generic(Dyn(nrows), Const::<1>, |i, _| f(i))
    }

    /// Creates a dynamically sized interval column vector from an iterator.
    pub fn from_iterator<I>(nrows: usize, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_iterator_generic(Dyn(nrows), Const::<1>, iter)
    }

    /// Creates a dynamically sized interval column vector from a slice.
    pub fn from_column_slice(entries: &[T]) -> Self {
        Self::from_column_slice_generic(Dyn(entries.len()), Const::<1>, entries)
    }

    /// Creates a dynamically sized zero interval column vector.
    #[must_use]
    pub fn zeros(nrows: usize) -> Self {
        Self::zeros_generic(Dyn(nrows), Const::<1>)
    }
}

#[cfg(feature = "alloc")]
impl<T> DIntervalRowVector<T>
where
    T: IntervalOps + Scalar,
{
    /// Creates a dynamically sized interval row vector filled with one value.
    pub fn from_element(ncols: usize, element: T) -> Self {
        Self::from_element_generic(Const::<1>, Dyn(ncols), element)
    }

    /// Creates a dynamically sized interval row vector by calling `f` for each column.
    pub fn from_fn<F>(ncols: usize, mut f: F) -> Self
    where
        F: FnMut(usize) -> T,
    {
        Self::from_fn_generic(Const::<1>, Dyn(ncols), |_, j| f(j))
    }

    /// Creates a dynamically sized interval row vector from an iterator.
    pub fn from_iterator<I>(ncols: usize, iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_iterator_generic(Const::<1>, Dyn(ncols), iter)
    }

    /// Creates a dynamically sized interval row vector from a slice.
    pub fn from_row_slice(entries: &[T]) -> Self {
        Self::from_row_slice_generic(Const::<1>, Dyn(entries.len()), entries)
    }

    /// Creates a dynamically sized zero interval row vector.
    #[must_use]
    pub fn zeros(ncols: usize) -> Self {
        Self::zeros_generic(Const::<1>, Dyn(ncols))
    }
}

impl<T, R, C, S> IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
{
    /// Returns whether any entry is empty.
    #[must_use]
    pub fn has_empty_entries(&self) -> bool {
        self.any(IntervalOps::is_empty)
    }

    /// Returns whether any entry is `NaI`.
    #[must_use]
    pub fn has_nai_entries(&self) -> bool {
        self.any(IntervalOps::is_nai)
    }

    /// Returns whether any entry is entire.
    #[must_use]
    pub fn has_entire_entries(&self) -> bool {
        self.any(IntervalOps::is_entire)
    }

    /// Intersects corresponding entries of two matrices.
    ///
    /// # Panics
    ///
    /// Panics if the matrices have different dimensions.
    #[must_use]
    pub fn intersection<R2, C2, S2>(
        &self,
        rhs: &IntervalMatrix<T, R2, C2, S2>,
    ) -> OIntervalMatrix<T, SameShapeR<R, R2>, SameShapeC<C, C2>>
    where
        R2: Dim,
        C2: Dim,
        S2: Storage<T, R2, C2>,
        DefaultAllocator: SameShapeAllocator<R, C, R2, C2>,
        ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2>,
    {
        self.zip_map(rhs, IntervalOps::intersection)
    }

    /// Computes the convex hull of corresponding entries of two matrices.
    ///
    /// # Panics
    ///
    /// Panics if the matrices have different dimensions.
    #[must_use]
    pub fn convex_hull<R2, C2, S2>(
        &self,
        rhs: &IntervalMatrix<T, R2, C2, S2>,
    ) -> OIntervalMatrix<T, SameShapeR<R, R2>, SameShapeC<C, C2>>
    where
        R2: Dim,
        C2: Dim,
        S2: Storage<T, R2, C2>,
        DefaultAllocator: SameShapeAllocator<R, C, R2, C2>,
        ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2>,
    {
        self.zip_map(rhs, IntervalOps::convex_hull)
    }

    /// Returns whether corresponding entries are interval-equal.
    ///
    /// # Panics
    ///
    /// Panics if the matrices have different dimensions.
    #[must_use]
    pub fn equal<R2, C2, S2>(&self, rhs: &IntervalMatrix<T, R2, C2, S2>) -> bool
    where
        R2: Dim,
        C2: Dim,
        S2: Storage<T, R2, C2>,
        ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2>,
    {
        assert_eq!(
            self.shape(),
            rhs.shape(),
            "interval matrix equality dimension mismatch",
        );
        self.iter()
            .copied()
            .zip(rhs.iter().copied())
            .all(|(lhs, rhs)| lhs.equal(rhs))
    }

    /// Returns whether every entry is a subset of the corresponding `rhs` entry.
    ///
    /// # Panics
    ///
    /// Panics if the matrices have different dimensions.
    #[must_use]
    pub fn subset<R2, C2, S2>(&self, rhs: &IntervalMatrix<T, R2, C2, S2>) -> bool
    where
        R2: Dim,
        C2: Dim,
        S2: Storage<T, R2, C2>,
        ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2>,
    {
        assert_eq!(
            self.shape(),
            rhs.shape(),
            "interval matrix subset dimension mismatch",
        );
        self.iter()
            .copied()
            .zip(rhs.iter().copied())
            .all(|(lhs, rhs)| lhs.subset(rhs))
    }

    /// Returns whether every entry lies in the interior of the corresponding `rhs` entry.
    ///
    /// # Panics
    ///
    /// Panics if the matrices have different dimensions.
    #[must_use]
    pub fn interior<R2, C2, S2>(&self, rhs: &IntervalMatrix<T, R2, C2, S2>) -> bool
    where
        R2: Dim,
        C2: Dim,
        S2: Storage<T, R2, C2>,
        ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2>,
    {
        assert_eq!(
            self.shape(),
            rhs.shape(),
            "interval matrix interior dimension mismatch",
        );
        self.iter()
            .copied()
            .zip(rhs.iter().copied())
            .all(|(lhs, rhs)| lhs.interior(rhs))
    }
}

impl<T, D, S> IntervalMatrix<T, D, D, S>
where
    T: IntervalOps + Scalar,
    D: Dim,
    S: Storage<T, D, D>,
{
    /// Returns whether every off-diagonal interval is nonpositive.
    #[must_use]
    pub fn is_z_matrix(&self) -> bool {
        // Def 4.4
        if !self.is_square() || self.has_empty_entries() || self.has_nai_entries() {
            return false;
        }
        let n = self.nrows();
        (0..n).all(|i| (0..n).all(|j| i == j || self[(i, j)].sup() <= 0.0))
    }
}

impl<T, D, S> IntervalMatrix<T, D, D, S>
where
    T: IntervalOps + Scalar,
    D: Dim,
    S: Storage<T, D, D>,
    DefaultAllocator: Allocator<D, D>,
{
    /// Builds the real comparison matrix of this interval matrix.
    ///
    /// Diagonal entries are the mignitudes of the corresponding intervals;
    /// off-diagonal entries are the negated magnitudes.
    ///
    /// Returns `None` when the matrix is not square or contains an empty or
    /// `NaI` entry.
    #[must_use]
    pub fn comparison_matrix(&self) -> Option<OMatrix<f64, D, D>> {
        if !self.is_square() || self.has_empty_entries() || self.has_nai_entries() {
            return None;
        }
        let (dim, _) = self.shape_generic();
        Some(OMatrix::from_fn_generic(dim, dim, |i, j| {
            if i == j {
                self[(i, j)].mig()
            } else {
                -self[(i, j)].mag()
            }
        }))
    }
}

#[allow(clippy::indexing_slicing)]
impl<T, D, S> IntervalMatrix<T, D, D, S>
where
    T: IntervalOps + Scalar,
    D: Dim + DimMin<D, Output = D>,
    S: Storage<T, D, D>,
    DefaultAllocator: Allocator<D, D> + Allocator<D>,
{
    /// Tests whether this interval matrix is an M-matrix.
    ///
    /// Returns `false` when the property cannot be certified, including for
    /// empty, invalid, or singular systems.
    #[must_use]
    pub fn is_m_matrix(&self) -> bool {
        // Def 4.5
        if !self.is_z_matrix() {
            return false;
        }
        let n = self.nrows();
        if n == 0 {
            return false;
        }
        let (dim, _) = self.shape_generic();

        // Theorem 4.9(3)
        let a_inf = self.inf();
        let e = OVector::<f64, D>::repeat_generic(dim, Const::<1>, 1.0);
        let Some(u) = a_inf.lu().solve(&e) else {
            return false; // Theorem 4.9(4)
        };

        // Check inv(inf(A)) e = u > 0
        if u.iter().any(|&entry| !entry.is_finite() || entry <= 0.0) {
            return false;
        }

        // Check Au > 0
        (0..n).all(|i| {
            let mut row_sum = T::ZERO;
            for j in 0..n {
                row_sum = self[(i, j)].mul_add(T::singleton(u[j]), row_sum);
            }
            row_sum.inf() > 0.0
        })
    }

    /// Tests whether this interval matrix is an H-matrix.
    ///
    /// Returns `false` when its comparison matrix is invalid, empty,
    /// non-finite, singular, or does not satisfy the positive-vector test.
    #[must_use]
    pub fn is_h_matrix(&self) -> bool {
        let Some(comparison) = self.comparison_matrix() else {
            return false; // not square or invalid entries
        };
        let n = comparison.nrows();
        if n == 0 || comparison.iter().any(|entry| !entry.is_finite()) {
            return false;
        }
        let (dim, _) = self.shape_generic();
        // Theorem 4.18(3)
        let e = OVector::<f64, D>::repeat_generic(dim, Const::<1>, 1.0);
        let Some(u) = comparison.clone().lu().solve(&e) else {
            return false;
        };
        if u.iter().any(|&entry| !entry.is_finite() || entry <= 0.0) {
            return false;
        }
        // NOTE: Technically the following rechecks this, but it uses IA. The previous check is just
        // a fast path to check for failure quickly.
        (0..n).all(|i| {
            let mut row_sum = T::ZERO;
            for j in 0..n {
                let c_ij = T::singleton(comparison[(i, j)]);
                let u_j = T::singleton(u[j]);
                row_sum = c_ij.mul_add(u_j, row_sum);
            }
            row_sum.inf() > 0.0
        })
    }

    /// Tests strong regularity using midpoint-inverse preconditioning.
    ///
    /// Returns `false` when the midpoint inverse or the resulting H-matrix
    /// condition cannot be certified.
    #[must_use]
    pub fn is_strongly_regular(&self) -> bool {
        if !self.is_square()
            || self.is_empty()
            || self.has_empty_entries()
            || self.has_nai_entries()
        {
            return false;
        }

        let a_c = self.mid();
        if a_c.iter().any(|entry| !entry.is_finite()) {
            return false;
        }
        let Some(c) = a_c.try_inverse() else {
            return false;
        };

        if c.iter().any(|entry| !entry.is_finite()) {
            return false;
        }
        let c_interval: OIntervalMatrix<T, D, D> = c.into();
        // Theorem 4.33(5)
        let preconditioned = Mul::mul(&c_interval, self);
        preconditioned.is_h_matrix()
    }
}

impl<T, R, C, S> IntervalMatrix<T, R, C, S>
where
    T: IntervalOps + Scalar,
    R: Dim,
    C: Dim,
    S: Storage<T, R, C>,
    DefaultAllocator: Allocator<R, C>,
{
    /// Returns the matrix of lower endpoints.
    #[must_use]
    pub fn inf(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::inf)
    }
    /// Returns the matrix of upper endpoints.
    #[must_use]
    pub fn sup(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::sup)
    }

    /// Returns the matrix of outward-rounded radii.
    #[must_use]
    pub fn rad(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::rad)
    }
    /// Returns the matrix of inward-rounded radii.
    #[must_use]
    pub fn inner_rad(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::inner_rad)
    }

    /// Returns the matrix of interval midpoints.
    #[must_use]
    pub fn mid(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::mid)
    }

    /// Returns the matrix of interval magnitudes.
    #[must_use]
    pub fn mag(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::mag)
    }

    /// Returns the matrix of interval mignitudes.
    #[must_use]
    pub fn mig(&self) -> OMatrix<f64, R, C> {
        self.map_inner(IntervalOps::mig)
    }

    /// Returns an upward-rounded upper bound for the induced matrix 1-norm.
    #[must_use]
    pub fn norm1(&self) -> f64 {
        let mut norm: f64 = 0.0;
        for column in self.mag().column_iter() {
            let mut sum = 0.0;
            for row_entry in column.iter() {
                sum = rounding::add(sum, *row_entry, Direction::Up);
                if sum.is_nan() {
                    return f64::NAN;
                }
                norm = norm.max(sum);
            }
        }
        norm
    }

    /// Returns an upward-rounded upper bound for the induced infinity norm.
    #[must_use]
    pub fn inf_norm(&self) -> f64 {
        let mut norm: f64 = 0.0;
        for row in self.mag().row_iter() {
            let mut sum = 0.0;
            for column_entry in row.iter() {
                sum = rounding::add(sum, *column_entry, Direction::Up);
                if sum.is_nan() {
                    return f64::NAN;
                }
                norm = norm.max(sum);
            }
        }
        norm
    }
}

impl<T, D, S> IntervalMatrix<T, D, Const<1>, S>
where
    T: IntervalOps + Scalar,
    D: Dim,
    S: Storage<T, D, Const<1>>,
{
    /// Returns an upward-rounded upper bound for the weighted maximum norm.
    ///
    /// The norm is `max_i mag(self[i]) / v[i]`. Returns `NaN` if a weight is
    /// nonpositive or non-finite, or if an interval magnitude is `NaN`.
    ///
    /// # Panics
    ///
    /// Panics if `self` and `v` have different lengths.
    #[must_use]
    #[allow(clippy::arithmetic_side_effects)]
    pub fn v_norm<SV>(&self, v: &Matrix<f64, D, Const<1>, SV>) -> f64
    where
        SV: Storage<f64, D, Const<1>>,
    {
        assert_eq!(
            self.nrows(),
            v.nrows(),
            "interval vector weighted norm dimension mismatch",
        );
        self.iter()
            .zip(v.iter())
            .try_fold(0.0_f64, |norm, (entry, &weight)| {
                if !weight.is_finite() || weight <= 0.0 {
                    None
                } else {
                    let weighted_magnitude = (*entry / weight).mag();
                    (!weighted_magnitude.is_nan()).then(|| norm.max(weighted_magnitude))
                }
            })
            .unwrap_or(f64::NAN)
    }
}

mod ops;

/// A verified solver for square interval linear systems.
pub trait Solver<T, D>
where
    T: IntervalOps + Scalar,
    D: Dim,
    DefaultAllocator: Allocator<D, D> + Allocator<D>,
{
    /// Computes an interval enclosure of the solution.
    ///
    /// Returns `None` when the system is dimensionally invalid or the method
    /// cannot certify an enclosure.
    #[must_use]
    fn solve<SA, SB>(
        &self,
        lhs: &IntervalMatrix<T, D, D, SA>,
        rhs: &IntervalMatrix<T, D, Const<1>, SB>,
    ) -> Option<OIntervalVector<T, D>>
    where
        SA: Storage<T, D, D>,
        SB: Storage<T, D, Const<1>>;

    /// Computes an interval enclosure of the inverse.
    ///
    /// Returns `None` if any column of the inverse cannot be certified.
    #[must_use]
    #[allow(clippy::indexing_slicing)]
    fn inverse<S>(&self, mat: &IntervalMatrix<T, D, D, S>) -> Option<OIntervalMatrix<T, D, D>>
    where
        S: Storage<T, D, D>,
    {
        let (dim, _) = mat.shape_generic();
        let mut inverse = OIntervalMatrix::zeros_generic(dim, dim);
        for column in 0..mat.ncols() {
            let rhs = OIntervalVector::from_fn_generic(dim, Const::<1>, |row, _| {
                if row == column { T::ONE } else { T::ZERO }
            });
            let solution = self.solve(mat, &rhs)?;
            for row in 0..mat.nrows() {
                inverse[(row, column)] = solution[row];
            }
        }
        Some(inverse)
    }
}

/// Epsilon-inflation method.
mod epsilon_inflation;
pub use epsilon_inflation::EpsilonInflationSolver;

/// Gaussian elimination method.
mod gaussian_elimination;
pub use gaussian_elimination::GaussianEliminationSolver;

/// Hansen–Bliek–Rohn method.
mod hansen_bliek_rohn;
pub use hansen_bliek_rohn::HansenBliekRohnSolver;

/// Iterative methods for matrix solves.
mod iterative;
pub use iterative::{
    GaussSeidelSolver, InitialEnclosure, JacobiSolver, KrawczykSolver, StoppingTolerance,
};

mod preconditioned;
pub use preconditioned::{Preconditioned, Preconditioner};

impl<T, D, S> IntervalMatrix<T, D, D, S>
where
    T: IntervalOps + Scalar,
    D: Dim,
    S: Storage<T, D, D>,
    DefaultAllocator: Allocator<D, D> + Allocator<D>,
{
    /// Computes an interval enclosure of the solution using Gaussian elimination.
    #[must_use]
    pub fn solve<SR>(
        &self,
        rhs: &IntervalMatrix<T, D, Const<1>, SR>,
    ) -> Option<OIntervalVector<T, D>>
    where
        SR: Storage<T, D, Const<1>>,
        D: DimMin<D, Output = D>,
        GaussianEliminationSolver: Solver<T, D>,
    {
        let solver = Preconditioned::auto(GaussianEliminationSolver, self);
        solver.solve(self, rhs)
    }

    /// Computes an interval enclosure of the solution using `solver`.
    #[must_use]
    pub fn solve_with<SR, V>(
        &self,
        rhs: &IntervalMatrix<T, D, Const<1>, SR>,
        solver: &V,
    ) -> Option<OIntervalVector<T, D>>
    where
        SR: Storage<T, D, Const<1>>,
        V: Solver<T, D>,
    {
        solver.solve(self, rhs)
    }

    /// Computes an interval enclosure of the inverse using Gaussian elimination.
    #[must_use]
    pub fn inverse(&self) -> Option<OIntervalMatrix<T, D, D>>
    where
        D: DimMin<D, Output = D>,
        GaussianEliminationSolver: Solver<T, D>,
    {
        let solver = Preconditioned::auto(GaussianEliminationSolver, self);
        solver.inverse(self)
    }

    /// Computes an interval enclosure of the inverse using `solver`.
    #[must_use]
    pub fn inverse_with<V>(&self, solver: &V) -> Option<OIntervalMatrix<T, D, D>>
    where
        V: Solver<T, D>,
    {
        solver.inverse(self)
    }
}