将数据从文件读入GenericArray

时间:2016-10-19 12:30:18

标签: arrays generics rust traits

我在Rust中使用generic_array crate。我想要固定长度数组,所以Vec不合适,但我希望在运行时定义数组的长度,因此使用此包而不是array

代码用于聚类算法,其中每个通用数组代表一个数据点。我希望数据具有任何维度。例如,如果我在图像上聚类像素,我可能会有3D数据,每个颜色通道一个;但我不希望代码只能用于3D数据。

我遇到了将CSV文件中的数据读入通用数组的问题。在使用通用数组之前,我有一个派生自RustcDecodable

的2D结构

如何最好地将文件中的数据读入GenericArray?我无法为Decodableas the Decodable trait is external实现GenericArray特征。

以下是我只允许2D数据时代码的样子:

use std::path::Path;

extern crate csv;
extern crate rustc_serialize;

/// Store one data point's (or one cluster centroid's) x and y co-ordinates
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct DataPoint {
    pub x: f64,
    pub y: f64,
}

impl DataPoint {

    pub fn squared_euclidean_distance(&self, other: &DataPoint) -> f64 {
        (other.x - self.x).powi(2) + (other.y - self.y).powi(2)
    }
}

pub fn read_data<P>(file_path: P) -> Vec<DataPoint>
    where P: AsRef<Path>
{
    let mut reader = csv::Reader::from_file(file_path).unwrap();
    reader.decode().map(|point| point.unwrap()).collect()
}

以下是我的代码与GenericArray s(减去read_data函数)的代码:

extern crate generic_array;

trait Euclidean<N> {
    fn squared_euclidean_distance(&self, other: &generic_array::GenericArray<f64, N>) -> f64
        where N: generic_array::ArrayLength<f64>;
}


impl <N> Euclidean<N> for generic_array::GenericArray<f64, N>
    where N: generic_array::ArrayLength<f64>
{
    fn squared_euclidean_distance(&self, other: &generic_array::GenericArray<f64, N>) -> f64
        where N: generic_array::ArrayLength<f64>
    {
        let iter = self.iter().zip(other.iter());
        iter.fold(0.0, |acc, x| acc + (x.0 - x.1).powi(2))
    }
}

我应该将数据读入中间数据,然后进入GenericArray吗?我应该定义自己的Decodable特征版本吗?我应该放弃通用数组吗?

0 个答案:

没有答案