use core::ffi::c_int;
use core::marker::PhantomData;
use core::ptr;
use std::ffi::CString;
use std::path::Path;
use num_complex::{Complex32, Complex64};
use onemkl_sys as sys;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PardisoMatrixType {
RealStructSym,
RealSpd,
RealSymIndefinite,
ComplexStructSym,
ComplexHpd,
ComplexHermIndefinite,
ComplexSym,
RealUnsym,
ComplexUnsym,
}
impl PardisoMatrixType {
#[inline]
fn as_int(self) -> i32 {
match self {
Self::RealStructSym => 1,
Self::RealSpd => 2,
Self::RealSymIndefinite => -2,
Self::ComplexStructSym => 3,
Self::ComplexHpd => 4,
Self::ComplexHermIndefinite => -4,
Self::ComplexSym => 6,
Self::RealUnsym => 11,
Self::ComplexUnsym => 13,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum IndexBase {
Zero,
#[default]
One,
}
pub trait PardisoScalar: Copy + 'static {
const IS_COMPLEX: bool;
}
impl PardisoScalar for f32 {
const IS_COMPLEX: bool = false;
}
impl PardisoScalar for f64 {
const IS_COMPLEX: bool = false;
}
impl PardisoScalar for Complex32 {
const IS_COMPLEX: bool = true;
}
impl PardisoScalar for Complex64 {
const IS_COMPLEX: bool = true;
}
#[derive(Debug)]
pub struct Pardiso<T> {
pt: [*mut core::ffi::c_void; 64],
iparm: [c_int; 64],
mtype: c_int,
msglvl: c_int,
indexing: IndexBase,
perm: Option<Vec<c_int>>,
initialized: bool,
factorized: bool,
factorized_n: c_int,
_marker: PhantomData<T>,
}
unsafe impl<T> Send for Pardiso<T> {}
impl<T: PardisoScalar> Pardiso<T> {
#[must_use]
pub fn new(mtype: PardisoMatrixType) -> Self {
let mtype_is_complex = matches!(
mtype,
PardisoMatrixType::ComplexStructSym
| PardisoMatrixType::ComplexHpd
| PardisoMatrixType::ComplexHermIndefinite
| PardisoMatrixType::ComplexSym
| PardisoMatrixType::ComplexUnsym
);
assert_eq!(
mtype_is_complex,
T::IS_COMPLEX,
"scalar type and matrix type disagree on real-vs-complex",
);
let mut pt: [*mut core::ffi::c_void; 64] = [ptr::null_mut(); 64];
let mut iparm: [c_int; 64] = [0; 64];
let mtype_int = mtype.as_int();
unsafe {
sys::pardisoinit(
pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
&mtype_int,
iparm.as_mut_ptr(),
);
}
Self {
pt,
iparm,
mtype: mtype_int,
msglvl: 0,
indexing: IndexBase::One,
perm: None,
initialized: true,
factorized: false,
factorized_n: 0,
_marker: PhantomData,
}
}
#[must_use]
pub fn with_indexing(mut self, indexing: IndexBase) -> Self {
self.indexing = indexing;
self
}
#[must_use]
pub fn with_message_level(mut self, level: i32) -> Self {
self.msglvl = level;
self
}
#[inline]
pub fn iparm(&mut self) -> &mut [c_int; 64] {
&mut self.iparm
}
pub fn set_perm(&mut self, perm: Option<Vec<c_int>>) {
self.perm = perm;
}
#[inline]
pub fn perm(&self) -> Option<&[c_int]> {
self.perm.as_deref()
}
pub fn analyze_and_factorize(
&mut self,
n: usize,
a: &[T],
ia: &[i32],
ja: &[i32],
) -> Result<()> {
self.run_phase(12, n, a, ia, ja, 0, &[], &mut [])
}
pub fn solve(
&mut self,
n: usize,
a: &[T],
ia: &[i32],
ja: &[i32],
b: &[T],
x: &mut [T],
) -> Result<()> {
let nrhs = (b.len() / n).max(1);
let phase = if self.factorized && self.factorized_n as usize == n {
33
} else {
13
};
self.run_phase(phase, n, a, ia, ja, nrhs as i32, b, x)
}
pub fn solve_multi(
&mut self,
n: usize,
nrhs: i32,
a: &[T],
ia: &[i32],
ja: &[i32],
b: &[T],
x: &mut [T],
) -> Result<()> {
let phase = if self.factorized && self.factorized_n as usize == n {
33
} else {
13
};
self.run_phase(phase, n, a, ia, ja, nrhs, b, x)
}
pub fn release_factorization(&mut self) -> Result<()> {
let dummy_a: [T; 0] = [];
let dummy_i: [i32; 0] = [];
self.run_phase(0, 0, &dummy_a, &dummy_i, &dummy_i, 0, &[], &mut [])?;
self.factorized = false;
Ok(())
}
#[must_use]
pub fn with_diagonal_enabled(mut self) -> Self {
self.iparm[55] = 1;
self
}
pub fn get_diagonal(&mut self, n: usize) -> Result<(Vec<T>, Vec<T>)>
where
T: Default,
{
if !self.factorized {
return Err(Error::InvalidArgument(
"matrix must be factorized before get_diagonal",
));
}
if self.iparm[55] != 1 {
return Err(Error::InvalidArgument(
"with_diagonal_enabled must be called before factorization",
));
}
let mut df: Vec<T> = (0..n).map(|_| T::default()).collect();
let mut da: Vec<T> = (0..n).map(|_| T::default()).collect();
let mnum: c_int = 1;
let mut error: c_int = 0;
unsafe {
sys::pardiso_getdiag(
self.pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
df.as_mut_ptr().cast(),
da.as_mut_ptr().cast(),
&mnum,
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
Ok((df, da))
}
pub fn save_handle<P: AsRef<Path>>(&mut self, dir: P) -> Result<()> {
let dir_c = path_to_cstring(dir.as_ref())?;
let mut error: c_int = 0;
unsafe {
sys::pardiso_handle_store(
self.pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
dir_c.as_ptr(),
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
Ok(())
}
pub fn load_handle<P: AsRef<Path>>(&mut self, dir: P) -> Result<()> {
let dir_c = path_to_cstring(dir.as_ref())?;
let mut error: c_int = 0;
unsafe {
sys::pardiso_handle_restore(
self.pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
dir_c.as_ptr(),
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
self.factorized = true;
Ok(())
}
pub fn export(
&mut self,
step: i32,
values: Option<&mut [T]>,
ia: &mut [i32],
ja: Option<&mut [i32]>,
) -> Result<()> {
let step_c: c_int = step;
let mut error: c_int = 0;
let values_ptr = values
.map(|v| v.as_mut_ptr().cast::<core::ffi::c_void>())
.unwrap_or(ptr::null_mut());
let ja_ptr = ja
.map(|j| j.as_mut_ptr())
.unwrap_or(ptr::null_mut());
unsafe {
sys::pardiso_export(
self.pt.as_mut_ptr() as *mut core::ffi::c_void,
values_ptr,
ia.as_mut_ptr(),
ja_ptr,
&step_c,
self.iparm.as_ptr(),
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
Ok(())
}
pub fn delete_handle_files<P: AsRef<Path>>(dir: P) -> Result<()> {
let dir_c = path_to_cstring(dir.as_ref())?;
let mut error: c_int = 0;
unsafe {
sys::pardiso_handle_delete(dir_c.as_ptr(), &mut error);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
Ok(())
}
pub fn reset(&mut self) -> Result<()> {
let dummy_a: [T; 0] = [];
let dummy_i: [i32; 0] = [];
self.run_phase(-1, 0, &dummy_a, &dummy_i, &dummy_i, 0, &[], &mut [])?;
self.initialized = false;
self.factorized = false;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_phase(
&mut self,
phase: i32,
n: usize,
a: &[T],
ia: &[i32],
ja: &[i32],
nrhs: i32,
b: &[T],
x: &mut [T],
) -> Result<()> {
let n_i32: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
let phase_c = phase;
let maxfct: c_int = 1;
let mnum: c_int = 1;
let mut error: c_int = 0;
self.iparm[34] = match self.indexing {
IndexBase::One => 0,
IndexBase::Zero => 1,
};
let mtype = self.mtype;
let perm_ptr: *mut c_int = match self.perm.as_mut() {
Some(p) => p.as_mut_ptr(),
None => ptr::null_mut(),
};
unsafe {
sys::pardiso(
self.pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
&maxfct,
&mnum,
&mtype,
&phase_c,
&n_i32,
a.as_ptr().cast(),
ia.as_ptr(),
ja.as_ptr(),
perm_ptr,
&nrhs,
self.iparm.as_mut_ptr(),
&self.msglvl,
b.as_ptr() as *mut core::ffi::c_void,
x.as_mut_ptr().cast(),
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error));
}
if phase == 22 || phase == 12 || phase == 13 {
self.factorized = true;
self.factorized_n = n_i32;
}
Ok(())
}
}
fn path_to_cstring(p: &Path) -> Result<CString> {
let s = p
.to_str()
.ok_or(Error::InvalidArgument("path is not valid UTF-8"))?;
CString::new(s).map_err(|_| Error::InvalidArgument("path contains a null byte"))
}
pub type PardisoPivotCallback = unsafe extern "C" fn(
aii: *mut f64,
bii: *mut f64,
eps: *mut f64,
) -> core::ffi::c_int;
pub unsafe fn set_pardiso_pivot_callback(
callback: Option<PardisoPivotCallback>,
) -> Option<PardisoPivotCallback> {
unsafe { sys::mkl_set_pardiso_pivot(callback) }
}
#[allow(clippy::too_many_arguments)]
pub fn pardiso_64_raw<T: PardisoScalar>(
pt: &mut [*mut core::ffi::c_void; 64],
maxfct: i64,
mnum: i64,
mtype: i64,
phase: i64,
n: i64,
a: &[T],
ia: &[i64],
ja: &[i64],
perm: Option<&mut [i64]>,
nrhs: i64,
iparm: &mut [i64; 64],
msglvl: i64,
b: &[T],
x: &mut [T],
) -> Result<()> {
let mtype_is_complex = matches!(mtype, 3 | 4 | -4 | 6 | 13);
if mtype_is_complex != T::IS_COMPLEX {
return Err(Error::InvalidArgument(
"scalar type and matrix type disagree on real-vs-complex",
));
}
let perm_ptr: *mut i64 = match perm {
Some(p) => p.as_mut_ptr(),
None => ptr::null_mut(),
};
let mut error: i64 = 0;
unsafe {
sys::pardiso_64(
pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
&maxfct,
&mnum,
&mtype,
&phase,
&n,
a.as_ptr().cast(),
ia.as_ptr(),
ja.as_ptr(),
perm_ptr,
&nrhs,
iparm.as_mut_ptr(),
&msglvl,
b.as_ptr() as *mut core::ffi::c_void,
x.as_mut_ptr().cast(),
&mut error,
);
}
if error != 0 {
return Err(Error::PardisoStatus(error as c_int));
}
Ok(())
}
impl<T> Drop for Pardiso<T> {
fn drop(&mut self) {
if !self.initialized {
return;
}
let phase: c_int = -1;
let maxfct: c_int = 1;
let mnum: c_int = 1;
let n: c_int = 0;
let nrhs: c_int = 0;
let msglvl: c_int = 0;
let mut error: c_int = 0;
unsafe {
sys::pardiso(
self.pt.as_mut_ptr() as sys::_MKL_DSS_HANDLE_t,
&maxfct, &mnum, &self.mtype, &phase, &n,
ptr::null(), ptr::null(), ptr::null(),
ptr::null_mut(), &nrhs,
self.iparm.as_mut_ptr(), &msglvl,
ptr::null_mut(), ptr::null_mut(),
&mut error,
);
}
}
}