Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various refactorings #1470

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
9 changes: 4 additions & 5 deletions nalgebra-glm/src/ext/quaternion_trigonometric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ pub fn quat_angle_axis<T: RealNumber>(angle: T, axis: &TVec3<T>) -> Qua<T> {

/// The rotation axis of a quaternion assumed to be normalized.
pub fn quat_axis<T: RealNumber>(x: &Qua<T>) -> TVec3<T> {
if let Some(a) = UnitQuaternion::from_quaternion(*x).axis() {
a.into_inner()
} else {
TVec3::zeros()
}
UnitQuaternion::from_quaternion(*x)
.axis()
.map(|a| a.into_inner())
.unwrap_or_else(|| TVec3::zeros())
}
8 changes: 3 additions & 5 deletions nalgebra-glm/src/gtx/rotate_vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ use crate::RealNumber;

/// Build the rotation matrix needed to align `normal` and `up`.
pub fn orientation<T: RealNumber>(normal: &TVec3<T>, up: &TVec3<T>) -> TMat4<T> {
if let Some(r) = Rotation3::rotation_between(normal, up) {
r.to_homogeneous()
} else {
TMat4::identity()
}
Rotation3::rotation_between(normal, up)
.map(|r| r.to_homogeneous())
.unwrap_or_else(|| TMat4::identity())
}

/// Rotate a two dimensional vector.
Expand Down
58 changes: 28 additions & 30 deletions nalgebra-sparse/src/cs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,20 +321,19 @@ where
let lane = self.pattern.get_lane(self.current_lane_idx);
let minor_dim = self.pattern.minor_dim();

if let Some(minor_indices) = lane {
let count = minor_indices.len();
let values_in_lane = &self.remaining_values[..count];
self.remaining_values = &self.remaining_values[count..];
self.current_lane_idx += 1;

Some(CsLane {
minor_dim,
minor_indices,
values: values_in_lane,
})
} else {
None
}
let Some(minor_indices) = lane else {
return None;
};
let count = minor_indices.len();
let values_in_lane = &self.remaining_values[..count];
self.remaining_values = &self.remaining_values[count..];
self.current_lane_idx += 1;

Some(CsLane {
minor_dim,
minor_indices,
values: values_in_lane,
})
}
}

Expand Down Expand Up @@ -365,22 +364,21 @@ where
let lane = self.pattern.get_lane(self.current_lane_idx);
let minor_dim = self.pattern.minor_dim();

if let Some(minor_indices) = lane {
let count = minor_indices.len();

let remaining = std::mem::take(&mut self.remaining_values);
let (values_in_lane, remaining) = remaining.split_at_mut(count);
self.remaining_values = remaining;
self.current_lane_idx += 1;

Some(CsLaneMut {
minor_dim,
minor_indices,
values: values_in_lane,
})
} else {
None
}
let Some(minor_indices) = lane else {
return None;
};
let count = minor_indices.len();

let remaining = std::mem::take(&mut self.remaining_values);
let (values_in_lane, remaining) = remaining.split_at_mut(count);
self.remaining_values = remaining;
self.current_lane_idx += 1;

Some(CsLaneMut {
minor_dim,
minor_indices,
values: values_in_lane,
})
}
}

Expand Down
45 changes: 18 additions & 27 deletions nalgebra-sparse/src/csc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,30 +592,27 @@ fn pattern_format_error_to_csc_error(err: SparsityPatternFormatError) -> SparseF
use SparsityPatternFormatError::DuplicateEntry as PatternDuplicateEntry;
use SparsityPatternFormatError::*;

