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
//! Permutation matrices.
#![allow(clippy::len_without_is_empty)]
use crate::{temp_mat_req, temp_mat_uninit, zipped, ComplexField, Entity, MatMut, MatRef};
use assert2::{assert, debug_assert};
use dyn_stack::{DynStack, SizeOverflow, StackReq};
use reborrow::*;
/// Swaps the two columns at indices `a` and `b` in the given matrix.
///
/// # Panics
///
/// Panics if either `a` or `b` is out of bounds.
///
/// # Example
///
/// ```
/// use faer_core::{mat, permutation::swap_cols};
///
/// let mut m = mat![
/// [1.0, 2.0, 3.0],
/// [4.0, 5.0, 6.0],
/// [7.0, 8.0, 9.0],
/// [10.0, 14.0, 12.0],
/// ];
///
/// swap_cols(m.as_mut(), 0, 2);
///
/// let swapped = mat![
/// [3.0, 2.0, 1.0],
/// [6.0, 5.0, 4.0],
/// [9.0, 8.0, 7.0],
/// [12.0, 14.0, 10.0],
/// ];
///
/// assert_eq!(m, swapped);
/// ```
#[track_caller]
#[inline]
pub fn swap_cols<E: ComplexField>(mat: MatMut<'_, E>, a: usize, b: usize) {
assert!(a < mat.ncols());
assert!(b < mat.ncols());
if a == b {
return;
}
let mat = mat.into_const();
let mat_a = mat.subcols(a, 1);
let mat_b = mat.subcols(b, 1);
unsafe {
zipped!(mat_a.const_cast(), mat_b.const_cast()).for_each(|mut a, mut b| {
let (a_read, b_read) = (a.read(), b.read());
a.write(b_read);
b.write(a_read);
});
}
}
/// Swaps the two rows at indices `a` and `b` in the given matrix.
///
/// # Panics
///
/// Panics if either `a` or `b` is out of bounds.
///
/// # Example
///
/// ```
/// use faer_core::{mat, permutation::swap_rows};
///
/// let mut m = mat![
/// [1.0, 2.0, 3.0],
/// [4.0, 5.0, 6.0],
/// [7.0, 8.0, 9.0],
/// [10.0, 14.0, 12.0],
/// ];
///
/// swap_rows(m.as_mut(), 0, 2);
///
/// let swapped = mat![
/// [7.0, 8.0, 9.0],
/// [4.0, 5.0, 6.0],
/// [1.0, 2.0, 3.0],
/// [10.0, 14.0, 12.0],
/// ];
///
/// assert_eq!(m, swapped);
/// ```
#[track_caller]
#[inline]
pub fn swap_rows<E: ComplexField>(mat: MatMut<'_, E>, a: usize, b: usize) {
swap_cols(mat.transpose(), a, b)
}
#[derive(Clone, Copy, Debug)]
pub struct PermutationRef<'a> {
forward: &'a [usize],
inverse: &'a [usize],
}
impl<'a> PermutationRef<'a> {
/// Returns the permutation as an array.
#[inline]
pub fn into_arrays(self) -> (&'a [usize], &'a [usize]) {
(self.forward, self.inverse)
}
#[inline]
pub fn len(&self) -> usize {
debug_assert!(self.inverse.len() == self.forward.len());
self.forward.len()
}
/// Returns the inverse permutation.
#[inline]
pub fn inverse(self) -> Self {
Self {
forward: self.inverse,
inverse: self.forward,
}
}
/// Creates a new permutation reference, without checking the validity of the inputs.
///
/// # Safety
///
/// `forward` and `inverse` must have the same length, be valid permutations, and be inverse
/// permutations of each other.
#[inline]
pub unsafe fn new_unchecked(forward: &'a [usize], inverse: &'a [usize]) -> Self {
Self { forward, inverse }
}
}
impl<'a> PermutationMut<'a> {
/// Returns the permutation as an array.
#[inline]
pub unsafe fn into_arrays(self) -> (&'a mut [usize], &'a mut [usize]) {
(self.forward, self.inverse)
}
#[inline]
pub fn len(&self) -> usize {
debug_assert!(self.inverse.len() == self.forward.len());
self.forward.len()
}
/// Returns the inverse permutation.
#[inline]
pub fn inverse(self) -> Self {
Self {
forward: self.inverse,
inverse: self.forward,
}
}
/// Creates a new permutation mutable reference, without checking the validity of the inputs.
///
/// # Safety
///
/// `forward` and `inverse` must have the same length, be valid permutations, and be inverse
/// permutations of each other.
#[inline]
pub unsafe fn new_unchecked(forward: &'a mut [usize], inverse: &'a mut [usize]) -> Self {
Self { forward, inverse }
}
}
#[derive(Debug)]
pub struct PermutationMut<'a> {
forward: &'a mut [usize],
inverse: &'a mut [usize],
}
impl<'short, 'a> Reborrow<'short> for PermutationRef<'a> {
type Target = PermutationRef<'short>;
#[inline]
fn rb(&'short self) -> Self::Target {
*self
}
}
impl<'short, 'a> ReborrowMut<'short> for PermutationRef<'a> {
type Target = PermutationRef<'short>;
#[inline]
fn rb_mut(&'short mut self) -> Self::Target {
*self
}
}
impl<'short, 'a> Reborrow<'short> for PermutationMut<'a> {
type Target = PermutationRef<'short>;
#[inline]
fn rb(&'short self) -> Self::Target {
PermutationRef {
forward: &*self.forward,
inverse: &*self.inverse,
}
}
}
impl<'short, 'a> ReborrowMut<'short> for PermutationMut<'a> {
type Target = PermutationMut<'short>;
#[inline]
fn rb_mut(&'short mut self) -> Self::Target {
PermutationMut {
forward: &mut *self.forward,
inverse: &mut *self.inverse,
}
}
}
/// Computes a permutation of the columns of the source matrix using the given permutation, and
/// stores the result in the destination matrix.
///
/// # Panics
///
/// - Panics if the matrices do not have the same shape.
/// - Panics if the size of the permutation doesn't match the number of columns of the matrices.
#[inline]
#[track_caller]
pub fn permute_cols<E: ComplexField>(
dst: MatMut<'_, E>,
src: MatRef<'_, E>,
perm_indices: PermutationRef<'_>,
) {
assert!((src.nrows(), src.ncols()) == (dst.nrows(), dst.ncols()));
assert!(perm_indices.into_arrays().0.len() == src.ncols());
permute_rows(dst.transpose(), src.transpose(), perm_indices);
}
/// Computes a permutation of the rows of the source matrix using the given permutation, and
/// stores the result in the destination matrix.
///
/// # Panics
///
/// - Panics if the matrices do not have the same shape.
/// - Panics if the size of the permutation doesn't match the number of rows of the matrices.
#[inline]
#[track_caller]
pub fn permute_rows<E: ComplexField>(
dst: MatMut<'_, E>,
src: MatRef<'_, E>,
perm_indices: PermutationRef<'_>,
) {
assert!((src.nrows(), src.ncols()) == (dst.nrows(), dst.ncols()));
assert!(perm_indices.into_arrays().0.len() == src.nrows());
let src = src;
let perm_indices = perm_indices;
let mut dst = dst;
let m = src.nrows();
let n = src.ncols();
let perm = perm_indices.into_arrays().0;
if dst.row_stride().abs() < dst.col_stride().abs() {
for j in 0..n {
for i in 0..m {
unsafe {
dst.rb_mut().write_unchecked(
i,
j,
src.read_unchecked(*perm.get_unchecked(i), j),
);
}
}
}
} else {
for i in 0..m {
unsafe {
let src_i = src.subrows(*perm.get_unchecked(i), 1);
let dst_i = dst.rb_mut().subrows(i, 1);
zipped!(dst_i, src_i).for_each(|mut dst, src| dst.write(src.read()));
}
}
}
}
/// Computes the size and alignment of required workspace for applying a row permutation to a
/// matrix in place.
pub fn permute_rows_in_place_req<E: Entity>(
nrows: usize,
ncols: usize,
) -> Result<StackReq, SizeOverflow> {
temp_mat_req::<E>(nrows, ncols)
}
/// Computes the size and alignment of required workspace for applying a column permutation to a
/// matrix in place.
pub fn permute_cols_in_place_req<E: Entity>(
nrows: usize,
ncols: usize,
) -> Result<StackReq, SizeOverflow> {
temp_mat_req::<E>(nrows, ncols)
}
/// Computes a permutation of the rows of the matrix using the given permutation, and
/// stores the result in the same matrix.
///
/// # Panics
///
/// - Panics if the size of the permutation doesn't match the number of rows of the matrix.
#[inline]
#[track_caller]
pub fn permute_rows_in_place<E: ComplexField>(
matrix: MatMut<'_, E>,
perm_indices: PermutationRef<'_>,
stack: DynStack<'_>,
) {
let mut matrix = matrix;
let (mut tmp, _) = unsafe { temp_mat_uninit::<E>(matrix.nrows(), matrix.ncols(), stack) };
let mut tmp = tmp.as_mut();
zipped!(tmp.rb_mut(), matrix.rb()).for_each(|mut dst, src| dst.write(src.read()));
permute_rows(matrix.rb_mut(), tmp.rb(), perm_indices);
}
/// Computes a permutation of the columns of the matrix using the given permutation, and
/// stores the result in the same matrix.
///
/// # Panics
///
/// - Panics if the size of the permutation doesn't match the number of columns of the matrix.
#[inline]
#[track_caller]
pub fn permute_cols_in_place<E: ComplexField>(
matrix: MatMut<'_, E>,
perm_indices: PermutationRef<'_>,
stack: DynStack<'_>,
) {
let mut matrix = matrix;
let (mut tmp, _) = unsafe { temp_mat_uninit::<E>(matrix.nrows(), matrix.ncols(), stack) };
let mut tmp = tmp.as_mut();
zipped!(tmp.rb_mut(), matrix.rb()).for_each(|mut dst, src| dst.write(src.read()));
permute_cols(matrix.rb_mut(), tmp.rb(), perm_indices);
}