Skip to content

Commit

Permalink
Replace compare_floats function
Browse files Browse the repository at this point in the history
  • Loading branch information
reinterpretcat committed Oct 3, 2024
1 parent b8ef397 commit cf9d1ec
Show file tree
Hide file tree
Showing 50 changed files with 94 additions and 193 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ are already published. So, I stick to it for now.
* apply some performance optimizations
* refactor dbscan clustering api

### Removed

* replace `compare_floats` with built-in `total_cmp`


## [1.24.0] 2024-07-13

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;
use itertools::{Itertools, MinMaxResult};
use rosomaxa::prelude::{compare_floats, compare_floats_refs, Float};
use rosomaxa::prelude::Float;
use std::cmp::Ordering;

/// Draws rosomaxa population state.
Expand Down Expand Up @@ -35,10 +35,8 @@ pub(crate) fn draw_on_area<B: DrawingBackend + 'static>(
series: &Series2D|
-> DrawResult<()> {
let matrix: MatrixData = (series.matrix_fn)();
let (min, max, size) = match matrix.iter().minmax_by(|(_, &a), (_, &b)| compare_floats(a, b)) {
MinMaxResult::OneElement((_, &value)) if compare_floats(value, 0.) != Ordering::Equal => {
(value, value, value)
}
let (min, max, size) = match matrix.iter().minmax_by(|(_, a), (_, b)| a.total_cmp(b)) {
MinMaxResult::OneElement((_, &value)) if value != 0. => (value, value, value),
MinMaxResult::MinMax((_, &min), (_, &max)) => (min, max, max - min),
_ => (1., 1., 1.),
};
Expand Down Expand Up @@ -91,7 +89,7 @@ pub(crate) fn draw_on_area<B: DrawingBackend + 'static>(
let compare_fitness = |left: &[Float], right: &[Float]| {
(left.iter())
.zip(right.iter())
.map(|(lhs, rhs)| compare_floats_refs(lhs, rhs))
.map(|(lhs, rhs)| lhs.total_cmp(rhs))
.find_or_first(|ord| *ord != Ordering::Equal)
.unwrap_or(Ordering::Equal)
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;
use plotters::style::full_palette::BLUE_200;
use rosomaxa::prelude::{compare_floats_refs, Float};
use rosomaxa::prelude::Float;

const TOP_SIZE: usize = 25;

Expand Down Expand Up @@ -59,7 +59,7 @@ fn draw_bar_plot<B: DrawingBackend + 'static>(
) -> DrawResult<()> {
area.fill(&WHITE)?;

let max_x = data.iter().copied().max_by(compare_floats_refs).unwrap_or(1.);
let max_x = data.iter().copied().max_by(|a, b| a.total_cmp(b)).unwrap_or(1.);
let max_y = data.len() - 1;
// TODO: improve font size detection
let font_size = if max_y < TOP_SIZE { 16 } else { 6 };
Expand Down
9 changes: 3 additions & 6 deletions rosomaxa/src/algorithms/gsom/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ where

/// Returns max unified distance of the network.
pub fn max_unified_distance(&self) -> Float {
self.get_nodes().map(|node| node.unified_distance(self, 1)).max_by(compare_floats_refs).unwrap_or(0.)
self.get_nodes().map(|node| node.unified_distance(self, 1)).max_by(|a, b| a.total_cmp(b)).unwrap_or(0.)
}

/// Trains network on an input.
Expand Down Expand Up @@ -243,10 +243,7 @@ where
}

let node = self.nodes.get(coord).unwrap();
(
matches!(compare_floats(node.error, self.growing_threshold), Ordering::Equal | Ordering::Greater),
node.is_boundary(self) && is_new_input,
)
(node.error >= self.growing_threshold, node.is_boundary(self) && is_new_input)
};

match (exceeds_ae, can_grow) {
Expand Down Expand Up @@ -444,7 +441,7 @@ where
fn compare_input<I: Input>(left: &I, right: &I) -> Ordering {
(left.weights().iter())
.zip(right.weights().iter())
.map(|(lhs, rhs)| compare_floats_refs(lhs, rhs))
.map(|(lhs, rhs)| lhs.total_cmp(rhs))
.find(|ord| *ord != Ordering::Equal)
.unwrap_or(Ordering::Equal)
}
Expand Down
4 changes: 1 addition & 3 deletions rosomaxa/src/algorithms/math/distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
mod distance_test;

use crate::prelude::Float;
use crate::utils::compare_floats;
use std::cmp::Ordering;

/// Calculates relative distance between two vectors. As weights are not normalized, apply
/// standardization using relative change: D = |x - y| / max(|x|, |y|)
Expand All @@ -16,7 +14,7 @@ where
a.zip(b)
.fold(Float::default(), |acc, (a, b)| {
let divider = a.abs().max(b.abs());
let change = if compare_floats(divider, 0.) == Ordering::Equal { 0. } else { (a - b).abs() / divider };
let change = if divider == 0. { 0. } else { (a - b).abs() / divider };

acc + change * change
})
Expand Down
4 changes: 1 addition & 3 deletions rosomaxa/src/algorithms/math/statistics.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use crate::prelude::Float;
use crate::utils::compare_floats;
use std::cmp::Ordering;

/// Returns coefficient variation.
pub fn get_cv(values: &[Float]) -> Float {
let (variance, mean) = get_variance_mean(values);
if compare_floats(mean, 0.) == Ordering::Equal {
if mean == 0. {
return 0.;
}
let sdev = variance.sqrt();
Expand Down
3 changes: 1 addition & 2 deletions rosomaxa/src/evolution/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::algorithms::math::relative_distance;
use crate::prelude::*;
use crate::utils::Timer;
use crate::{DynHeuristicPopulation, RemedianUsize};
use std::cmp::Ordering;
use std::fmt::Write;
use std::marker::PhantomData;

Expand Down Expand Up @@ -414,7 +413,7 @@ impl SpeedTracker {
_ => 1.,
};

let is_slow = compare_floats(ratio, 1.) == Ordering::Less;
let is_slow = ratio < 1.;
let median = self.median.approx_median();

self.speed = match &self.speed {
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl HeuristicObjective for VectorObjective {
type Solution = VectorSolution;

fn total_order(&self, a: &Self::Solution, b: &Self::Solution) -> Ordering {
a.fitness().next().zip(b.fitness().next()).map(|(a, b)| compare_floats(a, b)).expect("expecting fitness")
a.fitness().next().zip(b.fitness().next()).map(|(a, b)| a.total_cmp(&b)).expect("expecting fitness")
}
}

Expand Down
6 changes: 3 additions & 3 deletions rosomaxa/src/hyper/dynamic_selective.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod dynamic_selective_test;
use super::*;
use crate::algorithms::math::RemedianUsize;
use crate::algorithms::rl::{SlotAction, SlotFeedback, SlotMachine};
use crate::utils::{compare_floats, random_argmax, DefaultDistributionSampler};
use crate::utils::{random_argmax, DefaultDistributionSampler};
use crate::Timer;
use std::cmp::Ordering;
use std::collections::HashMap;
Expand Down Expand Up @@ -350,7 +350,7 @@ where
let distance_best = get_relative_distance(objective, new_solution, best_known);

// NOTE remap distances to range [0, 2]
match (compare_floats(distance_initial, 0.), compare_floats(distance_best, 0.)) {
match (distance_initial.total_cmp(&0.), distance_best.total_cmp(&0.)) {
(Ordering::Greater, Ordering::Greater) => {
(distance_initial + 1.) + (distance_best + 1.) * BEST_DISCOVERY_REWARD_MULTIPLIER
}
Expand Down Expand Up @@ -417,7 +417,7 @@ where
.fitness()
.zip(b.fitness())
.enumerate()
.find(|(_, (fitness_a, fitness_b))| compare_floats_refs(fitness_a, fitness_b) != Ordering::Equal)
.find(|(_, (fitness_a, fitness_b))| fitness_a != fitness_b)
.map(|(idx, _)| idx);

let idx = if let Some(idx) = idx {
Expand Down
5 changes: 1 addition & 4 deletions rosomaxa/src/population/elitism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,7 @@ where

fn is_improved(&self, best_known_fitness: Option<Vec<Float>>) -> bool {
best_known_fitness.zip(self.individuals.first()).map_or(true, |(best_known_fitness, new_best_known)| {
best_known_fitness
.into_iter()
.zip(new_best_known.fitness())
.any(|(a, b)| compare_floats(a, b) != Ordering::Equal)
best_known_fitness.into_iter().zip(new_best_known.fitness()).any(|(a, b)| a != b)
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/population/rosomaxa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ where
let fitness_a = a.fitness();
let fitness_b = b.fitness();

fitness_a.zip(fitness_b).all(|(a, b)| compare_floats(a, b) == Ordering::Equal)
fitness_a.zip(fitness_b).all(|(a, b)| a == b)
}
_ => {
let weights_a = a.weights();
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ pub use crate::hyper::HyperHeuristic;

pub use crate::termination::Termination;

pub use crate::utils::short_type_name;
pub use crate::utils::DefaultRandom;
pub use crate::utils::Environment;
pub use crate::utils::Float;
pub use crate::utils::InfoLogger;
pub use crate::utils::Noise;
pub use crate::utils::Quota;
pub use crate::utils::UnwrapValue;
pub use crate::utils::{compare_floats, compare_floats_refs, short_type_name};
pub use crate::utils::{GenericError, GenericResult};
pub use crate::utils::{Random, RandomGen};
2 changes: 1 addition & 1 deletion rosomaxa/src/termination/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,6 @@ where
}

fn estimate(&self, heuristic_ctx: &Self::Context) -> Float {
self.terminations.iter().map(|t| t.estimate(heuristic_ctx)).max_by(compare_floats_refs).unwrap_or(0.)
self.terminations.iter().map(|t| t.estimate(heuristic_ctx)).max_by(|a, b| a.total_cmp(b)).unwrap_or(0.)
}
}
27 changes: 0 additions & 27 deletions rosomaxa/src/utils/comparison.rs

This file was deleted.

3 changes: 0 additions & 3 deletions rosomaxa/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
//! This module contains helper functionality.

mod comparison;
pub use self::comparison::*;

mod environment;
pub use self::environment::*;

Expand Down
5 changes: 2 additions & 3 deletions rosomaxa/tests/unit/algorithms/gsom/network_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ type NetworkType = Network<Data, DataStorage, DataStorageFactory>;
mod common {
use super::*;
use crate::helpers::algorithms::gsom::create_test_network;
use crate::utils::{compare_floats, DefaultRandom};
use std::cmp::Ordering;
use crate::utils::DefaultRandom;

#[test]
fn can_train_network() {
Expand Down Expand Up @@ -112,7 +111,7 @@ mod common {
// -1-1 0-1 +1-1
assert_eq!(network.nodes.len(), 9);
network.nodes.iter().filter(|(coord, _)| **coord != Coordinate(0, 0)).for_each(|(coord, node)| {
if compare_floats(node.error, 42.) != Ordering::Equal {
if node.error != 42. {
unreachable!("node is not updated: ({},{}), value: {}", coord.0, coord.1, node.error);
}
});
Expand Down
6 changes: 2 additions & 4 deletions rosomaxa/tests/unit/evolution/telemetry_test.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use super::*;
use crate::example::*;
use crate::helpers::example::create_example_objective;
use crate::utils::compare_floats;
use crate::{get_default_population, get_default_selection_size};
use std::cmp::Ordering;
use std::sync::Arc;

fn compare_statistic(statistics: &HeuristicStatistics, expected: (usize, Float, Float)) {
assert_eq!(statistics.generation, expected.0);
assert_eq!(compare_floats(statistics.improvement_all_ratio, expected.1), Ordering::Equal);
assert_eq!(compare_floats(statistics.improvement_1000_ratio, expected.2), Ordering::Equal);
assert_eq!(statistics.improvement_all_ratio, expected.1);
assert_eq!(statistics.improvement_1000_ratio, expected.2);
}

#[test]
Expand Down
5 changes: 2 additions & 3 deletions vrp-core/src/algorithms/geometry/point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
#[path = "../../../tests/unit/algorithms/geometry/point_test.rs"]
mod point_test;

use rosomaxa::prelude::{compare_floats, Float};
use std::cmp::Ordering;
use rosomaxa::prelude::Float;
use std::hash::{Hash, Hasher};

/// Represents a point in 2D space.
Expand Down Expand Up @@ -33,7 +32,7 @@ impl Point {
pub fn distance_to_line(&self, a: &Point, b: &Point) -> Float {
let a_b_distance = a.distance_to_point(b);

if compare_floats(a_b_distance, 0.) == Ordering::Equal {
if a_b_distance == 0. {
0.
} else {
(Self::cross_product(a, b, self) / a_b_distance).abs()
Expand Down
5 changes: 2 additions & 3 deletions vrp-core/src/construction/clustering/dbscan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use crate::models::common::Profile;
use crate::models::problem::{Job, Single};
use crate::prelude::{Cost, Fleet};
use rosomaxa::prelude::*;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::sync::Arc;

Expand Down Expand Up @@ -82,8 +81,8 @@ where
costs.iter_mut().for_each(|cost| *cost /= fleet.profiles.len() as Float);

// sort all distances in ascending order
costs.sort_unstable_by(compare_floats_refs);
costs.dedup_by(|a, b| compare_floats(*a, *b) == Ordering::Equal);
costs.sort_unstable_by(|a, b| a.total_cmp(b));
costs.dedup_by(|a, b| a == b);

costs
}
Expand Down
5 changes: 2 additions & 3 deletions vrp-core/src/construction/clustering/vicinity/estimations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ fn get_dissimilarities(
outer_time.overlapping(inner_time).map(|tw| tw.duration())
})
})
.max_by(compare_floats_refs)
.max_by(|a, b| a.total_cmp(b))
.unwrap_or(0.);

if shared_time > min_shared_time {
Expand All @@ -151,8 +151,7 @@ fn get_dissimilarities(
let bck_distance = transport.distance_approx(&config.profile, inner_loc, outer_loc);
let bck_duration = transport.duration_approx(&config.profile, inner_loc, outer_loc);

let reachable = compare_floats(fwd_distance, 0.) != Ordering::Less
&& compare_floats(bck_distance, 0.) != Ordering::Less;
let reachable = fwd_distance >= 0. && bck_distance >= 0.;

let reachable = reachable
&& (fwd_duration - config.threshold.moving_duration < 0.)
Expand Down
10 changes: 5 additions & 5 deletions vrp-core/src/construction/enablers/departure_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use crate::construction::enablers::*;
use crate::construction::heuristics::RouteContext;
use crate::models::common::Timestamp;
use crate::models::problem::{ActivityCost, TransportCost, TravelTime};
use rosomaxa::prelude::{compare_floats, Float};
use std::cmp::Ordering;
use rosomaxa::prelude::Float;

/// Tries to move forward route's departure time.
pub fn advance_departure_time(
Expand Down Expand Up @@ -93,8 +92,9 @@ fn try_recede_departure_time(route_ctx: &RouteContext) -> Option<Timestamp> {
.map(|(&total, &limit)| (limit - total).min(max_change))
.unwrap_or(max_change);

match compare_floats(max_change, 0.) {
Ordering::Greater => Some(start.schedule.departure - max_change),
_ => None,
if max_change > 0. {
Some(start.schedule.departure - max_change)
} else {
None
}
}
8 changes: 3 additions & 5 deletions vrp-core/src/construction/enablers/reserved_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ mod reserved_time_test;
use crate::models::common::*;
use crate::models::problem::{ActivityCost, Actor, TransportCost, TravelTime};
use crate::models::solution::{Activity, Route};
use rosomaxa::prelude::{compare_floats, Float, GenericError};
use std::cmp::Ordering;
use rosomaxa::prelude::{Float, GenericError};
use std::collections::HashMap;
use std::sync::Arc;

Expand Down Expand Up @@ -204,7 +203,7 @@ pub(crate) fn create_reserved_times_fn(
(TimeSpan::Offset(a), TimeSpan::Offset(b)) => (a.start, b.start),
_ => unreachable!(),
};
compare_floats(a, b)
a.total_cmp(&b)
});
let has_no_intersections = times.windows(2).all(|pair| {
if let [ReservedTimeSpan { time: a, .. }, ReservedTimeSpan { time: b, .. }] = pair {
Expand Down Expand Up @@ -260,8 +259,7 @@ pub(crate) fn create_reserved_times_fn(
};

// NOTE use exclusive intersection
compare_floats(interval_start, reserved_end) == Ordering::Less
&& compare_floats(reserved_start, interval_end) == Ordering::Less
interval_start < reserved_end && reserved_start < interval_end
})
})
.flatten(),
Expand Down
Loading

0 comments on commit cf9d1ec

Please sign in to comment.