Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 5 additions & 25 deletions Cargo.lock.MSRV

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ optional = true
default-features = false

[dependencies.kdtree]
version = "0.7.0"
version = "0.8.1"
optional = true

[dev-dependencies]
Expand Down
4 changes: 2 additions & 2 deletions src/density/kde.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use kdtree::distance::squared_euclidean;

use crate::{
density::{Container, DensityError, nearest_neighbors},
density::{Container, DensityError, nearest_neighbors, neighborhood_radius},
function::kernel::{Gaussian, Kernel},
};

Expand Down Expand Up @@ -30,7 +30,7 @@ where
if neighbors.is_empty() {
Err(DensityError::EmptyNeighborhood)
} else {
let radius = neighbors.last().unwrap().sqrt(); // safe to unwrap here since `neighbors` is not empty
let radius = neighborhood_radius(&neighbors).unwrap();
let d = x.length() as i32;
Ok((1. / (n_samples * radius.powi(d)))
* samples
Expand Down
4 changes: 2 additions & 2 deletions src/density/knn.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::Container;
use crate::{
density::{DensityError, nearest_neighbors},
density::{DensityError, nearest_neighbors, neighborhood_radius},
function::gamma::gamma,
};
use core::f64::consts::PI;
Expand Down Expand Up @@ -30,7 +30,7 @@ where
if neighbors.is_empty() {
Err(DensityError::EmptyNeighborhood)
} else {
let radius = neighbors.last().unwrap().sqrt();
let radius = neighborhood_radius(&neighbors).unwrap();
let d = x.length() as f64;
Ok((k / n_samples) * (gamma(d / 2. + 1.) / (PI.powf(d / 2.) * radius.powf(d))))
}
Expand Down
13 changes: 13 additions & 0 deletions src/density/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ impl_container!(
);
pub type NearestNeighbors = (Vec<f64>, f64);

pub(crate) fn neighborhood_radius(neighbors: &[f64]) -> Option<f64> {
neighbors
.iter()
.copied()
.max_by(f64::total_cmp)
.map(f64::sqrt)
}

pub(crate) fn nearest_neighbors<S, X>(
x: &X,
samples: &S,
Expand Down Expand Up @@ -118,6 +126,11 @@ mod tests {

use super::*;

#[test]
fn neighborhood_radius_uses_farthest_distance() {
assert_eq!(neighborhood_radius(&[4.0, 1.0, 9.0, 2.0]), Some(3.0));
}

#[test]
fn test_vec_container() {
let v1 = vec![1.0, 2.0, 3.0];
Expand Down