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
use lapacke;
use ndarray::{ErrorKind, ShapeError};
use num_traits::Zero;
use crate::error::*;
use crate::layout::MatrixLayout;
use crate::types::*;
use super::into_result;
pub struct LeastSquaresOutput<A: Scalar> {
pub singular_values: Vec<A::Real>,
pub rank: i32,
}
pub trait LeastSquaresSvdDivideConquer_: Scalar {
unsafe fn least_squares(
a_layout: MatrixLayout,
a: &mut [Self],
b: &mut [Self],
) -> Result<LeastSquaresOutput<Self>>;
unsafe fn least_squares_nrhs(
a_layout: MatrixLayout,
a: &mut [Self],
b_layout: MatrixLayout,
b: &mut [Self],
) -> Result<LeastSquaresOutput<Self>>;
}
macro_rules! impl_least_squares {
($scalar:ty, $gelsd:path) => {
impl LeastSquaresSvdDivideConquer_ for $scalar {
unsafe fn least_squares(
a_layout: MatrixLayout,
a: &mut [Self],
b: &mut [Self],
) -> Result<LeastSquaresOutput<Self>> {
let (m, n) = a_layout.size();
if (m as usize) > b.len() || (n as usize) > b.len() {
return Err(LinalgError::Shape(ShapeError::from_kind(
ErrorKind::IncompatibleShape,
)));
}
let k = ::std::cmp::min(m, n);
let nrhs = 1;
let rcond: Self::Real = -1.;
let mut singular_values: Vec<Self::Real> = vec![Self::Real::zero(); k as usize];
let mut rank: i32 = 0;
let status = $gelsd(
a_layout.lapacke_layout(),
m,
n,
nrhs,
a,
a_layout.lda(),
b,
nrhs,
&mut singular_values,
rcond,
&mut rank,
);
into_result(
status,
LeastSquaresOutput {
singular_values,
rank,
},
)
}
unsafe fn least_squares_nrhs(
a_layout: MatrixLayout,
a: &mut [Self],
b_layout: MatrixLayout,
b: &mut [Self],
) -> Result<LeastSquaresOutput<Self>> {
let (m, n) = a_layout.size();
if (m as usize) > b.len()
|| (n as usize) > b.len()
|| a_layout.lapacke_layout() != b_layout.lapacke_layout()
{
return Err(LinalgError::Shape(ShapeError::from_kind(
ErrorKind::IncompatibleShape,
)));
}
let k = ::std::cmp::min(m, n);
let nrhs = b_layout.size().1;
let rcond: Self::Real = -1.;
let mut singular_values: Vec<Self::Real> = vec![Self::Real::zero(); k as usize];
let mut rank: i32 = 0;
let status = $gelsd(
a_layout.lapacke_layout(),
m,
n,
nrhs,
a,
a_layout.lda(),
b,
b_layout.lda(),
&mut singular_values,
rcond,
&mut rank,
);
into_result(
status,
LeastSquaresOutput {
singular_values,
rank,
},
)
}
}
};
}
impl_least_squares!(f64, lapacke::dgelsd);
impl_least_squares!(f32, lapacke::sgelsd);
impl_least_squares!(c64, lapacke::zgelsd);
impl_least_squares!(c32, lapacke::cgelsd);