match err {
InvalidOffsetArrayLength => E::from_kind_and_msg(
let (kind, msg) = match err {
InvalidOffsetArrayLength => (
K::InvalidStructure,
"Length of col offset array is not equal to ncols + 1.",
),
InvalidOffsetFirstLast => E::from_kind_and_msg(
InvalidOffsetFirstLast => (
K::InvalidStructure,
"First or last col offset is inconsistent with format specification.",
),
NonmonotonicOffsets => E::from_kind_and_msg(
NonmonotonicOffsets => (
K::InvalidStructure,
"Col offsets are not monotonically increasing.",
),
NonmonotonicMinorIndices => E::from_kind_and_msg(
NonmonotonicMinorIndices => (
K::InvalidStructure,
"Row indices are not monotonically increasing (sorted) within each column.",
),
MinorIndexOutOfBounds => {
E::from_kind_and_msg(K::IndexOutOfBounds, "Row indices are out of bounds.")
}
PatternDuplicateEntry => {
E::from_kind_and_msg(K::DuplicateEntry, "Matrix data contains duplicate entries.")
}
}
MinorIndexOutOfBounds => (K::IndexOutOfBounds, "Row indices are out of bounds."),
PatternDuplicateEntry => (K::DuplicateEntry, "Matrix data contains duplicate entries."),
};
E::from_kind_and_msg(kind, msg)
}

/// Iterator type for iterating over triplets in a CSC matrix.
Expand All @@ -627,7 +624,7 @@ pub struct CscTripletIter<'a, T> {

impl<'a, T> Clone for CscTripletIter<'a, T> {
fn clone(&self) -> Self {
CscTripletIter {
Self {
pattern_iter: self.pattern_iter.clone(),
values_iter: self.values_iter.clone(),
}
Expand All @@ -649,13 +646,10 @@ impl<'a, T> Iterator for CscTripletIter<'a, T> {
type Item = (usize, usize, &'a T);

fn next(&mut self) -> Option<Self::Item> {
let next_entry = self.pattern_iter.next();
let next_value = self.values_iter.next();

match (next_entry, next_value) {
(Some((i, j)), Some(v)) => Some((j, i, v)),
_ => None,
}
self.pattern_iter
.next()
.zip(self.values_iter.next())
.map(|((i, j), v)| (j, i, v))
}
}

Expand All @@ -671,13 +665,10 @@ impl<'a, T> Iterator for CscTripletIterMut<'a, T> {

#[inline]
fn next(&mut self) -> Option<Self::Item> {
let next_entry = self.pattern_iter.next();
let next_value = self.values_mut_iter.next();

match (next_entry, next_value) {
(Some((i, j)), Some(v)) => Some((j, i, v)),
_ => None,
}
self.pattern_iter
.next()
.zip(self.values_mut_iter.next())
.map(|((i, j), v)| (j, i, v))
}
}

Expand Down
24 changes: 9 additions & 15 deletions nalgebra-sparse/src/csr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ pub struct CsrTripletIter<'a, T> {

impl<'a, T> Clone for CsrTripletIter<'a, T> {
fn clone(&self) -> Self {
CsrTripletIter {
Self {
pattern_iter: self.pattern_iter.clone(),
values_iter: self.values_iter.clone(),
}
Expand All @@ -650,13 +650,10 @@ impl<'a, T> Iterator for CsrTripletIter<'a, T> {
type Item = (usize, usize, &'a T);

fn next(&mut self) -> Option<Self::Item> {
let next_entry = self.pattern_iter.next();
let next_value = self.values_iter.next();

match (next_entry, next_value) {
(Some((i, j)), Some(v)) => Some((i, j, v)),
_ => None,
}
self.pattern_iter
.next()
.zip(self.values_iter.next())
.map(|((i, j), v)| (i, j, v))
}
}

Expand All @@ -672,13 +669,10 @@ impl<'a, T> Iterator for CsrTripletIterMut<'a, T> {

#[inline]
fn next(&mut self) -> Option<Self::Item> {
let next_entry = self.pattern_iter.next();
let next_value = self.values_mut_iter.next();

match (next_entry, next_value) {
(Some((i, j)), Some(v)) => Some((i, j, v)),
_ => None,
}
self.pattern_iter
.next()
.zip(self.values_mut_iter.next())
.map(|((i, j), v)| (i, j, v))
}
}

Expand Down
69 changes: 25 additions & 44 deletions nalgebra-sparse/src/io/matrix_market.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,9 @@ pub enum MatrixMarketErrorKind {
}

impl MatrixMarketError {
fn from_kind_and_message(error_type: MatrixMarketErrorKind, message: String) -> Self {
fn from_kind_and_message(error_kind: MatrixMarketErrorKind, message: String) -> Self {
Self {
error_kind: error_type,
error_kind,
message,
}
}
Expand All @@ -260,38 +260,19 @@ impl MatrixMarketError {
impl fmt::Display for MatrixMarketError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Matrix Market error: ")?;
match self.kind() {
MatrixMarketErrorKind::ParsingError => {
write!(f, "ParsingError,")?;
}
MatrixMarketErrorKind::InvalidHeader => {
write!(f, "InvalidHeader,")?;
}
MatrixMarketErrorKind::EntryMismatch => {
write!(f, "EntryMismatch,")?;
}
MatrixMarketErrorKind::TypeMismatch => {
write!(f, "TypeMismatch,")?;
}
MatrixMarketErrorKind::SparseFormatError(_) => {
write!(f, "SparseFormatError,")?;
}
MatrixMarketErrorKind::ZeroError => {
write!(f, "ZeroError,")?;
}
MatrixMarketErrorKind::IOError(_) => {
write!(f, "IOError,")?;
}
MatrixMarketErrorKind::DiagonalError => {
write!(f, "DiagonalError,")?;
}
MatrixMarketErrorKind::NotLowerTriangle => {
write!(f, "NotLowerTriangle,")?;
}
MatrixMarketErrorKind::NonSquare => {
write!(f, "NonSquare,")?;
}
}
let msg = match self.kind() {
MatrixMarketErrorKind::ParsingError => "ParsingError,",
MatrixMarketErrorKind::InvalidHeader => "InvalidHeader,",
MatrixMarketErrorKind::EntryMismatch => "EntryMismatch,",
MatrixMarketErrorKind::TypeMismatch => "TypeMismatch,",
MatrixMarketErrorKind::SparseFormatError(_) => "SparseFormatError,",
MatrixMarketErrorKind::ZeroError => "ZeroError,",
MatrixMarketErrorKind::IOError(_) => "IOError,",
MatrixMarketErrorKind::DiagonalError => "DiagonalError,",
MatrixMarketErrorKind::NotLowerTriangle => "NotLowerTriangle,",
MatrixMarketErrorKind::NonSquare => "NonSquare,",
};
write!(f, "{}", msg)?;
write!(f, " message: {}", self.message)
}
}
Expand Down Expand Up @@ -391,8 +372,8 @@ impl FromStr for Sparsity {
/// Assumes that `word` is already lower case.
fn from_str(word: &str) -> Result<Self, Self::Err> {
match word {
"coordinate" => Ok(Sparsity::Sparse),
"array" => Ok(Sparsity::Dense),
"coordinate" => Ok(Self::Sparse),
"array" => Ok(Self::Dense),
_ => Err(MatrixMarketError::from_kind_and_message(
MatrixMarketErrorKind::ParsingError,
format!("keyword {} is unknown", word),
Expand All @@ -406,10 +387,10 @@ impl FromStr for DataType {
/// Assumes that `word` is already lower case.
fn from_str(word: &str) -> Result<Self, Self::Err> {
match word {
"real" => Ok(DataType::Real),
"complex" => Ok(DataType::Complex),
"integer" => Ok(DataType::Integer),
"pattern" => Ok(DataType::Pattern),
"real" => Ok(Self::Real),
"complex" => Ok(Self::Complex),
"integer" => Ok(Self::Integer),
"pattern" => Ok(Self::Pattern),
_ => Err(MatrixMarketError::from_kind_and_message(
MatrixMarketErrorKind::ParsingError,
format!("keyword {} is unknown", word),
Expand All @@ -423,10 +404,10 @@ impl FromStr for StorageScheme {
/// Assumes that `word` is already lower case.
fn from_str(word: &str) -> Result<Self, Self::Err> {
match word {
"skew-symmetric" => Ok(StorageScheme::Skew),
"general" => Ok(StorageScheme::General),
"symmetric" => Ok(StorageScheme::Symmetric),
"hermitian" => Ok(StorageScheme::Hermitian),
"skew-symmetric" => Ok(Self::Skew),
"general" => Ok(Self::General),
"symmetric" => Ok(Self::Symmetric),
"hermitian" => Ok(Self::Hermitian),
_ => Err(MatrixMarketError::from_kind_and_message(
MatrixMarketErrorKind::ParsingError,
format!("keyword {} is unknown", word),
Expand Down
8 changes: 4 additions & 4 deletions nalgebra-sparse/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ impl<'a, T: Clone + Zero> SparseEntry<'a, T> {
/// stored.
pub fn into_value(self) -> T {
match self {
SparseEntry::NonZero(value) => value.clone(),
SparseEntry::Zero => T::zero(),
Self::NonZero(value) => value.clone(),
Self::Zero => T::zero(),
}
}
}
Expand All @@ -275,8 +275,8 @@ impl<'a, T: Clone + Zero> SparseEntryMut<'a, T> {
/// stored.
pub fn into_value(self) -> T {
match self {
SparseEntryMut::NonZero(value) => value.clone(),
SparseEntryMut::Zero => T::zero(),
Self::NonZero(value) => value.clone(),
Self::Zero => T::zero(),
}
}
}
Loading
Loading