Skip to content

Commit

Permalink
'distinct': re-arrange the sequence of colors after optimization, see #…
Browse files Browse the repository at this point in the history
  • Loading branch information
sharkdp committed Aug 25, 2019
1 parent 11aa07a commit ccc617a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/cli/commands/distinct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::commands::show::show_color;

use pastel::ansi::Stream;
use pastel::distinct::{
DistanceMetric, IterationStatistics, OptimizationMode, OptimizationTarget, SimulatedAnnealing,
SimulationParameters,
self, DistanceMetric, IterationStatistics, OptimizationMode, OptimizationTarget,
SimulatedAnnealing, SimulationParameters,
};
use pastel::random::{self, RandomizationStrategy};

Expand Down Expand Up @@ -108,7 +108,10 @@ impl GenericCommand for DistinctCommand {

annealing.run(callback.as_mut());

for color in annealing.get_colors() {
let mut colors = annealing.get_colors();
distinct::rearrange_sequence(&mut colors, distance_metric);

for color in colors {
show_color(out, config, &color)?;
}

Expand Down
45 changes: 45 additions & 0 deletions src/distinct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,48 @@ impl SimulatedAnnealing {
}
}
}

/// Re-arrange the sequence of colors such that the minimal difference between a given color and
/// any of its predecessors is maximized.
pub fn rearrange_sequence(colors: &mut Vec<Color>, metric: DistanceMetric) {
let distance = |c1: &Color, c2: &Color| match metric {
DistanceMetric::CIE76 => c1.distance_delta_e_cie76(c2),
DistanceMetric::CIEDE2000 => c1.distance_delta_e_ciede2000(c2),
};

for i in 1..colors.len() {
let (left, right) = colors.split_at_mut(i);
right
.sort_unstable_by_key(|c| left.iter().map(|c2| (-distance(c2, c) * 100.0) as i32).max());
}
}

#[cfg(test)]
mod tests {
use super::{rearrange_sequence, DistanceMetric};
use crate::Color;

#[test]
fn test_rearrange_sequence() {
let mut colors = vec![
Color::white(),
Color::graytone(0.25),
Color::graytone(0.5),
Color::graytone(0.8),
Color::black(),
];

rearrange_sequence(&mut colors, DistanceMetric::CIE76);

assert_eq!(
colors,
vec![
Color::white(),
Color::black(),
Color::graytone(0.5),
Color::graytone(0.25),
Color::graytone(0.8),
]
);
}
}

0 comments on commit ccc617a

Please sign in to comment.