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

未關閉
#1,466 5 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
35/100
Issue 類型
功能
描述清晰度
基本清楚
活躍度
停滯
技術堆疊
rust
領域
data

研究方向

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.

由索引模型根據 Issue 內容生成。

描述

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.

主要語言
Rust
星號
4.3k
分支
391
PR 合併指標
30 天內沒有已合併 PR

貢獻指南

這個儲存庫沒有索引到貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

rust-ndarray/ndarray 的其他 Issue

查看 rust-ndarray/ndarray 的全部 Issue

相似的 Issue

更多 Rust Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。