diff --git a/src/approximators/mod.rs b/src/approximators/mod.rs index 7aec652..a4bdd7d 100644 --- a/src/approximators/mod.rs +++ b/src/approximators/mod.rs @@ -1,5 +1,5 @@ use error::*; -use projectors::{IndexT, IndexSet}; +use projectors::{IndexSet, IndexT}; use std::collections::HashMap; mod simple; @@ -28,7 +28,9 @@ pub trait Approximator { impl> Approximator for Box { type Value = T::Value; - fn evaluate(&self, input: &I) -> EvaluationResult { (**self).evaluate(input) } + fn evaluate(&self, input: &I) -> EvaluationResult { + (**self).evaluate(input) + } fn update(&mut self, input: &I, update: Self::Value) -> UpdateResult<()> { (**self).update(input, update) diff --git a/src/approximators/multi.rs b/src/approximators/multi.rs index 4561bd4..4619868 100644 --- a/src/approximators/multi.rs +++ b/src/approximators/multi.rs @@ -1,10 +1,10 @@ use approximators::Approximator; use error::AdaptError; -use geometry::{Vector, Matrix}; -use projectors::{Projection, IndexT, IndexSet}; +use geometry::{Matrix, Vector}; +use projectors::{IndexSet, IndexT, Projection}; use std::collections::HashMap; use std::mem::replace; -use {EvaluationResult, UpdateResult, AdaptResult}; +use {AdaptResult, EvaluationResult, UpdateResult}; #[derive(Clone, Serialize, Deserialize)] pub struct Multi { @@ -24,9 +24,8 @@ impl Multi { let n_rows_new = new_rows.len(); // Weight matrix stored in row-major format. - let mut weights = unsafe { - replace(&mut self.weights, Matrix::uninitialized((0, 0))).into_raw_vec() - }; + let mut weights = + unsafe { replace(&mut self.weights, Matrix::uninitialized((0, 0))).into_raw_vec() }; weights.reserve_exact(n_rows_new); @@ -34,7 +33,7 @@ impl Multi { weights.extend(row); } - self.weights = Matrix::from_shape_vec((n_rows+n_rows_new, n_cols), weights).unwrap(); + self.weights = Matrix::from_shape_vec((n_rows + n_rows_new, n_cols), weights).unwrap(); } } @@ -63,7 +62,7 @@ impl Approximator for Multi { let error_matrix = errors.view().into_shape((1, self.weights.cols())).unwrap(); self.weights.scaled_add(1.0 / z, &view.dot(&error_matrix)) - }, + } &Projection::Sparse(ref sparse) => for c in 0..self.weights.cols() { let mut col = self.weights.column_mut(c); let error = errors[c]; @@ -82,25 +81,30 @@ impl Approximator for Multi { let max_index = self.weights.len() + n_nfs - 1; - let new_weights: Result>, _> = new_features.into_iter().map(|(&i, idx)| { - if i > max_index { - Err(AdaptError::Failed) - } else { - Ok((0..n_outputs).map(|c| { - let c = self.weights.column(c); - - idx.iter().fold(0.0, |acc, r| acc + c[*r]) - }).collect()) - } - }).collect(); + let new_weights: Result>, _> = new_features + .into_iter() + .map(|(&i, idx)| { + if i > max_index { + Err(AdaptError::Failed) + } else { + Ok((0..n_outputs) + .map(|c| { + let c = self.weights.column(c); + + idx.iter().fold(0.0, |acc, r| acc + c[*r]) + }) + .collect()) + } + }) + .collect(); match new_weights { Ok(new_weights) => { self.append_weight_rows(new_weights); Ok(n_nfs) - }, - Err(err) => Err(err) + } + Err(err) => Err(err), } } } @@ -113,7 +117,7 @@ mod tests { use approximators::{Approximator, Multi}; use geometry::Vector; use projectors::fixed::{Fourier, TileCoding}; - use std::collections::{HashMap, BTreeSet}; + use std::collections::{BTreeSet, HashMap}; use std::hash::BuildHasherDefault; type SHBuilder = BuildHasherDefault; @@ -168,9 +172,9 @@ mod tests { let c0 = f.weights.column(0); let c1 = f.weights.column(1); - assert_eq!(c0[100], c0[10]/2.0 + c0[90]/2.0); - assert_eq!(c1[100], c1[10]/2.0 + c1[90]/2.0); - }, + assert_eq!(c0[100], c0[10] / 2.0 + c0[90] / 2.0); + assert_eq!(c1[100], c1[10] / 2.0 + c1[90] / 2.0); + } Err(err) => panic!("Simple::adapt failed with AdaptError::{:?}", err), } } diff --git a/src/approximators/simple.rs b/src/approximators/simple.rs index 42f2f95..fe336c2 100644 --- a/src/approximators/simple.rs +++ b/src/approximators/simple.rs @@ -1,10 +1,10 @@ use approximators::Approximator; use error::AdaptError; use geometry::Vector; -use projectors::{Projection, IndexT, IndexSet}; +use projectors::{IndexSet, IndexT, Projection}; use std::collections::HashMap; use std::mem::replace; -use {EvaluationResult, UpdateResult, AdaptResult}; +use {AdaptResult, EvaluationResult, UpdateResult}; #[derive(Clone, Serialize, Deserialize)] pub struct Simple { @@ -19,9 +19,8 @@ impl Simple { } fn extend_weights(&mut self, new_weights: Vec) { - let mut weights = unsafe { - replace(&mut self.weights, Vector::uninitialized((0,))).into_raw_vec() - }; + let mut weights = + unsafe { replace(&mut self.weights, Vector::uninitialized((0,))).into_raw_vec() }; weights.extend(new_weights); @@ -37,7 +36,7 @@ impl Approximator for Simple { &Projection::Dense(ref dense) => self.weights.dot(&(dense / p.z())), &Projection::Sparse(ref sparse) => { sparse.iter().fold(0.0, |acc, idx| acc + self.weights[*idx]) - }, + } }) } @@ -56,13 +55,16 @@ impl Approximator for Simple { let n_nfs = new_features.len(); let max_index = self.weights.len() + n_nfs - 1; - let new_weights: Result, _> = new_features.into_iter().map(|(&i, idx)| { - if i > max_index { - Err(AdaptError::Failed) - } else { - Ok(idx.iter().fold(0.0, |acc, j| acc + self.weights[*j]) / (idx.len() as f64)) - } - }).collect(); + let new_weights: Result, _> = new_features + .into_iter() + .map(|(&i, idx)| { + if i > max_index { + Err(AdaptError::Failed) + } else { + Ok(idx.iter().fold(0.0, |acc, j| acc + self.weights[*j]) / (idx.len() as f64)) + } + }) + .collect(); self.extend_weights(new_weights?); @@ -77,7 +79,7 @@ mod tests { use LFA; use approximators::{Approximator, Simple}; use projectors::fixed::{Fourier, TileCoding}; - use std::collections::{HashMap, BTreeSet}; + use std::collections::{BTreeSet, HashMap}; use std::hash::BuildHasherDefault; type SHBuilder = BuildHasherDefault; @@ -126,8 +128,8 @@ mod tests { Ok(n) => { assert_eq!(n, 1); assert_eq!(f.weights.len(), 101); - assert_eq!(f.weights[100], f.weights[10]/2.0 + f.weights[90]/2.0); - }, + assert_eq!(f.weights[100], f.weights[10] / 2.0 + f.weights[90] / 2.0); + } Err(err) => panic!("Simple::adapt failed with AdaptError::{:?}", err), } } diff --git a/src/lfa.rs b/src/lfa.rs index 2f0cf15..e38ded2 100644 --- a/src/lfa.rs +++ b/src/lfa.rs @@ -1,6 +1,6 @@ -use approximators::{Approximator, Simple, Multi}; +use approximators::{Approximator, Multi, Simple}; use error::*; -use projectors::{Projector, Projection, IndexT, IndexSet}; +use projectors::{IndexSet, IndexT, Projection, Projector}; use std::collections::HashMap; use std::marker::PhantomData; @@ -52,7 +52,8 @@ impl, A: Approximator> Approximator fo } fn update(&mut self, input: &I, update: Self::Value) -> UpdateResult<()> { - self.approximator.update(&self.projector.project(input), update) + self.approximator + .update(&self.projector.project(input), update) } fn adapt(&mut self, new_features: &HashMap) -> AdaptResult { diff --git a/src/lib.rs b/src/lib.rs index dbcf50e..37382b8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ -extern crate rand; -extern crate ndarray; extern crate itertools; +extern crate ndarray; +extern crate rand; pub extern crate spaces as geometry; @@ -14,7 +14,7 @@ mod error; pub use self::error::*; pub mod projectors; -pub use self::projectors::{Projection, Projector, AdaptiveProjector}; +pub use self::projectors::{AdaptiveProjector, Projection, Projector}; pub mod approximators; pub use self::approximators::Approximator; diff --git a/src/projectors/adaptive/ifdd.rs b/src/projectors/adaptive/ifdd.rs index be277a6..002eda6 100644 --- a/src/projectors/adaptive/ifdd.rs +++ b/src/projectors/adaptive/ifdd.rs @@ -1,12 +1,11 @@ -use geometry::{Vector, Space, Card}; -use projectors::{IndexT, IndexSet, Feature, CandidateFeature}; -use {Projection, Projector, AdaptiveProjector}; +use geometry::{Card, Space, Vector}; +use projectors::{CandidateFeature, Feature, IndexSet, IndexT}; +use {AdaptiveProjector, Projection, Projector}; use std::collections::HashMap; use rand::{Rng, ThreadRng, seq::sample_indices}; use itertools::Itertools; - pub struct IFDD> { pub base: P, pub features: Vec, @@ -18,14 +17,16 @@ pub struct IFDD> { impl> IFDD

{ pub fn new(base_projector: P, discovery_threshold: f64) -> Self { let initial_dim: usize = base_projector.dim(); - let mut base_features: Vec = (0..initial_dim).map(|i| Feature { - index: i, - parent_indices: { - let mut index_set = IndexSet::new(); - index_set.insert(i); - index_set - }, - }).collect(); + let mut base_features: Vec = (0..initial_dim) + .map(|i| Feature { + index: i, + parent_indices: { + let mut index_set = IndexSet::new(); + index_set.insert(i); + index_set + }, + }) + .collect(); base_features.reserve(initial_dim); @@ -44,7 +45,8 @@ impl> IFDD

{ let key = self.features[g].union(&self.features[h]); let rel = { let c = self.candidates - .entry(key.clone()).or_insert_with(|| CandidateFeature::new(key.clone())); + .entry(key.clone()) + .or_insert_with(|| CandidateFeature::new(key.clone())); c.relevance += error.abs(); @@ -87,25 +89,29 @@ impl> Space for IFDD

{ sample_indices(&mut rng, d, n).into() } - fn dim(&self) -> usize { self.features.len() } + fn dim(&self) -> usize { + self.features.len() + } - fn card(&self) -> Card { unimplemented!() } + fn card(&self) -> Card { + unimplemented!() + } } impl> Projector<[f64]> for IFDD

{ fn project(&self, input: &[f64]) -> Projection { let mut p = self.base.project(input); - let np: Vec = (self.base.dim()..self.dim()).filter_map(|i| { - - let f = &self.features[i]; - - if f.parent_indices.iter().all(|i| p[*i].abs() < 1e-7) { - Some(i) - } else { - None - } - - }).collect(); + let np: Vec = (self.base.dim()..self.dim()) + .filter_map(|i| { + let f = &self.features[i]; + + if f.parent_indices.iter().all(|i| p[*i].abs() < 1e-7) { + Some(i) + } else { + None + } + }) + .collect(); for i in np.iter() { for j in self.features[*i].parent_indices.iter() { @@ -132,7 +138,7 @@ impl> AdaptiveProjector<[f64]> for IFDD

{ match self.add_feature(f) { Some(nf) => { acc.get_or_insert_with(HashMap::new).insert(nf.0, nf.1); - }, + } None => (), }; @@ -151,12 +157,11 @@ impl> AdaptiveProjector<[f64]> for IFDD

{ } } - #[cfg(test)] mod tests { extern crate seahash; - use projectors::{fixed::TileCoding, adaptive::IFDD}; + use projectors::{adaptive::IFDD, fixed::TileCoding}; use super::*; use std::hash::BuildHasherDefault; @@ -166,16 +171,25 @@ mod tests { impl Space for BaseProjector { type Value = Projection; - fn sample(&self, _: &mut ThreadRng) -> Projection { unimplemented!() } + fn sample(&self, _: &mut ThreadRng) -> Projection { + unimplemented!() + } - fn dim(&self) -> usize { 5 } + fn dim(&self) -> usize { + 5 + } - fn card(&self) -> Card { unimplemented!() } + fn card(&self) -> Card { + unimplemented!() + } } impl Projector<[f64]> for BaseProjector { fn project(&self, input: &[f64]) -> Projection { - input.iter().map(|v| v.round().min(4.0).max(0.0) as usize).collect() + input + .iter() + .map(|v| v.round().min(4.0).max(0.0) as usize) + .collect() } } @@ -183,27 +197,39 @@ mod tests { fn test_discover() { let mut f = IFDD::new(BaseProjector, 10.0); - assert_eq!(f.discover(&vec![0.0, 4.0], 10.0), Some({ - let mut hm = HashMap::new(); - hm.insert(5, [0, 4].iter().cloned().collect()); - hm - })); - assert_eq!(f.features[5], Feature { - index: 5, - parent_indices: [0, 4].iter().cloned().collect(), - }); + assert_eq!( + f.discover(&vec![0.0, 4.0], 10.0), + Some({ + let mut hm = HashMap::new(); + hm.insert(5, [0, 4].iter().cloned().collect()); + hm + }) + ); + assert_eq!( + f.features[5], + Feature { + index: 5, + parent_indices: [0, 4].iter().cloned().collect(), + } + ); assert_eq!(f.discover(&vec![0.0, 3.0], 5.0), None); assert_eq!(f.features.len(), 6); - assert_eq!(f.discover(&vec![0.0, 3.0], 5.0), Some({ - let mut hm = HashMap::new(); - hm.insert(6, [0, 3].iter().cloned().collect()); - hm - })); - assert_eq!(f.features[6], Feature { - index: 6, - parent_indices: [0, 3].iter().cloned().collect(), - }); + assert_eq!( + f.discover(&vec![0.0, 3.0], 5.0), + Some({ + let mut hm = HashMap::new(); + hm.insert(6, [0, 3].iter().cloned().collect()); + hm + }) + ); + assert_eq!( + f.features[6], + Feature { + index: 6, + parent_indices: [0, 3].iter().cloned().collect(), + } + ); } } diff --git a/src/projectors/fixed/fourier.rs b/src/projectors/fixed/fourier.rs index 213faeb..42d46a8 100644 --- a/src/projectors/fixed/fourier.rs +++ b/src/projectors/fixed/fourier.rs @@ -1,4 +1,4 @@ -use geometry::{BoundedSpace, RegularSpace, Space, Card, dimensions::Continuous, norms::l2}; +use geometry::{BoundedSpace, Card, RegularSpace, Space, dimensions::Continuous, norms::l2}; use projectors::{Projection, Projector}; use rand::{ThreadRng, distributions::{IndependentSample, Range}}; use std::f64::consts::PI; @@ -67,9 +67,13 @@ impl Space for Fourier { self.project(&random_input) } - fn dim(&self) -> usize { self.coefficients.len() } + fn dim(&self) -> usize { + self.coefficients.len() + } - fn card(&self) -> Card { Card::Infinite } + fn card(&self) -> Card { + Card::Infinite + } } impl Projector<[f64]> for Fourier { diff --git a/src/projectors/fixed/mod.rs b/src/projectors/fixed/mod.rs index 2daebdb..38819ba 100644 --- a/src/projectors/fixed/mod.rs +++ b/src/projectors/fixed/mod.rs @@ -1,4 +1,4 @@ -///! Linear basis projection module. +/// ! Linear basis projection module. mod rbf_network; pub use self::rbf_network::*; diff --git a/src/projectors/fixed/polynomial/cpfk.rs b/src/projectors/fixed/polynomial/cpfk.rs index e41d6bb..c3b1847 100644 --- a/src/projectors/fixed/polynomial/cpfk.rs +++ b/src/projectors/fixed/polynomial/cpfk.rs @@ -1,18 +1,32 @@ #![allow(dead_code)] -pub(super) fn t_0(_x: f64) -> f64 { 1.0 } +pub(super) fn t_0(_x: f64) -> f64 { + 1.0 +} -pub(super) fn t_1(x: f64) -> f64 { x } +pub(super) fn t_1(x: f64) -> f64 { + x +} -pub(super) fn t_2(x: f64) -> f64 { 2.0 * x * x - 1.0 } +pub(super) fn t_2(x: f64) -> f64 { + 2.0 * x * x - 1.0 +} -pub(super) fn t_3(x: f64) -> f64 { 4.0 * x * x * x - 3.0 * x } +pub(super) fn t_3(x: f64) -> f64 { + 4.0 * x * x * x - 3.0 * x +} -pub(super) fn t_4(x: f64) -> f64 { 8.0 * x * x * x * x - 8.0 * x * x + 1.0 } +pub(super) fn t_4(x: f64) -> f64 { + 8.0 * x * x * x * x - 8.0 * x * x + 1.0 +} -pub(super) fn t_5(x: f64) -> f64 { 16.0 * x.powi(5) - 20.0 * x.powi(3) + 5.0 * x } +pub(super) fn t_5(x: f64) -> f64 { + 16.0 * x.powi(5) - 20.0 * x.powi(3) + 5.0 * x +} -pub(super) fn t_6(x: f64) -> f64 { 32.0 * x.powi(6) - 48.0 * x.powi(4) + 18.0 * x.powi(2) - 1.0 } +pub(super) fn t_6(x: f64) -> f64 { + 32.0 * x.powi(6) - 48.0 * x.powi(4) + 18.0 * x.powi(2) - 1.0 +} pub(super) fn t_7(x: f64) -> f64 { 64.0 * x.powi(7) - 112.0 * x.powi(5) + 56.0 * x.powi(3) - 7.0 * x diff --git a/src/projectors/fixed/polynomial/mod.rs b/src/projectors/fixed/polynomial/mod.rs index 4b3ff67..efd588f 100644 --- a/src/projectors/fixed/polynomial/mod.rs +++ b/src/projectors/fixed/polynomial/mod.rs @@ -1,4 +1,4 @@ -use geometry::{BoundedSpace, RegularSpace, Space, Card, Vector, dimensions::Continuous}; +use geometry::{BoundedSpace, Card, RegularSpace, Space, Vector, dimensions::Continuous}; use projectors::{Projection, Projector}; use rand::ThreadRng; use utils::cartesian_product; @@ -45,11 +45,17 @@ impl Polynomial { impl Space for Polynomial { type Value = Projection; - fn sample(&self, _rng: &mut ThreadRng) -> Projection { unimplemented!() } + fn sample(&self, _rng: &mut ThreadRng) -> Projection { + unimplemented!() + } - fn dim(&self) -> usize { self.exponents.len() } + fn dim(&self) -> usize { + self.exponents.len() + } - fn card(&self) -> Card { Card::Infinite } + fn card(&self) -> Card { + Card::Infinite + } } impl Projector<[f64]> for Polynomial { @@ -138,11 +144,17 @@ impl Chebyshev { impl Space for Chebyshev { type Value = Projection; - fn sample(&self, _rng: &mut ThreadRng) -> Projection { unimplemented!() } + fn sample(&self, _rng: &mut ThreadRng) -> Projection { + unimplemented!() + } - fn dim(&self) -> usize { self.polynomials.len() } + fn dim(&self) -> usize { + self.polynomials.len() + } - fn card(&self) -> Card { Card::Infinite } + fn card(&self) -> Card { + Card::Infinite + } } impl Projector<[f64]> for Chebyshev { diff --git a/src/projectors/fixed/rbf_network.rs b/src/projectors/fixed/rbf_network.rs index f9f5ff5..2afec69 100644 --- a/src/projectors/fixed/rbf_network.rs +++ b/src/projectors/fixed/rbf_network.rs @@ -1,10 +1,9 @@ -use geometry::{Matrix, RegularSpace, Space, Card, Vector, dimensions::Partitioned}; +use geometry::{Card, Matrix, RegularSpace, Space, Vector, dimensions::Partitioned}; use ndarray::Axis; use projectors::{Projection, Projector}; use rand::ThreadRng; use utils::cartesian_product; - /// Radial basis function network projector. #[derive(Clone, Serialize, Deserialize)] pub struct RBFNetwork { @@ -65,15 +64,23 @@ impl RBFNetwork { impl Space for RBFNetwork { type Value = Projection; - fn sample(&self, _rng: &mut ThreadRng) -> Projection { unimplemented!() } + fn sample(&self, _rng: &mut ThreadRng) -> Projection { + unimplemented!() + } - fn dim(&self) -> usize { self.mu.rows() } + fn dim(&self) -> usize { + self.mu.rows() + } - fn card(&self) -> Card { Card::Infinite } + fn card(&self) -> Card { + Card::Infinite + } } impl Projector<[f64]> for RBFNetwork { - fn project(&self, input: &[f64]) -> Projection { Projection::Dense(self.kernel(input)) } + fn project(&self, input: &[f64]) -> Projection { + Projection::Dense(self.kernel(input)) + } } #[cfg(test)] @@ -83,7 +90,9 @@ mod tests { #[test] fn test_dimensionality() { - fn get_dim(rbf_net: RBFNetwork) -> usize { rbf_net.dim() } + fn get_dim(rbf_net: RBFNetwork) -> usize { + rbf_net.dim() + } assert_eq!(get_dim(RBFNetwork::new(arr2(&[[0.0]]), arr1(&[0.25]))), 1); assert_eq!( @@ -102,7 +111,9 @@ mod tests { #[test] fn test_cardinality() { - fn get_card(rbf_net: RBFNetwork) -> Card { rbf_net.card() } + fn get_card(rbf_net: RBFNetwork) -> Card { + rbf_net.card() + } assert_eq!( get_card(RBFNetwork::new(arr2(&[[0.0]]), arr1(&[0.25]))), diff --git a/src/projectors/fixed/tile_coding.rs b/src/projectors/fixed/tile_coding.rs index a82300a..fb04c32 100644 --- a/src/projectors/fixed/tile_coding.rs +++ b/src/projectors/fixed/tile_coding.rs @@ -1,4 +1,4 @@ -use geometry::{Space, Card}; +use geometry::{Card, Space}; use projectors::{Projection, Projector}; use rand::{ThreadRng, seq::sample_indices}; use std::hash::{BuildHasher, Hasher}; @@ -17,8 +17,7 @@ fn hash_state( state: &[usize], n_tilings: usize, memory_size: usize, -) -> Vec -{ +) -> Vec { let state_len = state.len(); (0..n_tilings) @@ -58,9 +57,13 @@ impl Space for TileCoding { sample_indices(&mut rng, self.memory_size, self.n_tilings).into() } - fn dim(&self) -> usize { self.memory_size } + fn dim(&self) -> usize { + self.memory_size + } - fn card(&self) -> Card { unimplemented!() } + fn card(&self) -> Card { + unimplemented!() + } } impl Projector<[f64]> for TileCoding { diff --git a/src/projectors/fixed/uniform_grid.rs b/src/projectors/fixed/uniform_grid.rs index c93a773..700e7e6 100644 --- a/src/projectors/fixed/uniform_grid.rs +++ b/src/projectors/fixed/uniform_grid.rs @@ -1,8 +1,7 @@ -use geometry::{RegularSpace, Space, Card, Surjection, dimensions::Partitioned}; +use geometry::{Card, RegularSpace, Space, Surjection, dimensions::Partitioned}; use projectors::{Projection, Projector}; use rand::{ThreadRng, seq::sample_indices}; - /// Fixed uniform basis projector. #[derive(Clone, Serialize, Deserialize)] pub struct UniformGrid { @@ -38,13 +37,19 @@ impl Space for UniformGrid { sample_indices(&mut rng, self.n_features, 1).into() } - fn dim(&self) -> usize { self.n_features } + fn dim(&self) -> usize { + self.n_features + } - fn card(&self) -> Card { unimplemented!() } + fn card(&self) -> Card { + unimplemented!() + } } impl Projector<[f64]> for UniformGrid { - fn project(&self, input: &[f64]) -> Projection { vec![self.hash(input)].into() } + fn project(&self, input: &[f64]) -> Projection { + vec![self.hash(input)].into() + } } #[cfg(test)] @@ -79,7 +84,7 @@ mod tests { Projection::Sparse(ref idx) => { assert_eq!(idx.len(), 1); assert!(idx.contains(&expected_bin)); - }, + } _ => assert!(false), } @@ -106,7 +111,7 @@ mod tests { Projection::Sparse(ref idx) => { assert_eq!(idx.len(), 1); assert!(idx.contains(&expected_bin)); - }, + } _ => assert!(false), } @@ -135,7 +140,7 @@ mod tests { Projection::Sparse(ref idx) => { assert_eq!(idx.len(), 1); assert!(idx.contains(&expected_bin)); - }, + } _ => assert!(false), } diff --git a/src/projectors/mod.rs b/src/projectors/mod.rs index 9ca5163..8be3baf 100644 --- a/src/projectors/mod.rs +++ b/src/projectors/mod.rs @@ -13,7 +13,7 @@ mod projection; pub use self::projection::Projection; mod feature; -pub use self::feature::{Feature, CandidateFeature}; +pub use self::feature::{CandidateFeature, Feature}; pub mod adaptive; pub mod fixed; @@ -26,7 +26,9 @@ pub trait Projector: Space { /// Project data from an input space onto the basis and convert into a raw, /// dense vector. - fn project_expanded(&self, input: &I) -> DenseT { self.project(input).expanded(self.dim()) } + fn project_expanded(&self, input: &I) -> DenseT { + self.project(input).expanded(self.dim()) + } } /// Trait for projectors with adaptive bases. @@ -36,7 +38,9 @@ pub trait AdaptiveProjector: Projector { } impl> Projector> for P { - fn project(&self, input: &Vec) -> Projection { Projector::<[f64]>::project(self, &input) } + fn project(&self, input: &Vec) -> Projection { + Projector::<[f64]>::project(self, &input) + } } macro_rules! impl_fixed { diff --git a/src/projectors/projection.rs b/src/projectors/projection.rs index 180a3e1..eabb141 100644 --- a/src/projectors/projection.rs +++ b/src/projectors/projection.rs @@ -1,8 +1,8 @@ use geometry::{Vector, norms::l1}; -use ndarray::{Axis, stack}; +use ndarray::{stack, Axis}; use std::iter::FromIterator; use std::ops::{Add, Index}; -use super::{ActivationT, IndexT, DenseT, SparseT, IndexSet}; +use super::{ActivationT, DenseT, IndexSet, IndexT, SparseT}; /// Projected feature vector representation. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -23,7 +23,7 @@ impl Projection { &mut Dense(ref mut activations) => activations[idx] = 0.0, &mut Sparse(ref mut active_indices) => { active_indices.remove(&idx); - }, + } } } @@ -93,8 +93,10 @@ impl PartialEq for Projection { (&Sparse(ref idx1), &Sparse(ref idx2)) => idx1.eq(&idx2), (&Dense(ref act1), &Dense(ref act2)) => act1.eq(&act2), - _ => unimplemented!("Cannot check equality of dense/sparse with no knowledge of the \ - full dimensionality of sparse projection.") + _ => unimplemented!( + "Cannot check equality of dense/sparse with no knowledge of the \ + full dimensionality of sparse projection." + ), } } } @@ -107,11 +109,14 @@ impl Add for Projection { match (self, rhs) { (Sparse(idx1), Sparse(idx2)) => Sparse(idx1.union(&idx2).cloned().collect()), - (Dense(act1), Dense(act2)) => - Dense(stack(Axis(0), &[act1.view(), act2.view()]).unwrap()), + (Dense(act1), Dense(act2)) => { + Dense(stack(Axis(0), &[act1.view(), act2.view()]).unwrap()) + } - _ => unimplemented!("Cannot combine dense/sparse with no knowledge of the full \ - dimensionality of sparse projection.") + _ => unimplemented!( + "Cannot combine dense/sparse with no knowledge of the full \ + dimensionality of sparse projection." + ), } } } @@ -122,36 +127,47 @@ impl Index for Projection { fn index(&self, idx: usize) -> &f64 { match self { &Projection::Dense(ref activations) => activations.index(idx), - &Projection::Sparse(ref active_indices) => - if idx < active_indices.len() { &1.0 } else { &0.0 }, + &Projection::Sparse(ref active_indices) => if idx < active_indices.len() { + &1.0 + } else { + &0.0 + }, } } } impl Into for DenseT { - fn into(self) -> Projection { Projection::Dense(self) } + fn into(self) -> Projection { + Projection::Dense(self) + } } impl Into for Vec { - fn into(self) -> Projection { Projection::Dense(Vector::from_vec(self)) } + fn into(self) -> Projection { + Projection::Dense(Vector::from_vec(self)) + } } impl FromIterator for Projection { - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { Projection::Dense(Vector::from_iter(iter)) } } impl Into for SparseT { - fn into(self) -> Projection { Projection::Sparse(self) } + fn into(self) -> Projection { + Projection::Sparse(self) + } } impl Into for Vec { - fn into(self) -> Projection { Projection::from_iter(self.into_iter()) } + fn into(self) -> Projection { + Projection::from_iter(self.into_iter()) + } } impl FromIterator for Projection { - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { Projection::Sparse({ let mut is = IndexSet::new(); diff --git a/src/utils.rs b/src/utils.rs index c30acb5..a050050 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -23,7 +23,7 @@ pub(crate) fn cartesian_product(lists: &Vec>) -> Vec> { rest.iter() .cloned() .fold(init, |vec, list| partial_cartesian(vec, &list)) - }, + } None => vec![], } }