Feature Request: Unpacking Array<[A; N], D> into Array<A, D::Larger>

Abierto
#1,466 5 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
35/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
rust
Área
data

Línea de trabajo

Start by reviewing the Array, Dimension, mapv, raw_dim, strides, and from_shape_vec APIs shown in the proposal, along with existing dimension-changing operations. Determine how the requested unpacking should fit the ndarray API, including the offset and layout cases raised by the example. Done means the proposed Array<[A; N], D> transformation is integrated with documented behavior and coverage for its supported cases.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

In certain scenarios, it is convenient to create a new dimension by unpacking arrays. For example:

let angles = array![0.1, 0.2, 0.3];
let vectors = angles.mapv(|a| [a.cos(), a.sin()]); 
// Here, `vectors` is of type `Array1<[f64; 2]>`, but an `Array2<f64>` is preferred.

To address this, I have written an extension trait:

pub trait ArrayUnpackExt<A, D, const N: usize>
where
    D: Dimension,
{
    fn unpack(self) -> Array<A, D::Larger>;
}

impl<A, D, const N: usize> ArrayUnpackExt<A, D, N> for Array<[A; N], D>
where
    D: Dimension,
{
    fn unpack(self) -> Array<A, D::Larger> {
        assert!(mem::size_of::<[A; N]>() == mem::size_of::<A>() * N);
        let ndim = self.ndim();
        let mut sh = self.raw_dim().insert_axis(Axis(ndim));
        sh[ndim] = N;
        let mut st = D::zeros(ndim);
        self.strides().iter().enumerate().for_each(|(i, &v)| {
            st[i] = (v * (N as isize)) as usize;
        });
        let st = st.insert_axis(Axis(ndim));
        let (vec, off) = self.into_raw_vec_and_offset();
        match off {
            Some(0) => {
                let vec = {
                    let mut vec = mem::ManuallyDrop::new(vec);
                    let ptr = vec.as_mut_ptr() as *mut A;
                    let len = vec.len() * N;
                    let cap = vec.capacity() * N;
                    unsafe { Vec::from_raw_parts(ptr, len, cap) }
                };
                unsafe { Array::from_shape_vec_unchecked(sh.strides(st), vec) }
            }
            _ => unreachable!(), // Unable to handle non-zero offsets even with unsafe code
        }
    }
}

I believe this functionality would be a valuable addition to the ndarray crate, allowing users to easily transform arrays into higher dimensions when needed. I hope you consider embedding this feature into the library.

Thank you for your attention and consideration.

Lenguaje dominante
Rust
Estrellas
4.3k
Forks
391
Métricas de merge de PR
Sin PR fusionados en 30 d

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-ndarray/ndarray

Todos los issues de rust-ndarray/ndarray

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.