use core::ffi::c_int;
use onemkl_sys as sys;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy)]
pub struct IssOptions {
pub max_iterations: usize,
pub relative_tolerance: f64,
pub absolute_tolerance: f64,
pub restart_length: usize,
}
impl Default for IssOptions {
fn default() -> Self {
Self {
max_iterations: 1000,
relative_tolerance: 1e-10,
absolute_tolerance: 0.0,
restart_length: 20,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct IssResult {
pub iterations: usize,
pub initial_residual_norm: f64,
pub final_residual_norm: f64,
pub stop_reason: IssStopReason,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IssStopReason {
Converged,
MaxIterations,
Other(i32),
}
const RCI_OK: c_int = 0;
const RCI_NEED_MV: c_int = 1;
const RCI_NEED_PRECOND: c_int = 3;
pub fn solve_cg<F>(b: &[f64], x: &mut [f64], opts: IssOptions, mat_vec: F) -> Result<IssResult>
where
F: FnMut(&[f64], &mut [f64]),
{
solve_cg_preconditioned::<F, fn(&[f64], &mut [f64])>(b, x, opts, mat_vec, None)
}
pub fn solve_cg_preconditioned<F, P>(
b: &[f64],
x: &mut [f64],
opts: IssOptions,
mut mat_vec: F,
mut precondition: Option<P>,
) -> Result<IssResult>
where
F: FnMut(&[f64], &mut [f64]),
P: FnMut(&[f64], &mut [f64]),
{
if b.len() != x.len() {
return Err(Error::InvalidArgument("b and x must have the same length"));
}
let n = b.len();
let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
let mut ipar: [c_int; 128] = [0; 128];
let mut dpar: [f64; 128] = [0.0; 128];
let mut tmp: Vec<f64> = vec![0.0; 4 * n];
let mut rci: c_int = 0;
unsafe {
sys::dcg_init(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci != 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
ipar[4] = opts.max_iterations.try_into().unwrap_or(c_int::MAX);
ipar[7] = 1; ipar[8] = 1; ipar[9] = 0; ipar[10] = if precondition.is_some() { 1 } else { 0 };
dpar[0] = opts.relative_tolerance;
dpar[1] = opts.absolute_tolerance;
unsafe {
sys::dcg_check(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci < 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
let mut last_rci;
loop {
unsafe {
sys::dcg(
&n_i,
x.as_mut_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
last_rci = rci;
match rci {
RCI_OK => break,
RCI_NEED_MV => {
let (src, rest) = tmp.split_at_mut(n);
let dst = &mut rest[..n];
mat_vec(src, dst);
}
RCI_NEED_PRECOND => {
if let Some(p) = precondition.as_mut() {
let (lo, hi) = tmp.split_at_mut(3 * n);
let src = &lo[2 * n..3 * n];
let dst = &mut hi[..n];
p(src, dst);
} else {
return Err(Error::InvalidArgument(
"CG asked for preconditioning but none was provided",
));
}
}
other if other < 0 => {
return Err(Error::LapackComputationFailure { info: other });
}
_ => {
}
}
}
let mut itercount: c_int = 0;
unsafe {
sys::dcg_get(
&n_i,
x.as_ptr(),
b.as_ptr(),
&rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
&mut itercount,
);
}
let iterations = itercount.max(0) as usize;
Ok(IssResult {
iterations,
initial_residual_norm: dpar[2],
final_residual_norm: dpar[4],
stop_reason: classify_stop(last_rci, iterations, opts.max_iterations, dpar[4], &dpar),
})
}
pub fn solve_fgmres<F>(
b: &mut [f64],
x: &mut [f64],
opts: IssOptions,
mut mat_vec: F,
) -> Result<IssResult>
where
F: FnMut(&[f64], &mut [f64]),
{
if b.len() != x.len() {
return Err(Error::InvalidArgument("b and x must have the same length"));
}
let n = b.len();
let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
let restart = opts.restart_length.min(n);
let restart_i: c_int = restart.try_into().map_err(|_| Error::DimensionOverflow)?;
let mut ipar: [c_int; 128] = [0; 128];
let mut dpar: [f64; 128] = [0.0; 128];
let tmp_len = ((2 * restart + 1) * n) + restart * (restart + 9) / 2 + 1;
let mut tmp: Vec<f64> = vec![0.0; tmp_len];
let mut rci: c_int = 0;
unsafe {
sys::dfgmres_init(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci != 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
ipar[4] = opts.max_iterations.try_into().unwrap_or(c_int::MAX);
ipar[7] = 1;
ipar[8] = 1;
ipar[9] = 0;
ipar[10] = 0; ipar[11] = 1; ipar[14] = restart_i;
dpar[0] = opts.relative_tolerance;
dpar[1] = opts.absolute_tolerance;
unsafe {
sys::dfgmres_check(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci < 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
let mut last_rci;
loop {
unsafe {
sys::dfgmres(
&n_i,
x.as_mut_ptr(),
b.as_mut_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
last_rci = rci;
match rci {
RCI_OK => break,
RCI_NEED_MV => {
let src_off = (ipar[21] - 1).max(0) as usize;
let dst_off = (ipar[22] - 1).max(0) as usize;
debug_assert!(src_off + n <= tmp.len());
debug_assert!(dst_off + n <= tmp.len());
let (low, high, low_off, high_off) = if src_off < dst_off {
let (a, b) = tmp.split_at_mut(dst_off);
(a, b, src_off, 0)
} else if src_off > dst_off {
let (a, b) = tmp.split_at_mut(src_off);
(b, a, 0, dst_off)
} else {
return Err(Error::InvalidArgument(
"FGMRES requested mat-vec with overlapping src and dst slices",
));
};
if src_off < dst_off {
let src = &low[low_off..low_off + n];
let dst = &mut high[..n];
mat_vec(src, dst);
} else {
let src = &low[..n];
let dst = &mut high[high_off..high_off + n];
mat_vec(src, dst);
}
}
other if other < 0 => {
return Err(Error::LapackComputationFailure { info: other });
}
_ => {}
}
}
let mut itercount: c_int = 0;
unsafe {
sys::dfgmres_get(
&n_i,
x.as_mut_ptr(),
b.as_mut_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
&mut itercount,
);
}
let iterations = itercount.max(0) as usize;
Ok(IssResult {
iterations,
initial_residual_norm: dpar[2],
final_residual_norm: dpar[4],
stop_reason: classify_stop(last_rci, iterations, opts.max_iterations, dpar[4], &dpar),
})
}
fn classify_stop(
last_rci: c_int,
iterations: usize,
max_iterations: usize,
final_residual: f64,
dpar: &[f64; 128],
) -> IssStopReason {
if last_rci == 0 {
if final_residual <= dpar[3] {
IssStopReason::Converged
} else if iterations >= max_iterations {
IssStopReason::MaxIterations
} else {
IssStopReason::Converged
}
} else {
IssStopReason::Other(last_rci)
}
}
#[derive(Debug)]
pub enum RciAction<'a> {
Converged,
NeedMatVec {
src: &'a [f64],
dst: &'a mut [f64],
},
NeedPrecondition {
src: &'a [f64],
dst: &'a mut [f64],
},
StoppingTest,
Other(i32),
}
pub struct CgSession {
n: c_int,
n_us: usize,
ipar: [c_int; 128],
dpar: [f64; 128],
tmp: Vec<f64>,
last_rci: c_int,
max_iterations: usize,
preconditioned: bool,
}
impl CgSession {
pub fn new(
n: usize,
b: &[f64],
x: &[f64],
opts: IssOptions,
preconditioned: bool,
) -> Result<Self> {
if b.len() != n || x.len() != n {
return Err(Error::InvalidArgument("b and x must each have length n"));
}
let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
let mut ipar: [c_int; 128] = [0; 128];
let mut dpar: [f64; 128] = [0.0; 128];
let mut tmp: Vec<f64> = vec![0.0; 4 * n];
let mut rci: c_int = 0;
unsafe {
sys::dcg_init(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci != 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
ipar[4] = opts.max_iterations.try_into().unwrap_or(c_int::MAX);
ipar[7] = 1;
ipar[8] = 1;
ipar[9] = 0;
ipar[10] = if preconditioned { 1 } else { 0 };
dpar[0] = opts.relative_tolerance;
dpar[1] = opts.absolute_tolerance;
unsafe {
sys::dcg_check(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci < 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
Ok(Self {
n: n_i,
n_us: n,
ipar,
dpar,
tmp,
last_rci: 0,
max_iterations: opts.max_iterations,
preconditioned,
})
}
pub fn step<'a>(&'a mut self, b: &[f64], x: &mut [f64]) -> Result<RciAction<'a>> {
let mut rci: c_int = 0;
unsafe {
sys::dcg(
&self.n,
x.as_mut_ptr(),
b.as_ptr(),
&mut rci,
self.ipar.as_mut_ptr(),
self.dpar.as_mut_ptr(),
self.tmp.as_mut_ptr(),
);
}
self.last_rci = rci;
match rci {
0 => Ok(RciAction::Converged),
1 => {
let n = self.n_us;
let (src_part, rest) = self.tmp.split_at_mut(n);
let dst = &mut rest[..n];
Ok(RciAction::NeedMatVec { src: src_part, dst })
}
2 => Ok(RciAction::StoppingTest),
3 => {
if !self.preconditioned {
return Err(Error::InvalidArgument(
"CG requested preconditioning but session was built without it",
));
}
let n = self.n_us;
let (lo, hi) = self.tmp.split_at_mut(3 * n);
let src = &lo[2 * n..3 * n];
let dst = &mut hi[..n];
Ok(RciAction::NeedPrecondition { src, dst })
}
other => Ok(RciAction::Other(other)),
}
}
pub fn finish(&mut self, b: &[f64], x: &[f64]) -> Result<IssResult> {
let mut itercount: c_int = 0;
let rci: c_int = 0;
unsafe {
sys::dcg_get(
&self.n,
x.as_ptr(),
b.as_ptr(),
&rci,
self.ipar.as_mut_ptr(),
self.dpar.as_mut_ptr(),
self.tmp.as_mut_ptr(),
&mut itercount,
);
}
let iterations = itercount.max(0) as usize;
Ok(IssResult {
iterations,
initial_residual_norm: self.dpar[2],
final_residual_norm: self.dpar[4],
stop_reason: classify_stop(
self.last_rci,
iterations,
self.max_iterations,
self.dpar[4],
&self.dpar,
),
})
}
#[inline]
pub fn ipar(&mut self) -> &mut [c_int; 128] {
&mut self.ipar
}
#[inline]
pub fn dpar(&mut self) -> &mut [f64; 128] {
&mut self.dpar
}
}
pub struct FgmresSession {
n: c_int,
n_us: usize,
ipar: [c_int; 128],
dpar: [f64; 128],
tmp: Vec<f64>,
last_rci: c_int,
max_iterations: usize,
}
impl FgmresSession {
pub fn new(n: usize, b: &[f64], x: &[f64], opts: IssOptions) -> Result<Self> {
if b.len() != n || x.len() != n {
return Err(Error::InvalidArgument("b and x must each have length n"));
}
let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
let restart = opts.restart_length.min(n);
let restart_i: c_int = restart.try_into().map_err(|_| Error::DimensionOverflow)?;
let mut ipar: [c_int; 128] = [0; 128];
let mut dpar: [f64; 128] = [0.0; 128];
let tmp_len = ((2 * restart + 1) * n) + restart * (restart + 9) / 2 + 1;
let mut tmp: Vec<f64> = vec![0.0; tmp_len];
let mut rci: c_int = 0;
unsafe {
sys::dfgmres_init(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci != 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
ipar[4] = opts.max_iterations.try_into().unwrap_or(c_int::MAX);
ipar[7] = 1;
ipar[8] = 1;
ipar[9] = 0;
ipar[10] = 0;
ipar[11] = 1;
ipar[14] = restart_i;
dpar[0] = opts.relative_tolerance;
dpar[1] = opts.absolute_tolerance;
unsafe {
sys::dfgmres_check(
&n_i,
x.as_ptr(),
b.as_ptr(),
&mut rci,
ipar.as_mut_ptr(),
dpar.as_mut_ptr(),
tmp.as_mut_ptr(),
);
}
if rci < 0 {
return Err(Error::LapackComputationFailure { info: rci });
}
Ok(Self {
n: n_i,
n_us: n,
ipar,
dpar,
tmp,
last_rci: 0,
max_iterations: opts.max_iterations,
})
}
pub fn step<'a>(&'a mut self, b: &mut [f64], x: &mut [f64]) -> Result<RciAction<'a>> {
let mut rci: c_int = 0;
unsafe {
sys::dfgmres(
&self.n,
x.as_mut_ptr(),
b.as_mut_ptr(),
&mut rci,
self.ipar.as_mut_ptr(),
self.dpar.as_mut_ptr(),
self.tmp.as_mut_ptr(),
);
}
self.last_rci = rci;
match rci {
0 => Ok(RciAction::Converged),
1 => {
let n = self.n_us;
let src_off = (self.ipar[21] - 1).max(0) as usize;
let dst_off = (self.ipar[22] - 1).max(0) as usize;
if src_off + n > self.tmp.len() || dst_off + n > self.tmp.len() {
return Err(Error::InvalidArgument(
"FGMRES requested mat-vec with out-of-range tmp offsets",
));
}
if src_off == dst_off {
return Err(Error::InvalidArgument(
"FGMRES requested mat-vec with overlapping src and dst",
));
}
if src_off < dst_off {
let (lo, hi) = self.tmp.split_at_mut(dst_off);
let src = &lo[src_off..src_off + n];
let dst = &mut hi[..n];
Ok(RciAction::NeedMatVec { src, dst })
} else {
let (lo, hi) = self.tmp.split_at_mut(src_off);
let src = &hi[..n];
let dst = &mut lo[dst_off..dst_off + n];
Ok(RciAction::NeedMatVec { src, dst })
}
}
2 => Ok(RciAction::StoppingTest),
other => Ok(RciAction::Other(other)),
}
}
pub fn finish(&mut self, b: &mut [f64], x: &mut [f64]) -> Result<IssResult> {
let mut itercount: c_int = 0;
let mut rci: c_int = 0;
unsafe {
sys::dfgmres_get(
&self.n,
x.as_mut_ptr(),
b.as_mut_ptr(),
&mut rci,
self.ipar.as_mut_ptr(),
self.dpar.as_mut_ptr(),
self.tmp.as_mut_ptr(),
&mut itercount,
);
}
let iterations = itercount.max(0) as usize;
Ok(IssResult {
iterations,
initial_residual_norm: self.dpar[2],
final_residual_norm: self.dpar[4],
stop_reason: classify_stop(
self.last_rci,
iterations,
self.max_iterations,
self.dpar[4],
&self.dpar,
),
})
}
#[inline]
pub fn ipar(&mut self) -> &mut [c_int; 128] {
&mut self.ipar
}
#[inline]
pub fn dpar(&mut self) -> &mut [f64; 128] {
&mut self.dpar
}
}